Bug Summary

File:build/source/clang/lib/Sema/SemaTemplateInstantiate.cpp
Warning:line 1271, column 15
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateInstantiate.cpp -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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/clang/lib/Sema/SemaTemplateInstantiate.cpp

/build/source/clang/lib/Sema/SemaTemplateInstantiate.cpp

1//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
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 C++ template instantiation.
9//
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
13#include "clang/AST/ASTConcept.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprConcepts.h"
22#include "clang/AST/PrettyDeclStackTrace.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeVisitor.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/Stack.h"
27#include "clang/Basic/TargetInfo.h"
28#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/EnterExpressionEvaluationContext.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Sema.h"
33#include "clang/Sema/SemaConcept.h"
34#include "clang/Sema/SemaInternal.h"
35#include "clang/Sema/Template.h"
36#include "clang/Sema/TemplateDeduction.h"
37#include "clang/Sema/TemplateInstCallback.h"
38#include "llvm/ADT/ScopeExit.h"
39#include "llvm/Support/ErrorHandling.h"
40#include "llvm/Support/TimeProfiler.h"
41#include <optional>
42
43using namespace clang;
44using namespace sema;
45
46//===----------------------------------------------------------------------===/
47// Template Instantiation Support
48//===----------------------------------------------------------------------===/
49
50namespace {
51namespace TemplateInstArgsHelpers {
52struct Response {
53 const Decl *NextDecl = nullptr;
54 bool IsDone = false;
55 bool ClearRelativeToPrimary = true;
56 static Response Done() {
57 Response R;
58 R.IsDone = true;
59 return R;
60 }
61 static Response ChangeDecl(const Decl *ND) {
62 Response R;
63 R.NextDecl = ND;
64 return R;
65 }
66 static Response ChangeDecl(const DeclContext *Ctx) {
67 Response R;
68 R.NextDecl = Decl::castFromDeclContext(Ctx);
69 return R;
70 }
71
72 static Response UseNextDecl(const Decl *CurDecl) {
73 return ChangeDecl(CurDecl->getDeclContext());
74 }
75
76 static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {
77 Response R = Response::UseNextDecl(CurDecl);
78 R.ClearRelativeToPrimary = false;
79 return R;
80 }
81};
82// Add template arguments from a variable template instantiation.
83Response
84HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,
85 MultiLevelTemplateArgumentList &Result,
86 bool SkipForSpecialization) {
87 // For a class-scope explicit specialization, there are no template arguments
88 // at this level, but there may be enclosing template arguments.
89 if (VarTemplSpec->isClassScopeExplicitSpecialization())
90 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
91
92 // We're done when we hit an explicit specialization.
93 if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
94 !isa<VarTemplatePartialSpecializationDecl>(VarTemplSpec))
95 return Response::Done();
96
97 // If this variable template specialization was instantiated from a
98 // specialized member that is a variable template, we're done.
99 assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?")(static_cast <bool> (VarTemplSpec->getSpecializedTemplate
() && "No variable template?") ? void (0) : __assert_fail
("VarTemplSpec->getSpecializedTemplate() && \"No variable template?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 99, __extension__
__PRETTY_FUNCTION__))
;
100 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
101 Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();
102 if (VarTemplatePartialSpecializationDecl *Partial =
103 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
104 if (!SkipForSpecialization)
105 Result.addOuterTemplateArguments(
106 Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
107 /*Final=*/false);
108 if (Partial->isMemberSpecialization())
109 return Response::Done();
110 } else {
111 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
112 if (!SkipForSpecialization)
113 Result.addOuterTemplateArguments(
114 Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
115 /*Final=*/false);
116 if (Tmpl->isMemberSpecialization())
117 return Response::Done();
118 }
119 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
120}
121
122// If we have a template template parameter with translation unit context,
123// then we're performing substitution into a default template argument of
124// this template template parameter before we've constructed the template
125// that will own this template template parameter. In this case, we
126// use empty template parameter lists for all of the outer templates
127// to avoid performing any substitutions.
128Response
129HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,
130 MultiLevelTemplateArgumentList &Result) {
131 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
132 Result.addOuterTemplateArguments(std::nullopt);
133 return Response::Done();
134}
135
136Response HandlePartialClassTemplateSpec(
137 const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec,
138 MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) {
139 if (!SkipForSpecialization)
140 Result.addOuterRetainedLevels(PartialClassTemplSpec->getTemplateDepth());
141 return Response::Done();
142}
143
144// Add template arguments from a class template instantiation.
145Response
146HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,
147 MultiLevelTemplateArgumentList &Result,
148 bool SkipForSpecialization) {
149 if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {
150 // We're done when we hit an explicit specialization.
151 if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
152 !isa<ClassTemplatePartialSpecializationDecl>(ClassTemplSpec))
153 return Response::Done();
154
155 if (!SkipForSpecialization)
156 Result.addOuterTemplateArguments(
157 const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),
158 ClassTemplSpec->getTemplateInstantiationArgs().asArray(),
159 /*Final=*/false);
160
161 // If this class template specialization was instantiated from a
162 // specialized member that is a class template, we're done.
163 assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?")(static_cast <bool> (ClassTemplSpec->getSpecializedTemplate
() && "No class template?") ? void (0) : __assert_fail
("ClassTemplSpec->getSpecializedTemplate() && \"No class template?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 163, __extension__
__PRETTY_FUNCTION__))
;
164 if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())
165 return Response::Done();
166 }
167 return Response::UseNextDecl(ClassTemplSpec);
168}
169
170Response HandleFunction(const FunctionDecl *Function,
171 MultiLevelTemplateArgumentList &Result,
172 const FunctionDecl *Pattern, bool RelativeToPrimary,
173 bool ForConstraintInstantiation) {
174 // Add template arguments from a function template specialization.
175 if (!RelativeToPrimary &&
176 Function->getTemplateSpecializationKindForInstantiation() ==
177 TSK_ExplicitSpecialization)
178 return Response::Done();
179
180 if (!RelativeToPrimary &&
181 Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
182 // This is an implicit instantiation of an explicit specialization. We
183 // don't get any template arguments from this function but might get
184 // some from an enclosing template.
185 return Response::UseNextDecl(Function);
186 } else if (const TemplateArgumentList *TemplateArgs =
187 Function->getTemplateSpecializationArgs()) {
188 // Add the template arguments for this specialization.
189 Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function),
190 TemplateArgs->asArray(),
191 /*Final=*/false);
192
193 // If this function was instantiated from a specialized member that is
194 // a function template, we're done.
195 assert(Function->getPrimaryTemplate() && "No function template?")(static_cast <bool> (Function->getPrimaryTemplate() &&
"No function template?") ? void (0) : __assert_fail ("Function->getPrimaryTemplate() && \"No function template?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 195, __extension__
__PRETTY_FUNCTION__))
;
196 if (Function->getPrimaryTemplate()->isMemberSpecialization())
197 return Response::Done();
198
199 // If this function is a generic lambda specialization, we are done.
200 if (!ForConstraintInstantiation &&
201 isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function))
202 return Response::Done();
203
204 } else if (Function->getDescribedFunctionTemplate()) {
205 assert((static_cast <bool> ((ForConstraintInstantiation || Result
.getNumSubstitutedLevels() == 0) && "Outer template not instantiated?"
) ? void (0) : __assert_fail ("(ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && \"Outer template not instantiated?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 207, __extension__
__PRETTY_FUNCTION__))
206 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&(static_cast <bool> ((ForConstraintInstantiation || Result
.getNumSubstitutedLevels() == 0) && "Outer template not instantiated?"
) ? void (0) : __assert_fail ("(ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && \"Outer template not instantiated?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 207, __extension__
__PRETTY_FUNCTION__))
207 "Outer template not instantiated?")(static_cast <bool> ((ForConstraintInstantiation || Result
.getNumSubstitutedLevels() == 0) && "Outer template not instantiated?"
) ? void (0) : __assert_fail ("(ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && \"Outer template not instantiated?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 207, __extension__
__PRETTY_FUNCTION__))
;
208 }
209 // If this is a friend or local declaration and it declares an entity at
210 // namespace scope, take arguments from its lexical parent
211 // instead of its semantic parent, unless of course the pattern we're
212 // instantiating actually comes from the file's context!
213 if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
214 Function->getNonTransparentDeclContext()->isFileContext() &&
215 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
216 return Response::ChangeDecl(Function->getLexicalDeclContext());
217 }
218 return Response::UseNextDecl(Function);
219}
220
221Response HandleFunctionTemplateDecl(const FunctionTemplateDecl *FTD,
222 MultiLevelTemplateArgumentList &Result) {
223 if (!isa<ClassTemplateSpecializationDecl>(FTD->getDeclContext())) {
224 NestedNameSpecifier *NNS = FTD->getTemplatedDecl()->getQualifier();
225 const Type *Ty;
226 const TemplateSpecializationType *TSTy;
227 if (NNS && (Ty = NNS->getAsType()) &&
228 (TSTy = Ty->getAs<TemplateSpecializationType>()))
229 Result.addOuterTemplateArguments(const_cast<FunctionTemplateDecl *>(FTD),
230 TSTy->template_arguments(),
231 /*Final=*/false);
232 }
233 return Response::ChangeDecl(FTD->getLexicalDeclContext());
234}
235
236Response HandleRecordDecl(const CXXRecordDecl *Rec,
237 MultiLevelTemplateArgumentList &Result,
238 ASTContext &Context,
239 bool ForConstraintInstantiation) {
240 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
241 assert((static_cast <bool> ((ForConstraintInstantiation || Result
.getNumSubstitutedLevels() == 0) && "Outer template not instantiated?"
) ? void (0) : __assert_fail ("(ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && \"Outer template not instantiated?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 243, __extension__
__PRETTY_FUNCTION__))
242 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&(static_cast <bool> ((ForConstraintInstantiation || Result
.getNumSubstitutedLevels() == 0) && "Outer template not instantiated?"
) ? void (0) : __assert_fail ("(ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && \"Outer template not instantiated?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 243, __extension__
__PRETTY_FUNCTION__))
243 "Outer template not instantiated?")(static_cast <bool> ((ForConstraintInstantiation || Result
.getNumSubstitutedLevels() == 0) && "Outer template not instantiated?"
) ? void (0) : __assert_fail ("(ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && \"Outer template not instantiated?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 243, __extension__
__PRETTY_FUNCTION__))
;
244 if (ClassTemplate->isMemberSpecialization())
245 return Response::Done();
246 if (ForConstraintInstantiation)
247 Result.addOuterTemplateArguments(const_cast<CXXRecordDecl *>(Rec),
248 ClassTemplate->getInjectedTemplateArgs(),
249 /*Final=*/false);
250 }
251
252 bool IsFriend = Rec->getFriendObjectKind() ||
253 (Rec->getDescribedClassTemplate() &&
254 Rec->getDescribedClassTemplate()->getFriendObjectKind());
255 if (ForConstraintInstantiation && IsFriend &&
256 Rec->getNonTransparentDeclContext()->isFileContext()) {
257 return Response::ChangeDecl(Rec->getLexicalDeclContext());
258 }
259
260 // This is to make sure we pick up the VarTemplateSpecializationDecl that this
261 // lambda is defined inside of.
262 if (Rec->isLambda())
263 if (const Decl *LCD = Rec->getLambdaContextDecl())
264 return Response::ChangeDecl(LCD);
265
266 return Response::UseNextDecl(Rec);
267}
268
269Response HandleImplicitConceptSpecializationDecl(
270 const ImplicitConceptSpecializationDecl *CSD,
271 MultiLevelTemplateArgumentList &Result) {
272 Result.addOuterTemplateArguments(
273 const_cast<ImplicitConceptSpecializationDecl *>(CSD),
274 CSD->getTemplateArguments(),
275 /*Final=*/false);
276 return Response::UseNextDecl(CSD);
277}
278
279Response HandleGenericDeclContext(const Decl *CurDecl) {
280 return Response::UseNextDecl(CurDecl);
281}
282} // namespace TemplateInstArgsHelpers
283} // namespace
284
285/// Retrieve the template argument list(s) that should be used to
286/// instantiate the definition of the given declaration.
287///
288/// \param ND the declaration for which we are computing template instantiation
289/// arguments.
290///
291/// \param Innermost if non-NULL, specifies a template argument list for the
292/// template declaration passed as ND.
293///
294/// \param RelativeToPrimary true if we should get the template
295/// arguments relative to the primary template, even when we're
296/// dealing with a specialization. This is only relevant for function
297/// template specializations.
298///
299/// \param Pattern If non-NULL, indicates the pattern from which we will be
300/// instantiating the definition of the given declaration, \p ND. This is
301/// used to determine the proper set of template instantiation arguments for
302/// friend function template specializations.
303///
304/// \param ForConstraintInstantiation when collecting arguments,
305/// ForConstraintInstantiation indicates we should continue looking when
306/// encountering a lambda generic call operator, and continue looking for
307/// arguments on an enclosing class template.
308
309MultiLevelTemplateArgumentList Sema::getTemplateInstantiationArgs(
310 const NamedDecl *ND, bool Final, const TemplateArgumentList *Innermost,
311 bool RelativeToPrimary, const FunctionDecl *Pattern,
312 bool ForConstraintInstantiation, bool SkipForSpecialization) {
313 assert(ND && "Can't find arguments for a decl if one isn't provided")(static_cast <bool> (ND && "Can't find arguments for a decl if one isn't provided"
) ? void (0) : __assert_fail ("ND && \"Can't find arguments for a decl if one isn't provided\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 313, __extension__
__PRETTY_FUNCTION__))
;
314 // Accumulate the set of template argument lists in this structure.
315 MultiLevelTemplateArgumentList Result;
316
317 using namespace TemplateInstArgsHelpers;
318 const Decl *CurDecl = ND;
319 if (Innermost) {
320 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND),
321 Innermost->asArray(), Final);
322 CurDecl = Response::UseNextDecl(ND).NextDecl;
323 }
324
325 while (!CurDecl->isFileContextDecl()) {
326 Response R;
327 if (const auto *VarTemplSpec =
328 dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
329 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
330 } else if (const auto *PartialClassTemplSpec =
331 dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) {
332 R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,
333 SkipForSpecialization);
334 } else if (const auto *ClassTemplSpec =
335 dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
336 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
337 SkipForSpecialization);
338 } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
339 R = HandleFunction(Function, Result, Pattern, RelativeToPrimary,
340 ForConstraintInstantiation);
341 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
342 R = HandleRecordDecl(Rec, Result, Context, ForConstraintInstantiation);
343 } else if (const auto *CSD =
344 dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
345 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
346 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) {
347 R = HandleFunctionTemplateDecl(FTD, Result);
348 } else if (!isa<DeclContext>(CurDecl)) {
349 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
350 if (CurDecl->getDeclContext()->isTranslationUnit()) {
351 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
352 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
353 }
354 }
355 } else {
356 R = HandleGenericDeclContext(CurDecl);
357 }
358
359 if (R.IsDone)
360 return Result;
361 if (R.ClearRelativeToPrimary)
362 RelativeToPrimary = false;
363 assert(R.NextDecl)(static_cast <bool> (R.NextDecl) ? void (0) : __assert_fail
("R.NextDecl", "clang/lib/Sema/SemaTemplateInstantiate.cpp",
363, __extension__ __PRETTY_FUNCTION__))
;
364 CurDecl = R.NextDecl;
365 }
366
367 return Result;
368}
369
370bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
371 switch (Kind) {
372 case TemplateInstantiation:
373 case ExceptionSpecInstantiation:
374 case DefaultTemplateArgumentInstantiation:
375 case DefaultFunctionArgumentInstantiation:
376 case ExplicitTemplateArgumentSubstitution:
377 case DeducedTemplateArgumentSubstitution:
378 case PriorTemplateArgumentSubstitution:
379 case ConstraintsCheck:
380 case NestedRequirementConstraintsCheck:
381 return true;
382
383 case RequirementInstantiation:
384 case RequirementParameterInstantiation:
385 case DefaultTemplateArgumentChecking:
386 case DeclaringSpecialMember:
387 case DeclaringImplicitEqualityComparison:
388 case DefiningSynthesizedFunction:
389 case ExceptionSpecEvaluation:
390 case ConstraintSubstitution:
391 case ParameterMappingSubstitution:
392 case ConstraintNormalization:
393 case RewritingOperatorAsSpaceship:
394 case InitializingStructuredBinding:
395 case MarkingClassDllexported:
396 case BuildingBuiltinDumpStructCall:
397 case LambdaExpressionSubstitution:
398 return false;
399
400 // This function should never be called when Kind's value is Memoization.
401 case Memoization:
402 break;
403 }
404
405 llvm_unreachable("Invalid SynthesisKind!")::llvm::llvm_unreachable_internal("Invalid SynthesisKind!", "clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 405)
;
406}
407
408Sema::InstantiatingTemplate::InstantiatingTemplate(
409 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
410 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
411 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
412 sema::TemplateDeductionInfo *DeductionInfo)
413 : SemaRef(SemaRef) {
414 // Don't allow further instantiation if a fatal error and an uncompilable
415 // error have occurred. Any diagnostics we might have raised will not be
416 // visible, and we do not need to construct a correct AST.
417 if (SemaRef.Diags.hasFatalErrorOccurred() &&
418 SemaRef.hasUncompilableErrorOccurred()) {
419 Invalid = true;
420 return;
421 }
422 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
423 if (!Invalid) {
424 CodeSynthesisContext Inst;
425 Inst.Kind = Kind;
426 Inst.PointOfInstantiation = PointOfInstantiation;
427 Inst.Entity = Entity;
428 Inst.Template = Template;
429 Inst.TemplateArgs = TemplateArgs.data();
430 Inst.NumTemplateArgs = TemplateArgs.size();
431 Inst.DeductionInfo = DeductionInfo;
432 Inst.InstantiationRange = InstantiationRange;
433 SemaRef.pushCodeSynthesisContext(Inst);
434
435 AlreadyInstantiating = !Inst.Entity ? false :
436 !SemaRef.InstantiatingSpecializations
437 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
438 .second;
439 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
440 }
441}
442
443Sema::InstantiatingTemplate::InstantiatingTemplate(
444 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
445 SourceRange InstantiationRange)
446 : InstantiatingTemplate(SemaRef,
447 CodeSynthesisContext::TemplateInstantiation,
448 PointOfInstantiation, InstantiationRange, Entity) {}
449
450Sema::InstantiatingTemplate::InstantiatingTemplate(
451 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
452 ExceptionSpecification, SourceRange InstantiationRange)
453 : InstantiatingTemplate(
454 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
455 PointOfInstantiation, InstantiationRange, Entity) {}
456
457Sema::InstantiatingTemplate::InstantiatingTemplate(
458 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
459 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
460 SourceRange InstantiationRange)
461 : InstantiatingTemplate(
462 SemaRef,
463 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
464 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
465 Template, TemplateArgs) {}
466
467Sema::InstantiatingTemplate::InstantiatingTemplate(
468 Sema &SemaRef, SourceLocation PointOfInstantiation,
469 FunctionTemplateDecl *FunctionTemplate,
470 ArrayRef<TemplateArgument> TemplateArgs,
471 CodeSynthesisContext::SynthesisKind Kind,
472 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
473 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
474 InstantiationRange, FunctionTemplate, nullptr,
475 TemplateArgs, &DeductionInfo) {
476 assert((static_cast <bool> (Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? void (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 478, __extension__
__PRETTY_FUNCTION__))
477 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||(static_cast <bool> (Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? void (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 478, __extension__
__PRETTY_FUNCTION__))
478 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution)(static_cast <bool> (Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? void (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 478, __extension__
__PRETTY_FUNCTION__))
;
479}
480
481Sema::InstantiatingTemplate::InstantiatingTemplate(
482 Sema &SemaRef, SourceLocation PointOfInstantiation,
483 TemplateDecl *Template,
484 ArrayRef<TemplateArgument> TemplateArgs,
485 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
486 : InstantiatingTemplate(
487 SemaRef,
488 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
489 PointOfInstantiation, InstantiationRange, Template, nullptr,
490 TemplateArgs, &DeductionInfo) {}
491
492Sema::InstantiatingTemplate::InstantiatingTemplate(
493 Sema &SemaRef, SourceLocation PointOfInstantiation,
494 ClassTemplatePartialSpecializationDecl *PartialSpec,
495 ArrayRef<TemplateArgument> TemplateArgs,
496 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
497 : InstantiatingTemplate(
498 SemaRef,
499 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
500 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
501 TemplateArgs, &DeductionInfo) {}
502
503Sema::InstantiatingTemplate::InstantiatingTemplate(
504 Sema &SemaRef, SourceLocation PointOfInstantiation,
505 VarTemplatePartialSpecializationDecl *PartialSpec,
506 ArrayRef<TemplateArgument> TemplateArgs,
507 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
508 : InstantiatingTemplate(
509 SemaRef,
510 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
511 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
512 TemplateArgs, &DeductionInfo) {}
513
514Sema::InstantiatingTemplate::InstantiatingTemplate(
515 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
516 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
517 : InstantiatingTemplate(
518 SemaRef,
519 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
520 PointOfInstantiation, InstantiationRange, Param, nullptr,
521 TemplateArgs) {}
522
523Sema::InstantiatingTemplate::InstantiatingTemplate(
524 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
525 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
526 SourceRange InstantiationRange)
527 : InstantiatingTemplate(
528 SemaRef,
529 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
530 PointOfInstantiation, InstantiationRange, Param, Template,
531 TemplateArgs) {}
532
533Sema::InstantiatingTemplate::InstantiatingTemplate(
534 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
535 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
536 SourceRange InstantiationRange)
537 : InstantiatingTemplate(
538 SemaRef,
539 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
540 PointOfInstantiation, InstantiationRange, Param, Template,
541 TemplateArgs) {}
542
543Sema::InstantiatingTemplate::InstantiatingTemplate(
544 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
545 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
546 SourceRange InstantiationRange)
547 : InstantiatingTemplate(
548 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
549 PointOfInstantiation, InstantiationRange, Param, Template,
550 TemplateArgs) {}
551
552Sema::InstantiatingTemplate::InstantiatingTemplate(
553 Sema &SemaRef, SourceLocation PointOfInstantiation,
554 concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo,
555 SourceRange InstantiationRange)
556 : InstantiatingTemplate(
557 SemaRef, CodeSynthesisContext::RequirementInstantiation,
558 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
559 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
560}
561
562Sema::InstantiatingTemplate::InstantiatingTemplate(
563 Sema &SemaRef, SourceLocation PointOfInstantiation,
564 concepts::NestedRequirement *Req, ConstraintsCheck,
565 SourceRange InstantiationRange)
566 : InstantiatingTemplate(
567 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
568 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
569 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt) {}
570
571Sema::InstantiatingTemplate::InstantiatingTemplate(
572 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
573 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
574 : InstantiatingTemplate(
575 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
576 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
577 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
578}
579
580Sema::InstantiatingTemplate::InstantiatingTemplate(
581 Sema &SemaRef, SourceLocation PointOfInstantiation,
582 ConstraintsCheck, NamedDecl *Template,
583 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
584 : InstantiatingTemplate(
585 SemaRef, CodeSynthesisContext::ConstraintsCheck,
586 PointOfInstantiation, InstantiationRange, Template, nullptr,
587 TemplateArgs) {}
588
589Sema::InstantiatingTemplate::InstantiatingTemplate(
590 Sema &SemaRef, SourceLocation PointOfInstantiation,
591 ConstraintSubstitution, NamedDecl *Template,
592 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
593 : InstantiatingTemplate(
594 SemaRef, CodeSynthesisContext::ConstraintSubstitution,
595 PointOfInstantiation, InstantiationRange, Template, nullptr,
596 {}, &DeductionInfo) {}
597
598Sema::InstantiatingTemplate::InstantiatingTemplate(
599 Sema &SemaRef, SourceLocation PointOfInstantiation,
600 ConstraintNormalization, NamedDecl *Template,
601 SourceRange InstantiationRange)
602 : InstantiatingTemplate(
603 SemaRef, CodeSynthesisContext::ConstraintNormalization,
604 PointOfInstantiation, InstantiationRange, Template) {}
605
606Sema::InstantiatingTemplate::InstantiatingTemplate(
607 Sema &SemaRef, SourceLocation PointOfInstantiation,
608 ParameterMappingSubstitution, NamedDecl *Template,
609 SourceRange InstantiationRange)
610 : InstantiatingTemplate(
611 SemaRef, CodeSynthesisContext::ParameterMappingSubstitution,
612 PointOfInstantiation, InstantiationRange, Template) {}
613
614
615void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
616 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
617 InNonInstantiationSFINAEContext = false;
618
619 CodeSynthesisContexts.push_back(Ctx);
620
621 if (!Ctx.isInstantiationRecord())
622 ++NonInstantiationEntries;
623
624 // Check to see if we're low on stack space. We can't do anything about this
625 // from here, but we can at least warn the user.
626 if (isStackNearlyExhausted())
627 warnStackExhausted(Ctx.PointOfInstantiation);
628}
629
630void Sema::popCodeSynthesisContext() {
631 auto &Active = CodeSynthesisContexts.back();
632 if (!Active.isInstantiationRecord()) {
633 assert(NonInstantiationEntries > 0)(static_cast <bool> (NonInstantiationEntries > 0) ? void
(0) : __assert_fail ("NonInstantiationEntries > 0", "clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 633, __extension__ __PRETTY_FUNCTION__))
;
634 --NonInstantiationEntries;
635 }
636
637 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
638
639 // Name lookup no longer looks in this template's defining module.
640 assert(CodeSynthesisContexts.size() >=(static_cast <bool> (CodeSynthesisContexts.size() >=
CodeSynthesisContextLookupModules.size() && "forgot to remove a lookup module for a template instantiation"
) ? void (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 642, __extension__
__PRETTY_FUNCTION__))
641 CodeSynthesisContextLookupModules.size() &&(static_cast <bool> (CodeSynthesisContexts.size() >=
CodeSynthesisContextLookupModules.size() && "forgot to remove a lookup module for a template instantiation"
) ? void (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 642, __extension__
__PRETTY_FUNCTION__))
642 "forgot to remove a lookup module for a template instantiation")(static_cast <bool> (CodeSynthesisContexts.size() >=
CodeSynthesisContextLookupModules.size() && "forgot to remove a lookup module for a template instantiation"
) ? void (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 642, __extension__
__PRETTY_FUNCTION__))
;
643 if (CodeSynthesisContexts.size() ==
644 CodeSynthesisContextLookupModules.size()) {
645 if (Module *M = CodeSynthesisContextLookupModules.back())
646 LookupModulesCache.erase(M);
647 CodeSynthesisContextLookupModules.pop_back();
648 }
649
650 // If we've left the code synthesis context for the current context stack,
651 // stop remembering that we've emitted that stack.
652 if (CodeSynthesisContexts.size() ==
653 LastEmittedCodeSynthesisContextDepth)
654 LastEmittedCodeSynthesisContextDepth = 0;
655
656 CodeSynthesisContexts.pop_back();
657}
658
659void Sema::InstantiatingTemplate::Clear() {
660 if (!Invalid) {
661 if (!AlreadyInstantiating) {
662 auto &Active = SemaRef.CodeSynthesisContexts.back();
663 if (Active.Entity)
664 SemaRef.InstantiatingSpecializations.erase(
665 {Active.Entity->getCanonicalDecl(), Active.Kind});
666 }
667
668 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
669 SemaRef.CodeSynthesisContexts.back());
670
671 SemaRef.popCodeSynthesisContext();
672 Invalid = true;
673 }
674}
675
676static std::string convertCallArgsToString(Sema &S,
677 llvm::ArrayRef<const Expr *> Args) {
678 std::string Result;
679 llvm::raw_string_ostream OS(Result);
680 llvm::ListSeparator Comma;
681 for (const Expr *Arg : Args) {
682 OS << Comma;
683 Arg->IgnoreParens()->printPretty(OS, nullptr,
684 S.Context.getPrintingPolicy());
685 }
686 return Result;
687}
688
689bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
690 SourceLocation PointOfInstantiation,
691 SourceRange InstantiationRange) {
692 assert(SemaRef.NonInstantiationEntries <=(static_cast <bool> (SemaRef.NonInstantiationEntries <=
SemaRef.CodeSynthesisContexts.size()) ? void (0) : __assert_fail
("SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 693, __extension__
__PRETTY_FUNCTION__))
693 SemaRef.CodeSynthesisContexts.size())(static_cast <bool> (SemaRef.NonInstantiationEntries <=
SemaRef.CodeSynthesisContexts.size()) ? void (0) : __assert_fail
("SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 693, __extension__
__PRETTY_FUNCTION__))
;
694 if ((SemaRef.CodeSynthesisContexts.size() -
695 SemaRef.NonInstantiationEntries)
696 <= SemaRef.getLangOpts().InstantiationDepth)
697 return false;
698
699 SemaRef.Diag(PointOfInstantiation,
700 diag::err_template_recursion_depth_exceeded)
701 << SemaRef.getLangOpts().InstantiationDepth
702 << InstantiationRange;
703 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
704 << SemaRef.getLangOpts().InstantiationDepth;
705 return true;
706}
707
708/// Prints the current instantiation stack through a series of
709/// notes.
710void Sema::PrintInstantiationStack() {
711 // Determine which template instantiations to skip, if any.
712 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
713 unsigned Limit = Diags.getTemplateBacktraceLimit();
714 if (Limit && Limit < CodeSynthesisContexts.size()) {
715 SkipStart = Limit / 2 + Limit % 2;
716 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
717 }
718
719 // FIXME: In all of these cases, we need to show the template arguments
720 unsigned InstantiationIdx = 0;
721 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
722 Active = CodeSynthesisContexts.rbegin(),
723 ActiveEnd = CodeSynthesisContexts.rend();
724 Active != ActiveEnd;
725 ++Active, ++InstantiationIdx) {
726 // Skip this instantiation?
727 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
728 if (InstantiationIdx == SkipStart) {
729 // Note that we're skipping instantiations.
730 Diags.Report(Active->PointOfInstantiation,
731 diag::note_instantiation_contexts_suppressed)
732 << unsigned(CodeSynthesisContexts.size() - Limit);
733 }
734 continue;
735 }
736
737 switch (Active->Kind) {
738 case CodeSynthesisContext::TemplateInstantiation: {
739 Decl *D = Active->Entity;
740 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
741 unsigned DiagID = diag::note_template_member_class_here;
742 if (isa<ClassTemplateSpecializationDecl>(Record))
743 DiagID = diag::note_template_class_instantiation_here;
744 Diags.Report(Active->PointOfInstantiation, DiagID)
745 << Record << Active->InstantiationRange;
746 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
747 unsigned DiagID;
748 if (Function->getPrimaryTemplate())
749 DiagID = diag::note_function_template_spec_here;
750 else
751 DiagID = diag::note_template_member_function_here;
752 Diags.Report(Active->PointOfInstantiation, DiagID)
753 << Function
754 << Active->InstantiationRange;
755 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
756 Diags.Report(Active->PointOfInstantiation,
757 VD->isStaticDataMember()?
758 diag::note_template_static_data_member_def_here
759 : diag::note_template_variable_def_here)
760 << VD
761 << Active->InstantiationRange;
762 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
763 Diags.Report(Active->PointOfInstantiation,
764 diag::note_template_enum_def_here)
765 << ED
766 << Active->InstantiationRange;
767 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
768 Diags.Report(Active->PointOfInstantiation,
769 diag::note_template_nsdmi_here)
770 << FD << Active->InstantiationRange;
771 } else {
772 Diags.Report(Active->PointOfInstantiation,
773 diag::note_template_type_alias_instantiation_here)
774 << cast<TypeAliasTemplateDecl>(D)
775 << Active->InstantiationRange;
776 }
777 break;
778 }
779
780 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
781 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
782 SmallString<128> TemplateArgsStr;
783 llvm::raw_svector_ostream OS(TemplateArgsStr);
784 Template->printName(OS, getPrintingPolicy());
785 printTemplateArgumentList(OS, Active->template_arguments(),
786 getPrintingPolicy());
787 Diags.Report(Active->PointOfInstantiation,
788 diag::note_default_arg_instantiation_here)
789 << OS.str()
790 << Active->InstantiationRange;
791 break;
792 }
793
794 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
795 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
796 Diags.Report(Active->PointOfInstantiation,
797 diag::note_explicit_template_arg_substitution_here)
798 << FnTmpl
799 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
800 Active->TemplateArgs,
801 Active->NumTemplateArgs)
802 << Active->InstantiationRange;
803 break;
804 }
805
806 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
807 if (FunctionTemplateDecl *FnTmpl =
808 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
809 Diags.Report(Active->PointOfInstantiation,
810 diag::note_function_template_deduction_instantiation_here)
811 << FnTmpl
812 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
813 Active->TemplateArgs,
814 Active->NumTemplateArgs)
815 << Active->InstantiationRange;
816 } else {
817 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
818 isa<VarTemplateSpecializationDecl>(Active->Entity);
819 bool IsTemplate = false;
820 TemplateParameterList *Params;
821 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
822 IsTemplate = true;
823 Params = D->getTemplateParameters();
824 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
825 Active->Entity)) {
826 Params = D->getTemplateParameters();
827 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
828 Active->Entity)) {
829 Params = D->getTemplateParameters();
830 } else {
831 llvm_unreachable("unexpected template kind")::llvm::llvm_unreachable_internal("unexpected template kind",
"clang/lib/Sema/SemaTemplateInstantiate.cpp", 831)
;
832 }
833
834 Diags.Report(Active->PointOfInstantiation,
835 diag::note_deduced_template_arg_substitution_here)
836 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
837 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
838 Active->NumTemplateArgs)
839 << Active->InstantiationRange;
840 }
841 break;
842 }
843
844 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
845 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
846 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
847
848 SmallString<128> TemplateArgsStr;
849 llvm::raw_svector_ostream OS(TemplateArgsStr);
850 FD->printName(OS, getPrintingPolicy());
851 printTemplateArgumentList(OS, Active->template_arguments(),
852 getPrintingPolicy());
853 Diags.Report(Active->PointOfInstantiation,
854 diag::note_default_function_arg_instantiation_here)
855 << OS.str()
856 << Active->InstantiationRange;
857 break;
858 }
859
860 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
861 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
862 std::string Name;
863 if (!Parm->getName().empty())
864 Name = std::string(" '") + Parm->getName().str() + "'";
865
866 TemplateParameterList *TemplateParams = nullptr;
867 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
868 TemplateParams = Template->getTemplateParameters();
869 else
870 TemplateParams =
871 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
872 ->getTemplateParameters();
873 Diags.Report(Active->PointOfInstantiation,
874 diag::note_prior_template_arg_substitution)
875 << isa<TemplateTemplateParmDecl>(Parm)
876 << Name
877 << getTemplateArgumentBindingsText(TemplateParams,
878 Active->TemplateArgs,
879 Active->NumTemplateArgs)
880 << Active->InstantiationRange;
881 break;
882 }
883
884 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
885 TemplateParameterList *TemplateParams = nullptr;
886 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
887 TemplateParams = Template->getTemplateParameters();
888 else
889 TemplateParams =
890 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
891 ->getTemplateParameters();
892
893 Diags.Report(Active->PointOfInstantiation,
894 diag::note_template_default_arg_checking)
895 << getTemplateArgumentBindingsText(TemplateParams,
896 Active->TemplateArgs,
897 Active->NumTemplateArgs)
898 << Active->InstantiationRange;
899 break;
900 }
901
902 case CodeSynthesisContext::ExceptionSpecEvaluation:
903 Diags.Report(Active->PointOfInstantiation,
904 diag::note_evaluating_exception_spec_here)
905 << cast<FunctionDecl>(Active->Entity);
906 break;
907
908 case CodeSynthesisContext::ExceptionSpecInstantiation:
909 Diags.Report(Active->PointOfInstantiation,
910 diag::note_template_exception_spec_instantiation_here)
911 << cast<FunctionDecl>(Active->Entity)
912 << Active->InstantiationRange;
913 break;
914
915 case CodeSynthesisContext::RequirementInstantiation:
916 Diags.Report(Active->PointOfInstantiation,
917 diag::note_template_requirement_instantiation_here)
918 << Active->InstantiationRange;
919 break;
920 case CodeSynthesisContext::RequirementParameterInstantiation:
921 Diags.Report(Active->PointOfInstantiation,
922 diag::note_template_requirement_params_instantiation_here)
923 << Active->InstantiationRange;
924 break;
925
926 case CodeSynthesisContext::NestedRequirementConstraintsCheck:
927 Diags.Report(Active->PointOfInstantiation,
928 diag::note_nested_requirement_here)
929 << Active->InstantiationRange;
930 break;
931
932 case CodeSynthesisContext::DeclaringSpecialMember:
933 Diags.Report(Active->PointOfInstantiation,
934 diag::note_in_declaration_of_implicit_special_member)
935 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
936 break;
937
938 case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
939 Diags.Report(Active->Entity->getLocation(),
940 diag::note_in_declaration_of_implicit_equality_comparison);
941 break;
942
943 case CodeSynthesisContext::DefiningSynthesizedFunction: {
944 // FIXME: For synthesized functions that are not defaulted,
945 // produce a note.
946 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
947 DefaultedFunctionKind DFK =
948 FD ? getDefaultedFunctionKind(FD) : DefaultedFunctionKind();
949 if (DFK.isSpecialMember()) {
950 auto *MD = cast<CXXMethodDecl>(FD);
951 Diags.Report(Active->PointOfInstantiation,
952 diag::note_member_synthesized_at)
953 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
954 << Context.getTagDeclType(MD->getParent());
955 } else if (DFK.isComparison()) {
956 Diags.Report(Active->PointOfInstantiation,
957 diag::note_comparison_synthesized_at)
958 << (int)DFK.asComparison()
959 << Context.getTagDeclType(
960 cast<CXXRecordDecl>(FD->getLexicalDeclContext()));
961 }
962 break;
963 }
964
965 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
966 Diags.Report(Active->Entity->getLocation(),
967 diag::note_rewriting_operator_as_spaceship);
968 break;
969
970 case CodeSynthesisContext::InitializingStructuredBinding:
971 Diags.Report(Active->PointOfInstantiation,
972 diag::note_in_binding_decl_init)
973 << cast<BindingDecl>(Active->Entity);
974 break;
975
976 case CodeSynthesisContext::MarkingClassDllexported:
977 Diags.Report(Active->PointOfInstantiation,
978 diag::note_due_to_dllexported_class)
979 << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
980 break;
981
982 case CodeSynthesisContext::BuildingBuiltinDumpStructCall:
983 Diags.Report(Active->PointOfInstantiation,
984 diag::note_building_builtin_dump_struct_call)
985 << convertCallArgsToString(
986 *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs));
987 break;
988
989 case CodeSynthesisContext::Memoization:
990 break;
991
992 case CodeSynthesisContext::LambdaExpressionSubstitution:
993 Diags.Report(Active->PointOfInstantiation,
994 diag::note_lambda_substitution_here);
995 break;
996 case CodeSynthesisContext::ConstraintsCheck: {
997 unsigned DiagID = 0;
998 if (!Active->Entity) {
999 Diags.Report(Active->PointOfInstantiation,
1000 diag::note_nested_requirement_here)
1001 << Active->InstantiationRange;
1002 break;
1003 }
1004 if (isa<ConceptDecl>(Active->Entity))
1005 DiagID = diag::note_concept_specialization_here;
1006 else if (isa<TemplateDecl>(Active->Entity))
1007 DiagID = diag::note_checking_constraints_for_template_id_here;
1008 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1009 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1010 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1011 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1012 else {
1013 assert(isa<FunctionDecl>(Active->Entity))(static_cast <bool> (isa<FunctionDecl>(Active->
Entity)) ? void (0) : __assert_fail ("isa<FunctionDecl>(Active->Entity)"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1013, __extension__
__PRETTY_FUNCTION__))
;
1014 DiagID = diag::note_checking_constraints_for_function_here;
1015 }
1016 SmallString<128> TemplateArgsStr;
1017 llvm::raw_svector_ostream OS(TemplateArgsStr);
1018 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1019 if (!isa<FunctionDecl>(Active->Entity)) {
1020 printTemplateArgumentList(OS, Active->template_arguments(),
1021 getPrintingPolicy());
1022 }
1023 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
1024 << Active->InstantiationRange;
1025 break;
1026 }
1027 case CodeSynthesisContext::ConstraintSubstitution:
1028 Diags.Report(Active->PointOfInstantiation,
1029 diag::note_constraint_substitution_here)
1030 << Active->InstantiationRange;
1031 break;
1032 case CodeSynthesisContext::ConstraintNormalization:
1033 Diags.Report(Active->PointOfInstantiation,
1034 diag::note_constraint_normalization_here)
1035 << cast<NamedDecl>(Active->Entity)->getName()
1036 << Active->InstantiationRange;
1037 break;
1038 case CodeSynthesisContext::ParameterMappingSubstitution:
1039 Diags.Report(Active->PointOfInstantiation,
1040 diag::note_parameter_mapping_substitution_here)
1041 << Active->InstantiationRange;
1042 break;
1043 }
1044 }
1045}
1046
1047std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1048 if (InNonInstantiationSFINAEContext)
1049 return std::optional<TemplateDeductionInfo *>(nullptr);
1050
1051 bool SawLambdaSubstitution = false;
1052 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
1053 Active = CodeSynthesisContexts.rbegin(),
1054 ActiveEnd = CodeSynthesisContexts.rend();
1055 Active != ActiveEnd;
1056 ++Active)
1057 {
1058 switch (Active->Kind) {
1059 case CodeSynthesisContext::TemplateInstantiation:
1060 // An instantiation of an alias template may or may not be a SFINAE
1061 // context, depending on what else is on the stack.
1062 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1063 break;
1064 [[fallthrough]];
1065 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
1066 case CodeSynthesisContext::ExceptionSpecInstantiation:
1067 case CodeSynthesisContext::ConstraintsCheck:
1068 case CodeSynthesisContext::ParameterMappingSubstitution:
1069 case CodeSynthesisContext::ConstraintNormalization:
1070 case CodeSynthesisContext::NestedRequirementConstraintsCheck:
1071 // This is a template instantiation, so there is no SFINAE.
1072 return std::nullopt;
1073 case CodeSynthesisContext::LambdaExpressionSubstitution:
1074 // [temp.deduct]p9
1075 // A lambda-expression appearing in a function type or a template
1076 // parameter is not considered part of the immediate context for the
1077 // purposes of template argument deduction.
1078
1079 // We need to check parents.
1080 SawLambdaSubstitution = true;
1081 break;
1082
1083 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
1084 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
1085 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
1086 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
1087 // A default template argument instantiation and substitution into
1088 // template parameters with arguments for prior parameters may or may
1089 // not be a SFINAE context; look further up the stack.
1090 break;
1091
1092 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
1093 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
1094 // We're either substituting explicitly-specified template arguments,
1095 // deduced template arguments. SFINAE applies unless we are in a lambda
1096 // expression, see [temp.deduct]p9.
1097 if (SawLambdaSubstitution)
1098 return std::nullopt;
1099 [[fallthrough]];
1100 case CodeSynthesisContext::ConstraintSubstitution:
1101 case CodeSynthesisContext::RequirementInstantiation:
1102 case CodeSynthesisContext::RequirementParameterInstantiation:
1103 // SFINAE always applies in a constraint expression or a requirement
1104 // in a requires expression.
1105 assert(Active->DeductionInfo && "Missing deduction info pointer")(static_cast <bool> (Active->DeductionInfo &&
"Missing deduction info pointer") ? void (0) : __assert_fail
("Active->DeductionInfo && \"Missing deduction info pointer\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1105, __extension__
__PRETTY_FUNCTION__))
;
1106 return Active->DeductionInfo;
1107
1108 case CodeSynthesisContext::DeclaringSpecialMember:
1109 case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
1110 case CodeSynthesisContext::DefiningSynthesizedFunction:
1111 case CodeSynthesisContext::InitializingStructuredBinding:
1112 case CodeSynthesisContext::MarkingClassDllexported:
1113 case CodeSynthesisContext::BuildingBuiltinDumpStructCall:
1114 // This happens in a context unrelated to template instantiation, so
1115 // there is no SFINAE.
1116 return std::nullopt;
1117
1118 case CodeSynthesisContext::ExceptionSpecEvaluation:
1119 // FIXME: This should not be treated as a SFINAE context, because
1120 // we will cache an incorrect exception specification. However, clang
1121 // bootstrap relies this! See PR31692.
1122 break;
1123
1124 case CodeSynthesisContext::Memoization:
1125 break;
1126 }
1127
1128 // The inner context was transparent for SFINAE. If it occurred within a
1129 // non-instantiation SFINAE context, then SFINAE applies.
1130 if (Active->SavedInNonInstantiationSFINAEContext)
1131 return std::optional<TemplateDeductionInfo *>(nullptr);
1132 }
1133
1134 return std::nullopt;
1135}
1136
1137//===----------------------------------------------------------------------===/
1138// Template Instantiation for Types
1139//===----------------------------------------------------------------------===/
1140namespace {
1141 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1142 const MultiLevelTemplateArgumentList &TemplateArgs;
1143 SourceLocation Loc;
1144 DeclarationName Entity;
1145 bool EvaluateConstraints = true;
1146
1147 public:
1148 typedef TreeTransform<TemplateInstantiator> inherited;
1149
1150 TemplateInstantiator(Sema &SemaRef,
1151 const MultiLevelTemplateArgumentList &TemplateArgs,
1152 SourceLocation Loc, DeclarationName Entity)
1153 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1154 Entity(Entity) {}
1155
1156 void setEvaluateConstraints(bool B) {
1157 EvaluateConstraints = B;
1158 }
1159 bool getEvaluateConstraints() {
1160 return EvaluateConstraints;
1161 }
1162
1163 /// Determine whether the given type \p T has already been
1164 /// transformed.
1165 ///
1166 /// For the purposes of template instantiation, a type has already been
1167 /// transformed if it is NULL or if it is not dependent.
1168 bool AlreadyTransformed(QualType T);
1169
1170 /// Returns the location of the entity being instantiated, if known.
1171 SourceLocation getBaseLocation() { return Loc; }
1172
1173 /// Returns the name of the entity being instantiated, if any.
1174 DeclarationName getBaseEntity() { return Entity; }
1175
1176 /// Sets the "base" location and entity when that
1177 /// information is known based on another transformation.
1178 void setBase(SourceLocation Loc, DeclarationName Entity) {
1179 this->Loc = Loc;
1180 this->Entity = Entity;
1181 }
1182
1183 unsigned TransformTemplateDepth(unsigned Depth) {
1184 return TemplateArgs.getNewDepth(Depth);
1185 }
1186
1187 std::optional<unsigned> getPackIndex(TemplateArgument Pack) {
1188 int Index = getSema().ArgumentPackSubstitutionIndex;
1189 if (Index == -1)
1190 return std::nullopt;
1191 return Pack.pack_size() - 1 - Index;
1192 }
1193
1194 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1195 SourceRange PatternRange,
1196 ArrayRef<UnexpandedParameterPack> Unexpanded,
1197 bool &ShouldExpand, bool &RetainExpansion,
1198 std::optional<unsigned> &NumExpansions) {
1199 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
1200 PatternRange, Unexpanded,
1201 TemplateArgs,
1202 ShouldExpand,
1203 RetainExpansion,
1204 NumExpansions);
1205 }
1206
1207 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1208 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
1209 }
1210
1211 TemplateArgument ForgetPartiallySubstitutedPack() {
1212 TemplateArgument Result;
1213 if (NamedDecl *PartialPack
1214 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
1215 MultiLevelTemplateArgumentList &TemplateArgs
1216 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1217 unsigned Depth, Index;
1218 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1219 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1220 Result = TemplateArgs(Depth, Index);
1221 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1222 }
1223 }
1224
1225 return Result;
1226 }
1227
1228 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1229 if (Arg.isNull())
1230 return;
1231
1232 if (NamedDecl *PartialPack
1233 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
1234 MultiLevelTemplateArgumentList &TemplateArgs
1235 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1236 unsigned Depth, Index;
1237 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1238 TemplateArgs.setArgument(Depth, Index, Arg);
1239 }
1240 }
1241
1242 /// Transform the given declaration by instantiating a reference to
1243 /// this declaration.
1244 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1245
1246 void transformAttrs(Decl *Old, Decl *New) {
1247 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1248 }
1249
1250 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1251 if (Old->isParameterPack()) {
16
Assuming the condition is false
1252 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
1253 for (auto *New : NewDecls)
1254 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
1255 Old, cast<VarDecl>(New));
1256 return;
1257 }
1258
1259 assert(NewDecls.size() == 1 &&(static_cast <bool> (NewDecls.size() == 1 && "should only have multiple expansions for a pack"
) ? void (0) : __assert_fail ("NewDecls.size() == 1 && \"should only have multiple expansions for a pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1260, __extension__
__PRETTY_FUNCTION__))
17
Taking false branch
18
Assuming the condition is true
19
'?' condition is true
1260 "should only have multiple expansions for a pack")(static_cast <bool> (NewDecls.size() == 1 && "should only have multiple expansions for a pack"
) ? void (0) : __assert_fail ("NewDecls.size() == 1 && \"should only have multiple expansions for a pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1260, __extension__
__PRETTY_FUNCTION__))
;
1261 Decl *New = NewDecls.front();
1262
1263 // If we've instantiated the call operator of a lambda or the call
1264 // operator template of a generic lambda, update the "instantiation of"
1265 // information.
1266 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
20
Assuming 'New' is a 'CastReturnType'
1267 if (NewMD
20.1
'NewMD' is non-null
20.1
'NewMD' is non-null
&& isLambdaCallOperator(NewMD)) {
21
Taking true branch
1268 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
22
Assuming 'Old' is not a 'CastReturnType'
23
'OldMD' initialized to a null pointer value
1269 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
24
Assuming 'NewTD' is non-null
25
Taking true branch
1270 NewTD->setInstantiatedFromMemberTemplate(
1271 OldMD->getDescribedFunctionTemplate());
26
Called C++ object pointer is null
1272 else
1273 NewMD->setInstantiationOfMemberFunction(OldMD,
1274 TSK_ImplicitInstantiation);
1275 }
1276
1277 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
1278
1279 // We recreated a local declaration, but not by instantiating it. There
1280 // may be pending dependent diagnostics to produce.
1281 if (auto *DC = dyn_cast<DeclContext>(Old);
1282 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1283 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1284 }
1285
1286 /// Transform the definition of the given declaration by
1287 /// instantiating it.
1288 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1289
1290 /// Transform the first qualifier within a scope by instantiating the
1291 /// declaration.
1292 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1293
1294 /// Rebuild the exception declaration and register the declaration
1295 /// as an instantiated local.
1296 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1297 TypeSourceInfo *Declarator,
1298 SourceLocation StartLoc,
1299 SourceLocation NameLoc,
1300 IdentifierInfo *Name);
1301
1302 /// Rebuild the Objective-C exception declaration and register the
1303 /// declaration as an instantiated local.
1304 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1305 TypeSourceInfo *TSInfo, QualType T);
1306
1307 /// Check for tag mismatches when instantiating an
1308 /// elaborated type.
1309 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1310 ElaboratedTypeKeyword Keyword,
1311 NestedNameSpecifierLoc QualifierLoc,
1312 QualType T);
1313
1314 TemplateName
1315 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1316 SourceLocation NameLoc,
1317 QualType ObjectType = QualType(),
1318 NamedDecl *FirstQualifierInScope = nullptr,
1319 bool AllowInjectedClassName = false);
1320
1321 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1322 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1323 const Stmt *InstS,
1324 const NoInlineAttr *A);
1325 const AlwaysInlineAttr *
1326 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1327 const AlwaysInlineAttr *A);
1328
1329 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1330 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1331 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1332
1333 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1334 NonTypeTemplateParmDecl *D);
1335 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1336 SubstNonTypeTemplateParmPackExpr *E);
1337 ExprResult TransformSubstNonTypeTemplateParmExpr(
1338 SubstNonTypeTemplateParmExpr *E);
1339
1340 /// Rebuild a DeclRefExpr for a VarDecl reference.
1341 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1342
1343 /// Transform a reference to a function or init-capture parameter pack.
1344 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1345
1346 /// Transform a FunctionParmPackExpr which was built when we couldn't
1347 /// expand a function parameter pack reference which refers to an expanded
1348 /// pack.
1349 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1350
1351 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1352 FunctionProtoTypeLoc TL) {
1353 // Call the base version; it will forward to our overridden version below.
1354 return inherited::TransformFunctionProtoType(TLB, TL);
1355 }
1356
1357 template<typename Fn>
1358 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1359 FunctionProtoTypeLoc TL,
1360 CXXRecordDecl *ThisContext,
1361 Qualifiers ThisTypeQuals,
1362 Fn TransformExceptionSpec);
1363
1364 ParmVarDecl *
1365 TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
1366 std::optional<unsigned> NumExpansions,
1367 bool ExpectParameterPack);
1368
1369 using inherited::TransformTemplateTypeParmType;
1370 /// Transforms a template type parameter type by performing
1371 /// substitution of the corresponding template type argument.
1372 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1373 TemplateTypeParmTypeLoc TL,
1374 bool SuppressObjCLifetime);
1375
1376 QualType BuildSubstTemplateTypeParmType(
1377 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1378 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
1379 TemplateArgument Arg, SourceLocation NameLoc);
1380
1381 /// Transforms an already-substituted template type parameter pack
1382 /// into either itself (if we aren't substituting into its pack expansion)
1383 /// or the appropriate substituted argument.
1384 using inherited::TransformSubstTemplateTypeParmPackType;
1385 QualType
1386 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1387 SubstTemplateTypeParmPackTypeLoc TL,
1388 bool SuppressObjCLifetime);
1389
1390 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1391 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1392 Sema::ConstraintEvalRAII<TemplateInstantiator> RAII(*this);
1393
1394 Sema::CodeSynthesisContext C;
1395 C.Kind = clang::Sema::CodeSynthesisContext::LambdaExpressionSubstitution;
1396 C.PointOfInstantiation = E->getBeginLoc();
1397 SemaRef.pushCodeSynthesisContext(C);
1398 auto PopCtx =
1399 llvm::make_scope_exit([this] { SemaRef.popCodeSynthesisContext(); });
1400
1401 ExprResult Result = inherited::TransformLambdaExpr(E);
1
Calling 'TreeTransform::TransformLambdaExpr'
1402 if (Result.isInvalid())
1403 return Result;
1404
1405 CXXMethodDecl *MD = Result.getAs<LambdaExpr>()->getCallOperator();
1406 for (ParmVarDecl *PVD : MD->parameters()) {
1407 assert(PVD && "null in a parameter list")(static_cast <bool> (PVD && "null in a parameter list"
) ? void (0) : __assert_fail ("PVD && \"null in a parameter list\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1407, __extension__
__PRETTY_FUNCTION__))
;
1408 if (!PVD->hasDefaultArg())
1409 continue;
1410 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1411 // FIXME: Obtain the source location for the '=' token.
1412 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1413 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1414 // If substitution fails, the default argument is set to a
1415 // RecoveryExpr that wraps the uninstantiated default argument so
1416 // that downstream diagnostics are omitted.
1417 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1418 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
1419 { UninstExpr }, UninstExpr->getType());
1420 if (ErrorResult.isUsable())
1421 PVD->setDefaultArg(ErrorResult.get());
1422 }
1423 }
1424
1425 return Result;
1426 }
1427
1428 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1429 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1430 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1431 if (TransReq.isInvalid())
1432 return TransReq;
1433 assert(TransReq.get() != E &&(static_cast <bool> (TransReq.get() != E && "Do not change value of isSatisfied for the existing expression. "
"Create a new expression instead.") ? void (0) : __assert_fail
("TransReq.get() != E && \"Do not change value of isSatisfied for the existing expression. \" \"Create a new expression instead.\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1435, __extension__
__PRETTY_FUNCTION__))
1434 "Do not change value of isSatisfied for the existing expression. "(static_cast <bool> (TransReq.get() != E && "Do not change value of isSatisfied for the existing expression. "
"Create a new expression instead.") ? void (0) : __assert_fail
("TransReq.get() != E && \"Do not change value of isSatisfied for the existing expression. \" \"Create a new expression instead.\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1435, __extension__
__PRETTY_FUNCTION__))
1435 "Create a new expression instead.")(static_cast <bool> (TransReq.get() != E && "Do not change value of isSatisfied for the existing expression. "
"Create a new expression instead.") ? void (0) : __assert_fail
("TransReq.get() != E && \"Do not change value of isSatisfied for the existing expression. \" \"Create a new expression instead.\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1435, __extension__
__PRETTY_FUNCTION__))
;
1436 if (E->getBody()->isDependentContext()) {
1437 Sema::SFINAETrap Trap(SemaRef);
1438 // We recreate the RequiresExpr body, but not by instantiating it.
1439 // Produce pending diagnostics for dependent access check.
1440 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1441 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1442 if (Trap.hasErrorOccurred())
1443 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1444 }
1445 return TransReq;
1446 }
1447
1448 bool TransformRequiresExprRequirements(
1449 ArrayRef<concepts::Requirement *> Reqs,
1450 SmallVectorImpl<concepts::Requirement *> &Transformed) {
1451 bool SatisfactionDetermined = false;
1452 for (concepts::Requirement *Req : Reqs) {
1453 concepts::Requirement *TransReq = nullptr;
1454 if (!SatisfactionDetermined) {
1455 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1456 TransReq = TransformTypeRequirement(TypeReq);
1457 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1458 TransReq = TransformExprRequirement(ExprReq);
1459 else
1460 TransReq = TransformNestedRequirement(
1461 cast<concepts::NestedRequirement>(Req));
1462 if (!TransReq)
1463 return true;
1464 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1465 // [expr.prim.req]p6
1466 // [...] The substitution and semantic constraint checking
1467 // proceeds in lexical order and stops when a condition that
1468 // determines the result of the requires-expression is
1469 // encountered. [..]
1470 SatisfactionDetermined = true;
1471 } else
1472 TransReq = Req;
1473 Transformed.push_back(TransReq);
1474 }
1475 return false;
1476 }
1477
1478 TemplateParameterList *TransformTemplateParameterList(
1479 TemplateParameterList *OrigTPL) {
1480 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1481
1482 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1483 TemplateDeclInstantiator DeclInstantiator(getSema(),
1484 /* DeclContext *Owner */ Owner, TemplateArgs);
1485 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1486 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1487 }
1488
1489 concepts::TypeRequirement *
1490 TransformTypeRequirement(concepts::TypeRequirement *Req);
1491 concepts::ExprRequirement *
1492 TransformExprRequirement(concepts::ExprRequirement *Req);
1493 concepts::NestedRequirement *
1494 TransformNestedRequirement(concepts::NestedRequirement *Req);
1495 ExprResult TransformRequiresTypeParams(
1496 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1497 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
1498 SmallVectorImpl<QualType> &PTypes,
1499 SmallVectorImpl<ParmVarDecl *> &TransParams,
1500 Sema::ExtParameterInfoBuilder &PInfos);
1501
1502 private:
1503 ExprResult
1504 transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
1505 const NonTypeTemplateParmDecl *parm,
1506 SourceLocation loc, TemplateArgument arg,
1507 std::optional<unsigned> PackIndex);
1508 };
1509}
1510
1511bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1512 if (T.isNull())
1513 return true;
1514
1515 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
1516 return false;
1517
1518 getSema().MarkDeclarationsReferencedInType(Loc, T);
1519 return true;
1520}
1521
1522static TemplateArgument
1523getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
1524 assert(S.ArgumentPackSubstitutionIndex >= 0)(static_cast <bool> (S.ArgumentPackSubstitutionIndex >=
0) ? void (0) : __assert_fail ("S.ArgumentPackSubstitutionIndex >= 0"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1524, __extension__
__PRETTY_FUNCTION__))
;
1525 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size())(static_cast <bool> (S.ArgumentPackSubstitutionIndex <
(int)Arg.pack_size()) ? void (0) : __assert_fail ("S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size()"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1525, __extension__
__PRETTY_FUNCTION__))
;
1526 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
1527 if (Arg.isPackExpansion())
1528 Arg = Arg.getPackExpansionPattern();
1529 return Arg;
1530}
1531
1532Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1533 if (!D)
1534 return nullptr;
1535
1536 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1537 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1538 // If the corresponding template argument is NULL or non-existent, it's
1539 // because we are performing instantiation from explicitly-specified
1540 // template arguments in a function template, but there were some
1541 // arguments left unspecified.
1542 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1543 TTP->getPosition()))
1544 return D;
1545
1546 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1547
1548 if (TTP->isParameterPack()) {
1549 assert(Arg.getKind() == TemplateArgument::Pack &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1550, __extension__
__PRETTY_FUNCTION__))
1550 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1550, __extension__
__PRETTY_FUNCTION__))
;
1551 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1552 }
1553
1554 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1555 assert(!Template.isNull() && Template.getAsTemplateDecl() &&(static_cast <bool> (!Template.isNull() && Template
.getAsTemplateDecl() && "Wrong kind of template template argument"
) ? void (0) : __assert_fail ("!Template.isNull() && Template.getAsTemplateDecl() && \"Wrong kind of template template argument\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1556, __extension__
__PRETTY_FUNCTION__))
1556 "Wrong kind of template template argument")(static_cast <bool> (!Template.isNull() && Template
.getAsTemplateDecl() && "Wrong kind of template template argument"
) ? void (0) : __assert_fail ("!Template.isNull() && Template.getAsTemplateDecl() && \"Wrong kind of template template argument\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1556, __extension__
__PRETTY_FUNCTION__))
;
1557 return Template.getAsTemplateDecl();
1558 }
1559
1560 // Fall through to find the instantiated declaration for this template
1561 // template parameter.
1562 }
1563
1564 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1565}
1566
1567Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1568 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1569 if (!Inst)
1570 return nullptr;
1571
1572 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1573 return Inst;
1574}
1575
1576NamedDecl *
1577TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1578 SourceLocation Loc) {
1579 // If the first part of the nested-name-specifier was a template type
1580 // parameter, instantiate that type parameter down to a tag type.
1581 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1582 const TemplateTypeParmType *TTP
1583 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1584
1585 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1586 // FIXME: This needs testing w/ member access expressions.
1587 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1588
1589 if (TTP->isParameterPack()) {
1590 assert(Arg.getKind() == TemplateArgument::Pack &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1591, __extension__
__PRETTY_FUNCTION__))
1591 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1591, __extension__
__PRETTY_FUNCTION__))
;
1592
1593 if (getSema().ArgumentPackSubstitutionIndex == -1)
1594 return nullptr;
1595
1596 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1597 }
1598
1599 QualType T = Arg.getAsType();
1600 if (T.isNull())
1601 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1602
1603 if (const TagType *Tag = T->getAs<TagType>())
1604 return Tag->getDecl();
1605
1606 // The resulting type is not a tag; complain.
1607 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1608 return nullptr;
1609 }
1610 }
1611
1612 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1613}
1614
1615VarDecl *
1616TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1617 TypeSourceInfo *Declarator,
1618 SourceLocation StartLoc,
1619 SourceLocation NameLoc,
1620 IdentifierInfo *Name) {
1621 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1622 StartLoc, NameLoc, Name);
1623 if (Var)
1624 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1625 return Var;
1626}
1627
1628VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1629 TypeSourceInfo *TSInfo,
1630 QualType T) {
1631 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1632 if (Var)
1633 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1634 return Var;
1635}
1636
1637QualType
1638TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1639 ElaboratedTypeKeyword Keyword,
1640 NestedNameSpecifierLoc QualifierLoc,
1641 QualType T) {
1642 if (const TagType *TT = T->getAs<TagType>()) {
1643 TagDecl* TD = TT->getDecl();
1644
1645 SourceLocation TagLocation = KeywordLoc;
1646
1647 IdentifierInfo *Id = TD->getIdentifier();
1648
1649 // TODO: should we even warn on struct/class mismatches for this? Seems
1650 // like it's likely to produce a lot of spurious errors.
1651 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1652 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1653 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1654 TagLocation, Id)) {
1655 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1656 << Id
1657 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1658 TD->getKindName());
1659 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1660 }
1661 }
1662 }
1663
1664 return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
1665}
1666
1667TemplateName TemplateInstantiator::TransformTemplateName(
1668 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1669 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1670 bool AllowInjectedClassName) {
1671 if (TemplateTemplateParmDecl *TTP
1672 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1673 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1674 // If the corresponding template argument is NULL or non-existent, it's
1675 // because we are performing instantiation from explicitly-specified
1676 // template arguments in a function template, but there were some
1677 // arguments left unspecified.
1678 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1679 TTP->getPosition()))
1680 return Name;
1681
1682 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1683
1684 if (TemplateArgs.isRewrite()) {
1685 // We're rewriting the template parameter as a reference to another
1686 // template parameter.
1687 if (Arg.getKind() == TemplateArgument::Pack) {
1688 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&(static_cast <bool> (Arg.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() && "unexpected pack arguments in template rewrite"
) ? void (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1689, __extension__
__PRETTY_FUNCTION__))
1689 "unexpected pack arguments in template rewrite")(static_cast <bool> (Arg.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() && "unexpected pack arguments in template rewrite"
) ? void (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1689, __extension__
__PRETTY_FUNCTION__))
;
1690 Arg = Arg.pack_begin()->getPackExpansionPattern();
1691 }
1692 assert(Arg.getKind() == TemplateArgument::Template &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Template && "unexpected nontype template argument kind in template rewrite"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Template && \"unexpected nontype template argument kind in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1693, __extension__
__PRETTY_FUNCTION__))
1693 "unexpected nontype template argument kind in template rewrite")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Template && "unexpected nontype template argument kind in template rewrite"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Template && \"unexpected nontype template argument kind in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1693, __extension__
__PRETTY_FUNCTION__))
;
1694 return Arg.getAsTemplate();
1695 }
1696
1697 auto [AssociatedDecl, Final] =
1698 TemplateArgs.getAssociatedDecl(TTP->getDepth());
1699 std::optional<unsigned> PackIndex;
1700 if (TTP->isParameterPack()) {
1701 assert(Arg.getKind() == TemplateArgument::Pack &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1702, __extension__
__PRETTY_FUNCTION__))
1702 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1702, __extension__
__PRETTY_FUNCTION__))
;
1703
1704 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1705 // We have the template argument pack to substitute, but we're not
1706 // actually expanding the enclosing pack expansion yet. So, just
1707 // keep the entire argument pack.
1708 return getSema().Context.getSubstTemplateTemplateParmPack(
1709 Arg, AssociatedDecl, TTP->getIndex(), Final);
1710 }
1711
1712 PackIndex = getPackIndex(Arg);
1713 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1714 }
1715
1716 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1717 assert(!Template.isNull() && "Null template template argument")(static_cast <bool> (!Template.isNull() && "Null template template argument"
) ? void (0) : __assert_fail ("!Template.isNull() && \"Null template template argument\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1717, __extension__
__PRETTY_FUNCTION__))
;
1718 assert(!Template.getAsQualifiedTemplateName() &&(static_cast <bool> (!Template.getAsQualifiedTemplateName
() && "template decl to substitute is qualified?") ? void
(0) : __assert_fail ("!Template.getAsQualifiedTemplateName() && \"template decl to substitute is qualified?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1719, __extension__
__PRETTY_FUNCTION__))
1719 "template decl to substitute is qualified?")(static_cast <bool> (!Template.getAsQualifiedTemplateName
() && "template decl to substitute is qualified?") ? void
(0) : __assert_fail ("!Template.getAsQualifiedTemplateName() && \"template decl to substitute is qualified?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1719, __extension__
__PRETTY_FUNCTION__))
;
1720
1721 if (Final)
1722 return Template;
1723 return getSema().Context.getSubstTemplateTemplateParm(
1724 Template, AssociatedDecl, TTP->getIndex(), PackIndex);
1725 }
1726 }
1727
1728 if (SubstTemplateTemplateParmPackStorage *SubstPack
1729 = Name.getAsSubstTemplateTemplateParmPack()) {
1730 if (getSema().ArgumentPackSubstitutionIndex == -1)
1731 return Name;
1732
1733 TemplateArgument Pack = SubstPack->getArgumentPack();
1734 TemplateName Template =
1735 getPackSubstitutedTemplateArgument(getSema(), Pack).getAsTemplate();
1736 if (SubstPack->getFinal())
1737 return Template;
1738 return getSema().Context.getSubstTemplateTemplateParm(
1739 Template.getNameToSubstitute(), SubstPack->getAssociatedDecl(),
1740 SubstPack->getIndex(), getPackIndex(Pack));
1741 }
1742
1743 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1744 FirstQualifierInScope,
1745 AllowInjectedClassName);
1746}
1747
1748ExprResult
1749TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1750 if (!E->isTypeDependent())
1751 return E;
1752
1753 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
1754}
1755
1756ExprResult
1757TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1758 NonTypeTemplateParmDecl *NTTP) {
1759 // If the corresponding template argument is NULL or non-existent, it's
1760 // because we are performing instantiation from explicitly-specified
1761 // template arguments in a function template, but there were some
1762 // arguments left unspecified.
1763 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1764 NTTP->getPosition()))
1765 return E;
1766
1767 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1768
1769 if (TemplateArgs.isRewrite()) {
1770 // We're rewriting the template parameter as a reference to another
1771 // template parameter.
1772 if (Arg.getKind() == TemplateArgument::Pack) {
1773 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&(static_cast <bool> (Arg.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() && "unexpected pack arguments in template rewrite"
) ? void (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1774, __extension__
__PRETTY_FUNCTION__))
1774 "unexpected pack arguments in template rewrite")(static_cast <bool> (Arg.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() && "unexpected pack arguments in template rewrite"
) ? void (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1774, __extension__
__PRETTY_FUNCTION__))
;
1775 Arg = Arg.pack_begin()->getPackExpansionPattern();
1776 }
1777 assert(Arg.getKind() == TemplateArgument::Expression &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Expression && "unexpected nontype template argument kind in template rewrite"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Expression && \"unexpected nontype template argument kind in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1778, __extension__
__PRETTY_FUNCTION__))
1778 "unexpected nontype template argument kind in template rewrite")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Expression && "unexpected nontype template argument kind in template rewrite"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Expression && \"unexpected nontype template argument kind in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1778, __extension__
__PRETTY_FUNCTION__))
;
1779 // FIXME: This can lead to the same subexpression appearing multiple times
1780 // in a complete expression.
1781 return Arg.getAsExpr();
1782 }
1783
1784 auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
1785 std::optional<unsigned> PackIndex;
1786 if (NTTP->isParameterPack()) {
1787 assert(Arg.getKind() == TemplateArgument::Pack &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1788, __extension__
__PRETTY_FUNCTION__))
1788 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1788, __extension__
__PRETTY_FUNCTION__))
;
1789
1790 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1791 // We have an argument pack, but we can't select a particular argument
1792 // out of it yet. Therefore, we'll build an expression to hold on to that
1793 // argument pack.
1794 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1795 E->getLocation(),
1796 NTTP->getDeclName());
1797 if (TargetType.isNull())
1798 return ExprError();
1799
1800 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
1801 if (TargetType->isRecordType())
1802 ExprType.addConst();
1803 // FIXME: Pass in Final.
1804 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1805 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
1806 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
1807 }
1808 PackIndex = getPackIndex(Arg);
1809 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1810 }
1811 // FIXME: Don't put subst node on Final replacement.
1812 return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
1813 Arg, PackIndex);
1814}
1815
1816const LoopHintAttr *
1817TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1818 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1819
1820 if (TransformedExpr == LH->getValue())
1821 return LH;
1822
1823 // Generate error if there is a problem with the value.
1824 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1825 return LH;
1826
1827 // Create new LoopHintValueAttr with integral expression in place of the
1828 // non-type template parameter.
1829 return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
1830 LH->getState(), TransformedExpr, *LH);
1831}
1832const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
1833 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
1834 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
1835 return nullptr;
1836
1837 return A;
1838}
1839const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
1840 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
1841 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
1842 return nullptr;
1843
1844 return A;
1845}
1846
1847ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1848 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
1849 SourceLocation loc, TemplateArgument arg,
1850 std::optional<unsigned> PackIndex) {
1851 ExprResult result;
1852
1853 // Determine the substituted parameter type. We can usually infer this from
1854 // the template argument, but not always.
1855 auto SubstParamType = [&] {
1856 QualType T;
1857 if (parm->isExpandedParameterPack())
1858 T = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1859 else
1860 T = parm->getType();
1861 if (parm->isParameterPack() && isa<PackExpansionType>(T))
1862 T = cast<PackExpansionType>(T)->getPattern();
1863 return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
1864 };
1865
1866 bool refParam = false;
1867
1868 // The template argument itself might be an expression, in which case we just
1869 // return that expression. This happens when substituting into an alias
1870 // template.
1871 if (arg.getKind() == TemplateArgument::Expression) {
1872 Expr *argExpr = arg.getAsExpr();
1873 result = argExpr;
1874 if (argExpr->isLValue()) {
1875 if (argExpr->getType()->isRecordType()) {
1876 // Check whether the parameter was actually a reference.
1877 QualType paramType = SubstParamType();
1878 if (paramType.isNull())
1879 return ExprError();
1880 refParam = paramType->isReferenceType();
1881 } else {
1882 refParam = true;
1883 }
1884 }
1885 } else if (arg.getKind() == TemplateArgument::Declaration ||
1886 arg.getKind() == TemplateArgument::NullPtr) {
1887 ValueDecl *VD;
1888 if (arg.getKind() == TemplateArgument::Declaration) {
1889 VD = arg.getAsDecl();
1890
1891 // Find the instantiation of the template argument. This is
1892 // required for nested templates.
1893 VD = cast_or_null<ValueDecl>(
1894 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1895 if (!VD)
1896 return ExprError();
1897 } else {
1898 // Propagate NULL template argument.
1899 VD = nullptr;
1900 }
1901
1902 QualType paramType = VD ? arg.getParamTypeForDecl() : arg.getNullPtrType();
1903 assert(!paramType.isNull() && "type substitution failed for param type")(static_cast <bool> (!paramType.isNull() && "type substitution failed for param type"
) ? void (0) : __assert_fail ("!paramType.isNull() && \"type substitution failed for param type\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1903, __extension__
__PRETTY_FUNCTION__))
;
1904 assert(!paramType->isDependentType() && "param type still dependent")(static_cast <bool> (!paramType->isDependentType() &&
"param type still dependent") ? void (0) : __assert_fail ("!paramType->isDependentType() && \"param type still dependent\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1904, __extension__
__PRETTY_FUNCTION__))
;
1905 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
1906 refParam = paramType->isReferenceType();
1907 } else {
1908 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1909 assert(result.isInvalid() ||(static_cast <bool> (result.isInvalid() || SemaRef.Context
.hasSameType(result.get()->getType(), arg.getIntegralType(
))) ? void (0) : __assert_fail ("result.isInvalid() || SemaRef.Context.hasSameType(result.get()->getType(), arg.getIntegralType())"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1911, __extension__
__PRETTY_FUNCTION__))
1910 SemaRef.Context.hasSameType(result.get()->getType(),(static_cast <bool> (result.isInvalid() || SemaRef.Context
.hasSameType(result.get()->getType(), arg.getIntegralType(
))) ? void (0) : __assert_fail ("result.isInvalid() || SemaRef.Context.hasSameType(result.get()->getType(), arg.getIntegralType())"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1911, __extension__
__PRETTY_FUNCTION__))
1911 arg.getIntegralType()))(static_cast <bool> (result.isInvalid() || SemaRef.Context
.hasSameType(result.get()->getType(), arg.getIntegralType(
))) ? void (0) : __assert_fail ("result.isInvalid() || SemaRef.Context.hasSameType(result.get()->getType(), arg.getIntegralType())"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1911, __extension__
__PRETTY_FUNCTION__))
;
1912 }
1913
1914 if (result.isInvalid())
1915 return ExprError();
1916
1917 Expr *resultExpr = result.get();
1918 // FIXME: Don't put subst node on final replacement.
1919 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1920 resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
1921 AssociatedDecl, parm->getIndex(), PackIndex, refParam);
1922}
1923
1924ExprResult
1925TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1926 SubstNonTypeTemplateParmPackExpr *E) {
1927 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1928 // We aren't expanding the parameter pack, so just return ourselves.
1929 return E;
1930 }
1931
1932 TemplateArgument Pack = E->getArgumentPack();
1933 TemplateArgument Arg = getPackSubstitutedTemplateArgument(getSema(), Pack);
1934 // FIXME: Don't put subst node on final replacement.
1935 return transformNonTypeTemplateParmRef(
1936 E->getAssociatedDecl(), E->getParameterPack(),
1937 E->getParameterPackLocation(), Arg, getPackIndex(Pack));
1938}
1939
1940ExprResult
1941TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
1942 SubstNonTypeTemplateParmExpr *E) {
1943 ExprResult SubstReplacement = E->getReplacement();
1944 if (!isa<ConstantExpr>(SubstReplacement.get()))
1945 SubstReplacement = TransformExpr(E->getReplacement());
1946 if (SubstReplacement.isInvalid())
1947 return true;
1948 QualType SubstType = TransformType(E->getParameterType(getSema().Context));
1949 if (SubstType.isNull())
1950 return true;
1951 // The type may have been previously dependent and not now, which means we
1952 // might have to implicit cast the argument to the new type, for example:
1953 // template<auto T, decltype(T) U>
1954 // concept C = sizeof(U) == 4;
1955 // void foo() requires C<2, 'a'> { }
1956 // When normalizing foo(), we first form the normalized constraints of C:
1957 // AtomicExpr(sizeof(U) == 4,
1958 // U=SubstNonTypeTemplateParmExpr(Param=U,
1959 // Expr=DeclRef(U),
1960 // Type=decltype(T)))
1961 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
1962 // produce:
1963 // AtomicExpr(sizeof(U) == 4,
1964 // U=SubstNonTypeTemplateParmExpr(Param=U,
1965 // Expr=ImpCast(
1966 // decltype(2),
1967 // SubstNTTPE(Param=U, Expr='a',
1968 // Type=char)),
1969 // Type=decltype(2)))
1970 // The call to CheckTemplateArgument here produces the ImpCast.
1971 TemplateArgument SugaredConverted, CanonicalConverted;
1972 if (SemaRef
1973 .CheckTemplateArgument(E->getParameter(), SubstType,
1974 SubstReplacement.get(), SugaredConverted,
1975 CanonicalConverted, Sema::CTAK_Specified)
1976 .isInvalid())
1977 return true;
1978 return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
1979 E->getParameter(), E->getExprLoc(),
1980 SugaredConverted, E->getPackIndex());
1981}
1982
1983ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
1984 SourceLocation Loc) {
1985 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1986 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1987}
1988
1989ExprResult
1990TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1991 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1992 // We can expand this parameter pack now.
1993 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1994 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
1995 if (!VD)
1996 return ExprError();
1997 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
1998 }
1999
2000 QualType T = TransformType(E->getType());
2001 if (T.isNull())
2002 return ExprError();
2003
2004 // Transform each of the parameter expansions into the corresponding
2005 // parameters in the instantiation of the function decl.
2006 SmallVector<VarDecl *, 8> Vars;
2007 Vars.reserve(E->getNumExpansions());
2008 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2009 I != End; ++I) {
2010 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
2011 if (!D)
2012 return ExprError();
2013 Vars.push_back(D);
2014 }
2015
2016 auto *PackExpr =
2017 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
2018 E->getParameterPackLocation(), Vars);
2019 getSema().MarkFunctionParmPackReferenced(PackExpr);
2020 return PackExpr;
2021}
2022
2023ExprResult
2024TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2025 VarDecl *PD) {
2026 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2027 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2028 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2029 assert(Found && "no instantiation for parameter pack")(static_cast <bool> (Found && "no instantiation for parameter pack"
) ? void (0) : __assert_fail ("Found && \"no instantiation for parameter pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2029, __extension__
__PRETTY_FUNCTION__))
;
2030
2031 Decl *TransformedDecl;
2032 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
2033 // If this is a reference to a function parameter pack which we can
2034 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2035 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2036 QualType T = TransformType(E->getType());
2037 if (T.isNull())
2038 return ExprError();
2039 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2040 E->getExprLoc(), *Pack);
2041 getSema().MarkFunctionParmPackReferenced(PackExpr);
2042 return PackExpr;
2043 }
2044
2045 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
2046 } else {
2047 TransformedDecl = Found->get<Decl*>();
2048 }
2049
2050 // We have either an unexpanded pack or a specific expansion.
2051 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
2052}
2053
2054ExprResult
2055TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2056 NamedDecl *D = E->getDecl();
2057
2058 // Handle references to non-type template parameters and non-type template
2059 // parameter packs.
2060 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2061 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2062 return TransformTemplateParmRefExpr(E, NTTP);
2063
2064 // We have a non-type template parameter that isn't fully substituted;
2065 // FindInstantiatedDecl will find it in the local instantiation scope.
2066 }
2067
2068 // Handle references to function parameter packs.
2069 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2070 if (PD->isParameterPack())
2071 return TransformFunctionParmPackRefExpr(E, PD);
2072
2073 return inherited::TransformDeclRefExpr(E);
2074}
2075
2076ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2077 CXXDefaultArgExpr *E) {
2078 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->(static_cast <bool> (!cast<FunctionDecl>(E->getParam
()->getDeclContext())-> getDescribedFunctionTemplate() &&
"Default arg expressions are never formed in dependent cases."
) ? void (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2080, __extension__
__PRETTY_FUNCTION__))
2079 getDescribedFunctionTemplate() &&(static_cast <bool> (!cast<FunctionDecl>(E->getParam
()->getDeclContext())-> getDescribedFunctionTemplate() &&
"Default arg expressions are never formed in dependent cases."
) ? void (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2080, __extension__
__PRETTY_FUNCTION__))
2080 "Default arg expressions are never formed in dependent cases.")(static_cast <bool> (!cast<FunctionDecl>(E->getParam
()->getDeclContext())-> getDescribedFunctionTemplate() &&
"Default arg expressions are never formed in dependent cases."
) ? void (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2080, __extension__
__PRETTY_FUNCTION__))
;
2081 return SemaRef.BuildCXXDefaultArgExpr(
2082 E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
2083 E->getParam());
2084}
2085
2086template<typename Fn>
2087QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2088 FunctionProtoTypeLoc TL,
2089 CXXRecordDecl *ThisContext,
2090 Qualifiers ThisTypeQuals,
2091 Fn TransformExceptionSpec) {
2092 // We need a local instantiation scope for this function prototype.
2093 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
2094 return inherited::TransformFunctionProtoType(
2095 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2096}
2097
2098ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2099 ParmVarDecl *OldParm, int indexAdjustment,
2100 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
2101 auto NewParm = SemaRef.SubstParmVarDecl(
2102 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2103 ExpectParameterPack, EvaluateConstraints);
2104 if (NewParm && SemaRef.getLangOpts().OpenCL)
2105 SemaRef.deduceOpenCLAddressSpace(NewParm);
2106 return NewParm;
2107}
2108
2109QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2110 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2111 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
2112 TemplateArgument Arg, SourceLocation NameLoc) {
2113 QualType Replacement = Arg.getAsType();
2114
2115 // If the template parameter had ObjC lifetime qualifiers,
2116 // then any such qualifiers on the replacement type are ignored.
2117 if (SuppressObjCLifetime) {
2118 Qualifiers RQs;
2119 RQs = Replacement.getQualifiers();
2120 RQs.removeObjCLifetime();
2121 Replacement =
2122 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2123 }
2124
2125 if (Final) {
2126 TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
2127 return Replacement;
2128 }
2129 // TODO: only do this uniquing once, at the start of instantiation.
2130 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2131 Replacement, AssociatedDecl, Index, PackIndex);
2132 SubstTemplateTypeParmTypeLoc NewTL =
2133 TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
2134 NewTL.setNameLoc(NameLoc);
2135 return Result;
2136}
2137
2138QualType
2139TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2140 TemplateTypeParmTypeLoc TL,
2141 bool SuppressObjCLifetime) {
2142 const TemplateTypeParmType *T = TL.getTypePtr();
2143 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2144 // Replace the template type parameter with its corresponding
2145 // template argument.
2146
2147 // If the corresponding template argument is NULL or doesn't exist, it's
2148 // because we are performing instantiation from explicitly-specified
2149 // template arguments in a function template class, but there were some
2150 // arguments left unspecified.
2151 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2152 TemplateTypeParmTypeLoc NewTL
2153 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
2154 NewTL.setNameLoc(TL.getNameLoc());
2155 return TL.getType();
2156 }
2157
2158 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2159
2160 if (TemplateArgs.isRewrite()) {
2161 // We're rewriting the template parameter as a reference to another
2162 // template parameter.
2163 if (Arg.getKind() == TemplateArgument::Pack) {
2164 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&(static_cast <bool> (Arg.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() && "unexpected pack arguments in template rewrite"
) ? void (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2165, __extension__
__PRETTY_FUNCTION__))
2165 "unexpected pack arguments in template rewrite")(static_cast <bool> (Arg.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() && "unexpected pack arguments in template rewrite"
) ? void (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2165, __extension__
__PRETTY_FUNCTION__))
;
2166 Arg = Arg.pack_begin()->getPackExpansionPattern();
2167 }
2168 assert(Arg.getKind() == TemplateArgument::Type &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Type && "unexpected nontype template argument kind in template rewrite"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"unexpected nontype template argument kind in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2169, __extension__
__PRETTY_FUNCTION__))
2169 "unexpected nontype template argument kind in template rewrite")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Type && "unexpected nontype template argument kind in template rewrite"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"unexpected nontype template argument kind in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2169, __extension__
__PRETTY_FUNCTION__))
;
2170 QualType NewT = Arg.getAsType();
2171 assert(isa<TemplateTypeParmType>(NewT) &&(static_cast <bool> (isa<TemplateTypeParmType>(NewT
) && "type parm not rewritten to type parm") ? void (
0) : __assert_fail ("isa<TemplateTypeParmType>(NewT) && \"type parm not rewritten to type parm\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2172, __extension__
__PRETTY_FUNCTION__))
2172 "type parm not rewritten to type parm")(static_cast <bool> (isa<TemplateTypeParmType>(NewT
) && "type parm not rewritten to type parm") ? void (
0) : __assert_fail ("isa<TemplateTypeParmType>(NewT) && \"type parm not rewritten to type parm\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2172, __extension__
__PRETTY_FUNCTION__))
;
2173 auto NewTL = TLB.push<TemplateTypeParmTypeLoc>(NewT);
2174 NewTL.setNameLoc(TL.getNameLoc());
2175 return NewT;
2176 }
2177
2178 auto [AssociatedDecl, Final] =
2179 TemplateArgs.getAssociatedDecl(T->getDepth());
2180 std::optional<unsigned> PackIndex;
2181 if (T->isParameterPack()) {
2182 assert(Arg.getKind() == TemplateArgument::Pack &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2183, __extension__
__PRETTY_FUNCTION__))
2183 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2183, __extension__
__PRETTY_FUNCTION__))
;
2184
2185 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2186 // We have the template argument pack, but we're not expanding the
2187 // enclosing pack expansion yet. Just save the template argument
2188 // pack for later substitution.
2189 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2190 AssociatedDecl, T->getIndex(), Final, Arg);
2191 SubstTemplateTypeParmPackTypeLoc NewTL
2192 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2193 NewTL.setNameLoc(TL.getNameLoc());
2194 return Result;
2195 }
2196
2197 // PackIndex starts from last element.
2198 PackIndex = getPackIndex(Arg);
2199 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2200 }
2201
2202 assert(Arg.getKind() == TemplateArgument::Type &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Type && "Template argument kind mismatch") ? void (0)
: __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"Template argument kind mismatch\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2203, __extension__
__PRETTY_FUNCTION__))
2203 "Template argument kind mismatch")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Type && "Template argument kind mismatch") ? void (0)
: __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"Template argument kind mismatch\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2203, __extension__
__PRETTY_FUNCTION__))
;
2204
2205 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2206 AssociatedDecl, T->getIndex(),
2207 PackIndex, Arg, TL.getNameLoc());
2208 }
2209
2210 // The template type parameter comes from an inner template (e.g.,
2211 // the template parameter list of a member template inside the
2212 // template we are instantiating). Create a new template type
2213 // parameter with the template "level" reduced by one.
2214 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2215 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2216 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2217 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2218 QualType Result = getSema().Context.getTemplateTypeParmType(
2219 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2220 T->isParameterPack(), NewTTPDecl);
2221 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
2222 NewTL.setNameLoc(TL.getNameLoc());
2223 return Result;
2224}
2225
2226QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2227 TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL,
2228 bool SuppressObjCLifetime) {
2229 const SubstTemplateTypeParmPackType *T = TL.getTypePtr();
2230
2231 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2232
2233 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2234 // We aren't expanding the parameter pack, so just return ourselves.
2235 QualType Result = TL.getType();
2236 if (NewReplaced != T->getAssociatedDecl())
2237 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2238 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2239 SubstTemplateTypeParmPackTypeLoc NewTL =
2240 TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2241 NewTL.setNameLoc(TL.getNameLoc());
2242 return Result;
2243 }
2244
2245 TemplateArgument Pack = T->getArgumentPack();
2246 TemplateArgument Arg = getPackSubstitutedTemplateArgument(getSema(), Pack);
2247 return BuildSubstTemplateTypeParmType(
2248 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2249 getPackIndex(Pack), Arg, TL.getNameLoc());
2250}
2251
2252template<typename EntityPrinter>
2253static concepts::Requirement::SubstitutionDiagnostic *
2254createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
2255 SmallString<128> Message;
2256 SourceLocation ErrorLoc;
2257 if (Info.hasSFINAEDiagnostic()) {
2258 PartialDiagnosticAt PDA(SourceLocation(),
2259 PartialDiagnostic::NullDiagnostic{});
2260 Info.takeSFINAEDiagnostic(PDA);
2261 PDA.second.EmitToString(S.getDiagnostics(), Message);
2262 ErrorLoc = PDA.first;
2263 } else {
2264 ErrorLoc = Info.getLocation();
2265 }
2266 char *MessageBuf = new (S.Context) char[Message.size()];
2267 std::copy(Message.begin(), Message.end(), MessageBuf);
2268 SmallString<128> Entity;
2269 llvm::raw_svector_ostream OS(Entity);
2270 Printer(OS);
2271 char *EntityBuf = new (S.Context) char[Entity.size()];
2272 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2273 return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
2274 StringRef(EntityBuf, Entity.size()), ErrorLoc,
2275 StringRef(MessageBuf, Message.size())};
2276}
2277
2278ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2279 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2280 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
2281 SmallVectorImpl<QualType> &PTypes,
2282 SmallVectorImpl<ParmVarDecl *> &TransParams,
2283 Sema::ExtParameterInfoBuilder &PInfos) {
2284
2285 TemplateDeductionInfo Info(KWLoc);
2286 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2287 RE, Info,
2288 SourceRange{KWLoc, RBraceLoc});
2289 Sema::SFINAETrap Trap(SemaRef);
2290
2291 unsigned ErrorIdx;
2292 if (getDerived().TransformFunctionTypeParams(
2293 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2294 &TransParams, PInfos, &ErrorIdx) ||
2295 Trap.hasErrorOccurred()) {
2296 SmallVector<concepts::Requirement *, 4> TransReqs;
2297 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2298 // Add a 'failed' Requirement to contain the error that caused the failure
2299 // here.
2300 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2301 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2302 return getDerived().RebuildRequiresExpr(KWLoc, Body, TransParams, TransReqs,
2303 RBraceLoc);
2304 }
2305
2306 return ExprResult{};
2307}
2308
2309concepts::TypeRequirement *
2310TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2311 if (!Req->isDependent() && !AlwaysRebuild())
2312 return Req;
2313 if (Req->isSubstitutionFailure()) {
2314 if (AlwaysRebuild())
2315 return RebuildTypeRequirement(
2316 Req->getSubstitutionDiagnostic());
2317 return Req;
2318 }
2319
2320 Sema::SFINAETrap Trap(SemaRef);
2321 TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
2322 Sema::InstantiatingTemplate TypeInst(SemaRef,
2323 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2324 Req->getType()->getTypeLoc().getSourceRange());
2325 if (TypeInst.isInvalid())
2326 return nullptr;
2327 TypeSourceInfo *TransType = TransformType(Req->getType());
2328 if (!TransType || Trap.hasErrorOccurred())
2329 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2330 [&] (llvm::raw_ostream& OS) {
2331 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2332 }));
2333 return RebuildTypeRequirement(TransType);
2334}
2335
2336concepts::ExprRequirement *
2337TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2338 if (!Req->isDependent() && !AlwaysRebuild())
2339 return Req;
2340
2341 Sema::SFINAETrap Trap(SemaRef);
2342
2343 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2344 TransExpr;
2345 if (Req->isExprSubstitutionFailure())
2346 TransExpr = Req->getExprSubstitutionDiagnostic();
2347 else {
2348 Expr *E = Req->getExpr();
2349 TemplateDeductionInfo Info(E->getBeginLoc());
2350 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2351 E->getSourceRange());
2352 if (ExprInst.isInvalid())
2353 return nullptr;
2354 ExprResult TransExprRes = TransformExpr(E);
2355 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2356 TransExprRes.get()->hasPlaceholderType())
2357 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2358 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2359 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2360 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2361 });
2362 else
2363 TransExpr = TransExprRes.get();
2364 }
2365
2366 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2367 const auto &RetReq = Req->getReturnTypeRequirement();
2368 if (RetReq.isEmpty())
2369 TransRetReq.emplace();
2370 else if (RetReq.isSubstitutionFailure())
2371 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2372 else if (RetReq.isTypeConstraint()) {
2373 TemplateParameterList *OrigTPL =
2374 RetReq.getTypeConstraintTemplateParameterList();
2375 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2376 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
2377 Req, Info, OrigTPL->getSourceRange());
2378 if (TPLInst.isInvalid())
2379 return nullptr;
2380 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2381 if (!TPL)
2382 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2383 [&] (llvm::raw_ostream& OS) {
2384 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2385 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2386 }));
2387 else {
2388 TPLInst.Clear();
2389 TransRetReq.emplace(TPL);
2390 }
2391 }
2392 assert(TransRetReq && "All code paths leading here must set TransRetReq")(static_cast <bool> (TransRetReq && "All code paths leading here must set TransRetReq"
) ? void (0) : __assert_fail ("TransRetReq && \"All code paths leading here must set TransRetReq\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2392, __extension__
__PRETTY_FUNCTION__))
;
2393 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2394 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2395 std::move(*TransRetReq));
2396 return RebuildExprRequirement(
2397 TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
2398 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2399}
2400
2401concepts::NestedRequirement *
2402TemplateInstantiator::TransformNestedRequirement(
2403 concepts::NestedRequirement *Req) {
2404 if (!Req->isDependent() && !AlwaysRebuild())
2405 return Req;
2406 if (Req->hasInvalidConstraint()) {
2407 if (AlwaysRebuild())
2408 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2409 Req->getConstraintSatisfaction());
2410 return Req;
2411 }
2412 Sema::InstantiatingTemplate ReqInst(SemaRef,
2413 Req->getConstraintExpr()->getBeginLoc(), Req,
2414 Sema::InstantiatingTemplate::ConstraintsCheck{},
2415 Req->getConstraintExpr()->getSourceRange());
2416
2417 ExprResult TransConstraint;
2418 ConstraintSatisfaction Satisfaction;
2419 TemplateDeductionInfo Info(Req->getConstraintExpr()->getBeginLoc());
2420 {
2421 EnterExpressionEvaluationContext ContextRAII(
2422 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2423 Sema::SFINAETrap Trap(SemaRef);
2424 Sema::InstantiatingTemplate ConstrInst(SemaRef,
2425 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2426 Req->getConstraintExpr()->getSourceRange());
2427 if (ConstrInst.isInvalid())
2428 return nullptr;
2429 llvm::SmallVector<Expr *> Result;
2430 if (!SemaRef.CheckConstraintSatisfaction(
2431 nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
2432 Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
2433 !Result.empty())
2434 TransConstraint = Result[0];
2435 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "(static_cast <bool> (!Trap.hasErrorOccurred() &&
"Substitution failures must be handled " "by CheckConstraintSatisfaction."
) ? void (0) : __assert_fail ("!Trap.hasErrorOccurred() && \"Substitution failures must be handled \" \"by CheckConstraintSatisfaction.\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2436, __extension__
__PRETTY_FUNCTION__))
2436 "by CheckConstraintSatisfaction.")(static_cast <bool> (!Trap.hasErrorOccurred() &&
"Substitution failures must be handled " "by CheckConstraintSatisfaction."
) ? void (0) : __assert_fail ("!Trap.hasErrorOccurred() && \"Substitution failures must be handled \" \"by CheckConstraintSatisfaction.\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2436, __extension__
__PRETTY_FUNCTION__))
;
2437 }
2438 if (TransConstraint.isUsable() &&
2439 TransConstraint.get()->isInstantiationDependent())
2440 return new (SemaRef.Context)
2441 concepts::NestedRequirement(TransConstraint.get());
2442 if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2443 Satisfaction.HasSubstitutionFailure()) {
2444 SmallString<128> Entity;
2445 llvm::raw_svector_ostream OS(Entity);
2446 Req->getConstraintExpr()->printPretty(OS, nullptr,
2447 SemaRef.getPrintingPolicy());
2448 char *EntityBuf = new (SemaRef.Context) char[Entity.size()];
2449 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2450 return new (SemaRef.Context) concepts::NestedRequirement(
2451 SemaRef.Context, StringRef(EntityBuf, Entity.size()), Satisfaction);
2452 }
2453 return new (SemaRef.Context) concepts::NestedRequirement(
2454 SemaRef.Context, TransConstraint.get(), Satisfaction);
2455}
2456
2457
2458/// Perform substitution on the type T with a given set of template
2459/// arguments.
2460///
2461/// This routine substitutes the given template arguments into the
2462/// type T and produces the instantiated type.
2463///
2464/// \param T the type into which the template arguments will be
2465/// substituted. If this type is not dependent, it will be returned
2466/// immediately.
2467///
2468/// \param Args the template arguments that will be
2469/// substituted for the top-level template parameters within T.
2470///
2471/// \param Loc the location in the source code where this substitution
2472/// is being performed. It will typically be the location of the
2473/// declarator (if we're instantiating the type of some declaration)
2474/// or the location of the type in the source code (if, e.g., we're
2475/// instantiating the type of a cast expression).
2476///
2477/// \param Entity the name of the entity associated with a declaration
2478/// being instantiated (if any). May be empty to indicate that there
2479/// is no such entity (if, e.g., this is a type that occurs as part of
2480/// a cast expression) or that the entity has no name (e.g., an
2481/// unnamed function parameter).
2482///
2483/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
2484/// acceptable as the top level type of the result.
2485///
2486/// \returns If the instantiation succeeds, the instantiated
2487/// type. Otherwise, produces diagnostics and returns a NULL type.
2488TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
2489 const MultiLevelTemplateArgumentList &Args,
2490 SourceLocation Loc,
2491 DeclarationName Entity,
2492 bool AllowDeducedTST) {
2493 assert(!CodeSynthesisContexts.empty() &&(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2495, __extension__
__PRETTY_FUNCTION__))
2494 "Cannot perform an instantiation without some context on the "(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2495, __extension__
__PRETTY_FUNCTION__))
2495 "instantiation stack")(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2495, __extension__
__PRETTY_FUNCTION__))
;
2496
2497 if (!T->getType()->isInstantiationDependentType() &&
2498 !T->getType()->isVariablyModifiedType())
2499 return T;
2500
2501 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2502 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2503 : Instantiator.TransformType(T);
2504}
2505
2506TypeSourceInfo *Sema::SubstType(TypeLoc TL,
2507 const MultiLevelTemplateArgumentList &Args,
2508 SourceLocation Loc,
2509 DeclarationName Entity) {
2510 assert(!CodeSynthesisContexts.empty() &&(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2512, __extension__
__PRETTY_FUNCTION__))
2511 "Cannot perform an instantiation without some context on the "(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2512, __extension__
__PRETTY_FUNCTION__))
2512 "instantiation stack")(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2512, __extension__
__PRETTY_FUNCTION__))
;
2513
2514 if (TL.getType().isNull())
2515 return nullptr;
2516
2517 if (!TL.getType()->isInstantiationDependentType() &&
2518 !TL.getType()->isVariablyModifiedType()) {
2519 // FIXME: Make a copy of the TypeLoc data here, so that we can
2520 // return a new TypeSourceInfo. Inefficient!
2521 TypeLocBuilder TLB;
2522 TLB.pushFullCopy(TL);
2523 return TLB.getTypeSourceInfo(Context, TL.getType());
2524 }
2525
2526 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2527 TypeLocBuilder TLB;
2528 TLB.reserve(TL.getFullDataSize());
2529 QualType Result = Instantiator.TransformType(TLB, TL);
2530 if (Result.isNull())
2531 return nullptr;
2532
2533 return TLB.getTypeSourceInfo(Context, Result);
2534}
2535
2536/// Deprecated form of the above.
2537QualType Sema::SubstType(QualType T,
2538 const MultiLevelTemplateArgumentList &TemplateArgs,
2539 SourceLocation Loc, DeclarationName Entity) {
2540 assert(!CodeSynthesisContexts.empty() &&(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2542, __extension__
__PRETTY_FUNCTION__))
2541 "Cannot perform an instantiation without some context on the "(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2542, __extension__
__PRETTY_FUNCTION__))
2542 "instantiation stack")(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2542, __extension__
__PRETTY_FUNCTION__))
;
2543
2544 // If T is not a dependent type or a variably-modified type, there
2545 // is nothing to do.
2546 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
2547 return T;
2548
2549 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
2550 return Instantiator.TransformType(T);
2551}
2552
2553static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
2554 if (T->getType()->isInstantiationDependentType() ||
2555 T->getType()->isVariablyModifiedType())
2556 return true;
2557
2558 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2559 if (!TL.getAs<FunctionProtoTypeLoc>())
2560 return false;
2561
2562 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
2563 for (ParmVarDecl *P : FP.getParams()) {
2564 // This must be synthesized from a typedef.
2565 if (!P) continue;
2566
2567 // If there are any parameters, a new TypeSourceInfo that refers to the
2568 // instantiated parameters must be built.
2569 return true;
2570 }
2571
2572 return false;
2573}
2574
2575/// A form of SubstType intended specifically for instantiating the
2576/// type of a FunctionDecl. Its purpose is solely to force the
2577/// instantiation of default-argument expressions and to avoid
2578/// instantiating an exception-specification.
2579TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
2580 const MultiLevelTemplateArgumentList &Args,
2581 SourceLocation Loc,
2582 DeclarationName Entity,
2583 CXXRecordDecl *ThisContext,
2584 Qualifiers ThisTypeQuals,
2585 bool EvaluateConstraints) {
2586 assert(!CodeSynthesisContexts.empty() &&(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2588, __extension__
__PRETTY_FUNCTION__))
2587 "Cannot perform an instantiation without some context on the "(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2588, __extension__
__PRETTY_FUNCTION__))
2588 "instantiation stack")(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2588, __extension__
__PRETTY_FUNCTION__))
;
2589
2590 if (!NeedsInstantiationAsFunctionType(T))
2591 return T;
2592
2593 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2594 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2595
2596 TypeLocBuilder TLB;
2597
2598 TypeLoc TL = T->getTypeLoc();
2599 TLB.reserve(TL.getFullDataSize());
2600
2601 QualType Result;
2602
2603 if (FunctionProtoTypeLoc Proto =
2604 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
2605 // Instantiate the type, other than its exception specification. The
2606 // exception specification is instantiated in InitFunctionInstantiation
2607 // once we've built the FunctionDecl.
2608 // FIXME: Set the exception specification to EST_Uninstantiated here,
2609 // instead of rebuilding the function type again later.
2610 Result = Instantiator.TransformFunctionProtoType(
2611 TLB, Proto, ThisContext, ThisTypeQuals,
2612 [](FunctionProtoType::ExceptionSpecInfo &ESI,
2613 bool &Changed) { return false; });
2614 } else {
2615 Result = Instantiator.TransformType(TLB, TL);
2616 }
2617 if (Result.isNull())
2618 return nullptr;
2619
2620 return TLB.getTypeSourceInfo(Context, Result);
2621}
2622
2623bool Sema::SubstExceptionSpec(SourceLocation Loc,
2624 FunctionProtoType::ExceptionSpecInfo &ESI,
2625 SmallVectorImpl<QualType> &ExceptionStorage,
2626 const MultiLevelTemplateArgumentList &Args) {
2627 assert(ESI.Type != EST_Uninstantiated)(static_cast <bool> (ESI.Type != EST_Uninstantiated) ? void
(0) : __assert_fail ("ESI.Type != EST_Uninstantiated", "clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2627, __extension__ __PRETTY_FUNCTION__))
;
2628
2629 bool Changed = false;
2630 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2631 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
2632 Changed);
2633}
2634
2635void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
2636 const MultiLevelTemplateArgumentList &Args) {
2637 FunctionProtoType::ExceptionSpecInfo ESI =
2638 Proto->getExtProtoInfo().ExceptionSpec;
2639
2640 SmallVector<QualType, 4> ExceptionStorage;
2641 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
2642 ESI, ExceptionStorage, Args))
2643 // On error, recover by dropping the exception specification.
2644 ESI.Type = EST_None;
2645
2646 UpdateExceptionSpec(New, ESI);
2647}
2648
2649namespace {
2650
2651 struct GetContainedInventedTypeParmVisitor :
2652 public TypeVisitor<GetContainedInventedTypeParmVisitor,
2653 TemplateTypeParmDecl *> {
2654 using TypeVisitor<GetContainedInventedTypeParmVisitor,
2655 TemplateTypeParmDecl *>::Visit;
2656
2657 TemplateTypeParmDecl *Visit(QualType T) {
2658 if (T.isNull())
2659 return nullptr;
2660 return Visit(T.getTypePtr());
2661 }
2662 // The deduced type itself.
2663 TemplateTypeParmDecl *VisitTemplateTypeParmType(
2664 const TemplateTypeParmType *T) {
2665 if (!T->getDecl() || !T->getDecl()->isImplicit())
2666 return nullptr;
2667 return T->getDecl();
2668 }
2669
2670 // Only these types can contain 'auto' types, and subsequently be replaced
2671 // by references to invented parameters.
2672
2673 TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
2674 return Visit(T->getNamedType());
2675 }
2676
2677 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
2678 return Visit(T->getPointeeType());
2679 }
2680
2681 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
2682 return Visit(T->getPointeeType());
2683 }
2684
2685 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
2686 return Visit(T->getPointeeTypeAsWritten());
2687 }
2688
2689 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
2690 return Visit(T->getPointeeType());
2691 }
2692
2693 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
2694 return Visit(T->getElementType());
2695 }
2696
2697 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
2698 const DependentSizedExtVectorType *T) {
2699 return Visit(T->getElementType());
2700 }
2701
2702 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
2703 return Visit(T->getElementType());
2704 }
2705
2706 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
2707 return VisitFunctionType(T);
2708 }
2709
2710 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
2711 return Visit(T->getReturnType());
2712 }
2713
2714 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
2715 return Visit(T->getInnerType());
2716 }
2717
2718 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
2719 return Visit(T->getModifiedType());
2720 }
2721
2722 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
2723 return Visit(T->getUnderlyingType());
2724 }
2725
2726 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
2727 return Visit(T->getOriginalType());
2728 }
2729
2730 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
2731 return Visit(T->getPattern());
2732 }
2733 };
2734
2735} // namespace
2736
2737bool Sema::SubstTypeConstraint(
2738 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
2739 const MultiLevelTemplateArgumentList &TemplateArgs,
2740 bool EvaluateConstraints) {
2741 const ASTTemplateArgumentListInfo *TemplArgInfo =
2742 TC->getTemplateArgsAsWritten();
2743
2744 if (!EvaluateConstraints) {
2745 Inst->setTypeConstraint(TC->getNestedNameSpecifierLoc(),
2746 TC->getConceptNameInfo(), TC->getNamedConcept(),
2747 TC->getNamedConcept(), TemplArgInfo,
2748 TC->getImmediatelyDeclaredConstraint());
2749 return false;
2750 }
2751
2752 TemplateArgumentListInfo InstArgs;
2753
2754 if (TemplArgInfo) {
2755 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
2756 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
2757 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
2758 InstArgs))
2759 return true;
2760 }
2761 return AttachTypeConstraint(
2762 TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
2763 TC->getNamedConcept(), &InstArgs, Inst,
2764 Inst->isParameterPack()
2765 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2766 ->getEllipsisLoc()
2767 : SourceLocation());
2768}
2769
2770ParmVarDecl *Sema::SubstParmVarDecl(
2771 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
2772 int indexAdjustment, std::optional<unsigned> NumExpansions,
2773 bool ExpectParameterPack, bool EvaluateConstraint) {
2774 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
2775 TypeSourceInfo *NewDI = nullptr;
2776
2777 TypeLoc OldTL = OldDI->getTypeLoc();
2778 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
2779
2780 // We have a function parameter pack. Substitute into the pattern of the
2781 // expansion.
2782 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
2783 OldParm->getLocation(), OldParm->getDeclName());
2784 if (!NewDI)
2785 return nullptr;
2786
2787 if (NewDI->getType()->containsUnexpandedParameterPack()) {
2788 // We still have unexpanded parameter packs, which means that
2789 // our function parameter is still a function parameter pack.
2790 // Therefore, make its type a pack expansion type.
2791 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
2792 NumExpansions);
2793 } else if (ExpectParameterPack) {
2794 // We expected to get a parameter pack but didn't (because the type
2795 // itself is not a pack expansion type), so complain. This can occur when
2796 // the substitution goes through an alias template that "loses" the
2797 // pack expansion.
2798 Diag(OldParm->getLocation(),
2799 diag::err_function_parameter_pack_without_parameter_packs)
2800 << NewDI->getType();
2801 return nullptr;
2802 }
2803 } else {
2804 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
2805 OldParm->getDeclName());
2806 }
2807
2808 if (!NewDI)
2809 return nullptr;
2810
2811 if (NewDI->getType()->isVoidType()) {
2812 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
2813 return nullptr;
2814 }
2815
2816 // In abbreviated templates, TemplateTypeParmDecls with possible
2817 // TypeConstraints are created when the parameter list is originally parsed.
2818 // The TypeConstraints can therefore reference other functions parameters in
2819 // the abbreviated function template, which is why we must instantiate them
2820 // here, when the instantiated versions of those referenced parameters are in
2821 // scope.
2822 if (TemplateTypeParmDecl *TTP =
2823 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
2824 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
2825 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
2826 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
2827 // We will first get here when instantiating the abbreviated function
2828 // template's described function, but we might also get here later.
2829 // Make sure we do not instantiate the TypeConstraint more than once.
2830 if (Inst && !Inst->getTypeConstraint()) {
2831 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
2832 return nullptr;
2833 }
2834 }
2835 }
2836
2837 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
2838 OldParm->getInnerLocStart(),
2839 OldParm->getLocation(),
2840 OldParm->getIdentifier(),
2841 NewDI->getType(), NewDI,
2842 OldParm->getStorageClass());
2843 if (!NewParm)
2844 return nullptr;
2845
2846 // Mark the (new) default argument as uninstantiated (if any).
2847 if (OldParm->hasUninstantiatedDefaultArg()) {
2848 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
2849 NewParm->setUninstantiatedDefaultArg(Arg);
2850 } else if (OldParm->hasUnparsedDefaultArg()) {
2851 NewParm->setUnparsedDefaultArg();
2852 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
2853 } else if (Expr *Arg = OldParm->getDefaultArg()) {
2854 // Default arguments cannot be substituted until the declaration context
2855 // for the associated function or lambda capture class is available.
2856 // This is necessary for cases like the following where construction of
2857 // the lambda capture class for the outer lambda is dependent on the
2858 // parameter types but where the default argument is dependent on the
2859 // outer lambda's declaration context.
2860 // template <typename T>
2861 // auto f() {
2862 // return [](T = []{ return T{}; }()) { return 0; };
2863 // }
2864 NewParm->setUninstantiatedDefaultArg(Arg);
2865 }
2866
2867 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
2868
2869 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
2870 // Add the new parameter to the instantiated parameter pack.
2871 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
2872 } else {
2873 // Introduce an Old -> New mapping
2874 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
2875 }
2876
2877 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
2878 // can be anything, is this right ?
2879 NewParm->setDeclContext(CurContext);
2880
2881 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
2882 OldParm->getFunctionScopeIndex() + indexAdjustment);
2883
2884 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
2885
2886 return NewParm;
2887}
2888
2889/// Substitute the given template arguments into the given set of
2890/// parameters, producing the set of parameter types that would be generated
2891/// from such a substitution.
2892bool Sema::SubstParmTypes(
2893 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
2894 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
2895 const MultiLevelTemplateArgumentList &TemplateArgs,
2896 SmallVectorImpl<QualType> &ParamTypes,
2897 SmallVectorImpl<ParmVarDecl *> *OutParams,
2898 ExtParameterInfoBuilder &ParamInfos) {
2899 assert(!CodeSynthesisContexts.empty() &&(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2901, __extension__
__PRETTY_FUNCTION__))
2900 "Cannot perform an instantiation without some context on the "(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2901, __extension__
__PRETTY_FUNCTION__))
2901 "instantiation stack")(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2901, __extension__
__PRETTY_FUNCTION__))
;
2902
2903 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2904 DeclarationName());
2905 return Instantiator.TransformFunctionTypeParams(
2906 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
2907}
2908
2909/// Substitute the given template arguments into the default argument.
2910bool Sema::SubstDefaultArgument(
2911 SourceLocation Loc,
2912 ParmVarDecl *Param,
2913 const MultiLevelTemplateArgumentList &TemplateArgs,
2914 bool ForCallExpr) {
2915 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
2916 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
2917
2918 EnterExpressionEvaluationContext EvalContext(
2919 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
2920
2921 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
2922 if (Inst.isInvalid())
2923 return true;
2924 if (Inst.isAlreadyInstantiating()) {
2925 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
2926 Param->setInvalidDecl();
2927 return true;
2928 }
2929
2930 ExprResult Result;
2931 {
2932 // C++ [dcl.fct.default]p5:
2933 // The names in the [default argument] expression are bound, and
2934 // the semantic constraints are checked, at the point where the
2935 // default argument expression appears.
2936 ContextRAII SavedContext(*this, FD);
2937 std::unique_ptr<LocalInstantiationScope> LIS;
2938
2939 if (ForCallExpr) {
2940 // When instantiating a default argument due to use in a call expression,
2941 // an instantiation scope that includes the parameters of the callee is
2942 // required to satisfy references from the default argument. For example:
2943 // template<typename T> void f(T a, int = decltype(a)());
2944 // void g() { f(0); }
2945 LIS = std::make_unique<LocalInstantiationScope>(*this);
2946 FunctionDecl *PatternFD = FD->getTemplateInstantiationPattern(
2947 /*ForDefinition*/ false);
2948 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
2949 return true;
2950 }
2951
2952 runWithSufficientStackSpace(Loc, [&] {
2953 Result = SubstInitializer(PatternExpr, TemplateArgs,
2954 /*DirectInit*/false);
2955 });
2956 }
2957 if (Result.isInvalid())
2958 return true;
2959
2960 if (ForCallExpr) {
2961 // Check the expression as an initializer for the parameter.
2962 InitializedEntity Entity
2963 = InitializedEntity::InitializeParameter(Context, Param);
2964 InitializationKind Kind = InitializationKind::CreateCopy(
2965 Param->getLocation(),
2966 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
2967 Expr *ResultE = Result.getAs<Expr>();
2968
2969 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
2970 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
2971 if (Result.isInvalid())
2972 return true;
2973
2974 Result =
2975 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
2976 /*DiscardedValue*/ false);
2977 } else {
2978 // FIXME: Obtain the source location for the '=' token.
2979 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
2980 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
2981 }
2982 if (Result.isInvalid())
2983 return true;
2984
2985 // Remember the instantiated default argument.
2986 Param->setDefaultArg(Result.getAs<Expr>());
2987
2988 return false;
2989}
2990
2991/// Perform substitution on the base class specifiers of the
2992/// given class template specialization.
2993///
2994/// Produces a diagnostic and returns true on error, returns false and
2995/// attaches the instantiated base classes to the class template
2996/// specialization if successful.
2997bool
2998Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
2999 CXXRecordDecl *Pattern,
3000 const MultiLevelTemplateArgumentList &TemplateArgs) {
3001 bool Invalid = false;
3002 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3003 for (const auto &Base : Pattern->bases()) {
3004 if (!Base.getType()->isDependentType()) {
3005 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3006 if (RD->isInvalidDecl())
3007 Instantiation->setInvalidDecl();
3008 }
3009 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3010 continue;
3011 }
3012
3013 SourceLocation EllipsisLoc;
3014 TypeSourceInfo *BaseTypeLoc;
3015 if (Base.isPackExpansion()) {
3016 // This is a pack expansion. See whether we should expand it now, or
3017 // wait until later.
3018 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3019 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
3020 Unexpanded);
3021 bool ShouldExpand = false;
3022 bool RetainExpansion = false;
3023 std::optional<unsigned> NumExpansions;
3024 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
3025 Base.getSourceRange(),
3026 Unexpanded,
3027 TemplateArgs, ShouldExpand,
3028 RetainExpansion,
3029 NumExpansions)) {
3030 Invalid = true;
3031 continue;
3032 }
3033
3034 // If we should expand this pack expansion now, do so.
3035 if (ShouldExpand) {
3036 for (unsigned I = 0; I != *NumExpansions; ++I) {
3037 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3038
3039 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3040 TemplateArgs,
3041 Base.getSourceRange().getBegin(),
3042 DeclarationName());
3043 if (!BaseTypeLoc) {
3044 Invalid = true;
3045 continue;
3046 }
3047
3048 if (CXXBaseSpecifier *InstantiatedBase
3049 = CheckBaseSpecifier(Instantiation,
3050 Base.getSourceRange(),
3051 Base.isVirtual(),
3052 Base.getAccessSpecifierAsWritten(),
3053 BaseTypeLoc,
3054 SourceLocation()))
3055 InstantiatedBases.push_back(InstantiatedBase);
3056 else
3057 Invalid = true;
3058 }
3059
3060 continue;
3061 }
3062
3063 // The resulting base specifier will (still) be a pack expansion.
3064 EllipsisLoc = Base.getEllipsisLoc();
3065 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3066 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3067 TemplateArgs,
3068 Base.getSourceRange().getBegin(),
3069 DeclarationName());
3070 } else {
3071 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3072 TemplateArgs,
3073 Base.getSourceRange().getBegin(),
3074 DeclarationName());
3075 }
3076
3077 if (!BaseTypeLoc) {
3078 Invalid = true;
3079 continue;
3080 }
3081
3082 if (CXXBaseSpecifier *InstantiatedBase
3083 = CheckBaseSpecifier(Instantiation,
3084 Base.getSourceRange(),
3085 Base.isVirtual(),
3086 Base.getAccessSpecifierAsWritten(),
3087 BaseTypeLoc,
3088 EllipsisLoc))
3089 InstantiatedBases.push_back(InstantiatedBase);
3090 else
3091 Invalid = true;
3092 }
3093
3094 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3095 Invalid = true;
3096
3097 return Invalid;
3098}
3099
3100// Defined via #include from SemaTemplateInstantiateDecl.cpp
3101namespace clang {
3102 namespace sema {
3103 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
3104 const MultiLevelTemplateArgumentList &TemplateArgs);
3105 Attr *instantiateTemplateAttributeForDecl(
3106 const Attr *At, ASTContext &C, Sema &S,
3107 const MultiLevelTemplateArgumentList &TemplateArgs);
3108 }
3109}
3110
3111/// Instantiate the definition of a class from a given pattern.
3112///
3113/// \param PointOfInstantiation The point of instantiation within the
3114/// source code.
3115///
3116/// \param Instantiation is the declaration whose definition is being
3117/// instantiated. This will be either a class template specialization
3118/// or a member class of a class template specialization.
3119///
3120/// \param Pattern is the pattern from which the instantiation
3121/// occurs. This will be either the declaration of a class template or
3122/// the declaration of a member class of a class template.
3123///
3124/// \param TemplateArgs The template arguments to be substituted into
3125/// the pattern.
3126///
3127/// \param TSK the kind of implicit or explicit instantiation to perform.
3128///
3129/// \param Complain whether to complain if the class cannot be instantiated due
3130/// to the lack of a definition.
3131///
3132/// \returns true if an error occurred, false otherwise.
3133bool
3134Sema::InstantiateClass(SourceLocation PointOfInstantiation,
3135 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3136 const MultiLevelTemplateArgumentList &TemplateArgs,
3137 TemplateSpecializationKind TSK,
3138 bool Complain) {
3139 CXXRecordDecl *PatternDef
3140 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3141 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3142 Instantiation->getInstantiatedFromMemberClass(),
3143 Pattern, PatternDef, TSK, Complain))
3144 return true;
3145
3146 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3147 std::string Name;
3148 llvm::raw_string_ostream OS(Name);
3149 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3150 /*Qualified=*/true);
3151 return Name;
3152 });
3153
3154 Pattern = PatternDef;
3155
3156 // Record the point of instantiation.
3157 if (MemberSpecializationInfo *MSInfo
3158 = Instantiation->getMemberSpecializationInfo()) {
3159 MSInfo->setTemplateSpecializationKind(TSK);
3160 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3161 } else if (ClassTemplateSpecializationDecl *Spec
3162 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3163 Spec->setTemplateSpecializationKind(TSK);
3164 Spec->setPointOfInstantiation(PointOfInstantiation);
3165 }
3166
3167 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3168 if (Inst.isInvalid())
3169 return true;
3170 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller")(static_cast <bool> (!Inst.isAlreadyInstantiating() &&
"should have been caught by caller") ? void (0) : __assert_fail
("!Inst.isAlreadyInstantiating() && \"should have been caught by caller\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3170, __extension__
__PRETTY_FUNCTION__))
;
3171 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3172 "instantiating class definition");
3173
3174 // Enter the scope of this instantiation. We don't use
3175 // PushDeclContext because we don't have a scope.
3176 ContextRAII SavedContext(*this, Instantiation);
3177 EnterExpressionEvaluationContext EvalContext(
3178 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3179
3180 // If this is an instantiation of a local class, merge this local
3181 // instantiation scope with the enclosing scope. Otherwise, every
3182 // instantiation of a class has its own local instantiation scope.
3183 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3184 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3185
3186 // Some class state isn't processed immediately but delayed till class
3187 // instantiation completes. We may not be ready to handle any delayed state
3188 // already on the stack as it might correspond to a different class, so save
3189 // it now and put it back later.
3190 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3191
3192 // Pull attributes from the pattern onto the instantiation.
3193 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3194
3195 // Start the definition of this instantiation.
3196 Instantiation->startDefinition();
3197
3198 // The instantiation is visible here, even if it was first declared in an
3199 // unimported module.
3200 Instantiation->setVisibleDespiteOwningModule();
3201
3202 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3203 Instantiation->setTagKind(Pattern->getTagKind());
3204
3205 // Do substitution on the base class specifiers.
3206 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3207 Instantiation->setInvalidDecl();
3208
3209 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3210 Instantiator.setEvaluateConstraints(false);
3211 SmallVector<Decl*, 4> Fields;
3212 // Delay instantiation of late parsed attributes.
3213 LateInstantiatedAttrVec LateAttrs;
3214 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3215
3216 bool MightHaveConstexprVirtualFunctions = false;
3217 for (auto *Member : Pattern->decls()) {
3218 // Don't instantiate members not belonging in this semantic context.
3219 // e.g. for:
3220 // @code
3221 // template <int i> class A {
3222 // class B *g;
3223 // };
3224 // @endcode
3225 // 'class B' has the template as lexical context but semantically it is
3226 // introduced in namespace scope.
3227 if (Member->getDeclContext() != Pattern)
3228 continue;
3229
3230 // BlockDecls can appear in a default-member-initializer. They must be the
3231 // child of a BlockExpr, so we only know how to instantiate them from there.
3232 // Similarly, lambda closure types are recreated when instantiating the
3233 // corresponding LambdaExpr.
3234 if (isa<BlockDecl>(Member) ||
3235 (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
3236 continue;
3237
3238 if (Member->isInvalidDecl()) {
3239 Instantiation->setInvalidDecl();
3240 continue;
3241 }
3242
3243 Decl *NewMember = Instantiator.Visit(Member);
3244 if (NewMember) {
3245 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3246 Fields.push_back(Field);
3247 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3248 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3249 // specialization causes the implicit instantiation of the definitions
3250 // of unscoped member enumerations.
3251 // Record a point of instantiation for this implicit instantiation.
3252 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3253 Enum->isCompleteDefinition()) {
3254 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3255 assert(MSInfo && "no spec info for member enum specialization")(static_cast <bool> (MSInfo && "no spec info for member enum specialization"
) ? void (0) : __assert_fail ("MSInfo && \"no spec info for member enum specialization\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3255, __extension__
__PRETTY_FUNCTION__))
;
3256 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
3257 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3258 }
3259 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3260 if (SA->isFailed()) {
3261 // A static_assert failed. Bail out; instantiating this
3262 // class is probably not meaningful.
3263 Instantiation->setInvalidDecl();
3264 break;
3265 }
3266 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3267 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3268 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3269 MightHaveConstexprVirtualFunctions = true;
3270 }
3271
3272 if (NewMember->isInvalidDecl())
3273 Instantiation->setInvalidDecl();
3274 } else {
3275 // FIXME: Eventually, a NULL return will mean that one of the
3276 // instantiations was a semantic disaster, and we'll want to mark the
3277 // declaration invalid.
3278 // For now, we expect to skip some members that we can't yet handle.
3279 }
3280 }
3281
3282 // Finish checking fields.
3283 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3284 SourceLocation(), SourceLocation(), ParsedAttributesView());
3285 CheckCompletedCXXClass(nullptr, Instantiation);
3286
3287 // Default arguments are parsed, if not instantiated. We can go instantiate
3288 // default arg exprs for default constructors if necessary now. Unless we're
3289 // parsing a class, in which case wait until that's finished.
3290 if (ParsingClassDepth == 0)
3291 ActOnFinishCXXNonNestedClass();
3292
3293 // Instantiate late parsed attributes, and attach them to their decls.
3294 // See Sema::InstantiateAttrs
3295 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3296 E = LateAttrs.end(); I != E; ++I) {
3297 assert(CurrentInstantiationScope == Instantiator.getStartingScope())(static_cast <bool> (CurrentInstantiationScope == Instantiator
.getStartingScope()) ? void (0) : __assert_fail ("CurrentInstantiationScope == Instantiator.getStartingScope()"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3297, __extension__
__PRETTY_FUNCTION__))
;
3298 CurrentInstantiationScope = I->Scope;
3299
3300 // Allow 'this' within late-parsed attributes.
3301 auto *ND = cast<NamedDecl>(I->NewDecl);
3302 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3303 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3304 ND->isCXXInstanceMember());
3305
3306 Attr *NewAttr =
3307 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3308 if (NewAttr)
3309 I->NewDecl->addAttr(NewAttr);
3310 LocalInstantiationScope::deleteScopes(I->Scope,
3311 Instantiator.getStartingScope());
3312 }
3313 Instantiator.disableLateAttributeInstantiation();
3314 LateAttrs.clear();
3315
3316 ActOnFinishDelayedMemberInitializers(Instantiation);
3317
3318 // FIXME: We should do something similar for explicit instantiations so they
3319 // end up in the right module.
3320 if (TSK == TSK_ImplicitInstantiation) {
3321 Instantiation->setLocation(Pattern->getLocation());
3322 Instantiation->setLocStart(Pattern->getInnerLocStart());
3323 Instantiation->setBraceRange(Pattern->getBraceRange());
3324 }
3325
3326 if (!Instantiation->isInvalidDecl()) {
3327 // Perform any dependent diagnostics from the pattern.
3328 if (Pattern->isDependentContext())
3329 PerformDependentDiagnostics(Pattern, TemplateArgs);
3330
3331 // Instantiate any out-of-line class template partial
3332 // specializations now.
3333 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
3334 P = Instantiator.delayed_partial_spec_begin(),
3335 PEnd = Instantiator.delayed_partial_spec_end();
3336 P != PEnd; ++P) {
3337 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
3338 P->first, P->second)) {
3339 Instantiation->setInvalidDecl();
3340 break;
3341 }
3342 }
3343
3344 // Instantiate any out-of-line variable template partial
3345 // specializations now.
3346 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
3347 P = Instantiator.delayed_var_partial_spec_begin(),
3348 PEnd = Instantiator.delayed_var_partial_spec_end();
3349 P != PEnd; ++P) {
3350 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
3351 P->first, P->second)) {
3352 Instantiation->setInvalidDecl();
3353 break;
3354 }
3355 }
3356 }
3357
3358 // Exit the scope of this instantiation.
3359 SavedContext.pop();
3360
3361 if (!Instantiation->isInvalidDecl()) {
3362 // Always emit the vtable for an explicit instantiation definition
3363 // of a polymorphic class template specialization. Otherwise, eagerly
3364 // instantiate only constexpr virtual functions in preparation for their use
3365 // in constant evaluation.
3366 if (TSK == TSK_ExplicitInstantiationDefinition)
3367 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3368 else if (MightHaveConstexprVirtualFunctions)
3369 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3370 /*ConstexprOnly*/ true);
3371 }
3372
3373 Consumer.HandleTagDeclDefinition(Instantiation);
3374
3375 return Instantiation->isInvalidDecl();
3376}
3377
3378/// Instantiate the definition of an enum from a given pattern.
3379///
3380/// \param PointOfInstantiation The point of instantiation within the
3381/// source code.
3382/// \param Instantiation is the declaration whose definition is being
3383/// instantiated. This will be a member enumeration of a class
3384/// temploid specialization, or a local enumeration within a
3385/// function temploid specialization.
3386/// \param Pattern The templated declaration from which the instantiation
3387/// occurs.
3388/// \param TemplateArgs The template arguments to be substituted into
3389/// the pattern.
3390/// \param TSK The kind of implicit or explicit instantiation to perform.
3391///
3392/// \return \c true if an error occurred, \c false otherwise.
3393bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3394 EnumDecl *Instantiation, EnumDecl *Pattern,
3395 const MultiLevelTemplateArgumentList &TemplateArgs,
3396 TemplateSpecializationKind TSK) {
3397 EnumDecl *PatternDef = Pattern->getDefinition();
3398 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3399 Instantiation->getInstantiatedFromMemberEnum(),
3400 Pattern, PatternDef, TSK,/*Complain*/true))
3401 return true;
3402 Pattern = PatternDef;
3403
3404 // Record the point of instantiation.
3405 if (MemberSpecializationInfo *MSInfo
3406 = Instantiation->getMemberSpecializationInfo()) {
3407 MSInfo->setTemplateSpecializationKind(TSK);
3408 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3409 }
3410
3411 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3412 if (Inst.isInvalid())
3413 return true;
3414 if (Inst.isAlreadyInstantiating())
3415 return false;
3416 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3417 "instantiating enum definition");
3418
3419 // The instantiation is visible here, even if it was first declared in an
3420 // unimported module.
3421 Instantiation->setVisibleDespiteOwningModule();
3422
3423 // Enter the scope of this instantiation. We don't use
3424 // PushDeclContext because we don't have a scope.
3425 ContextRAII SavedContext(*this, Instantiation);
3426 EnterExpressionEvaluationContext EvalContext(
3427 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3428
3429 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3430
3431 // Pull attributes from the pattern onto the instantiation.
3432 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3433
3434 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3435 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3436
3437 // Exit the scope of this instantiation.
3438 SavedContext.pop();
3439
3440 return Instantiation->isInvalidDecl();
3441}
3442
3443
3444/// Instantiate the definition of a field from the given pattern.
3445///
3446/// \param PointOfInstantiation The point of instantiation within the
3447/// source code.
3448/// \param Instantiation is the declaration whose definition is being
3449/// instantiated. This will be a class of a class temploid
3450/// specialization, or a local enumeration within a function temploid
3451/// specialization.
3452/// \param Pattern The templated declaration from which the instantiation
3453/// occurs.
3454/// \param TemplateArgs The template arguments to be substituted into
3455/// the pattern.
3456///
3457/// \return \c true if an error occurred, \c false otherwise.
3458bool Sema::InstantiateInClassInitializer(
3459 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3460 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3461 // If there is no initializer, we don't need to do anything.
3462 if (!Pattern->hasInClassInitializer())
3463 return false;
3464
3465 assert(Instantiation->getInClassInitStyle() ==(static_cast <bool> (Instantiation->getInClassInitStyle
() == Pattern->getInClassInitStyle() && "pattern and instantiation disagree about init style"
) ? void (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3467, __extension__
__PRETTY_FUNCTION__))
3466 Pattern->getInClassInitStyle() &&(static_cast <bool> (Instantiation->getInClassInitStyle
() == Pattern->getInClassInitStyle() && "pattern and instantiation disagree about init style"
) ? void (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3467, __extension__
__PRETTY_FUNCTION__))
3467 "pattern and instantiation disagree about init style")(static_cast <bool> (Instantiation->getInClassInitStyle
() == Pattern->getInClassInitStyle() && "pattern and instantiation disagree about init style"
) ? void (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3467, __extension__
__PRETTY_FUNCTION__))
;
3468
3469 // Error out if we haven't parsed the initializer of the pattern yet because
3470 // we are waiting for the closing brace of the outer class.
3471 Expr *OldInit = Pattern->getInClassInitializer();
3472 if (!OldInit) {
3473 RecordDecl *PatternRD = Pattern->getParent();
3474 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3475 Diag(PointOfInstantiation,
3476 diag::err_default_member_initializer_not_yet_parsed)
3477 << OutermostClass << Pattern;
3478 Diag(Pattern->getEndLoc(),
3479 diag::note_default_member_initializer_not_yet_parsed);
3480 Instantiation->setInvalidDecl();
3481 return true;
3482 }
3483
3484 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3485 if (Inst.isInvalid())
3486 return true;
3487 if (Inst.isAlreadyInstantiating()) {
3488 // Error out if we hit an instantiation cycle for this initializer.
3489 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3490 << Instantiation;
3491 return true;
3492 }
3493 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3494 "instantiating default member init");
3495
3496 // Enter the scope of this instantiation. We don't use PushDeclContext because
3497 // we don't have a scope.
3498 ContextRAII SavedContext(*this, Instantiation->getParent());
3499 EnterExpressionEvaluationContext EvalContext(
3500 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3501 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3502 PointOfInstantiation, Instantiation, CurContext};
3503
3504 LocalInstantiationScope Scope(*this, true);
3505
3506 // Instantiate the initializer.
3507 ActOnStartCXXInClassMemberInitializer();
3508 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3509
3510 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3511 /*CXXDirectInit=*/false);
3512 Expr *Init = NewInit.get();
3513 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class")(static_cast <bool> ((!Init || !isa<ParenListExpr>
(Init)) && "call-style init in class") ? void (0) : __assert_fail
("(!Init || !isa<ParenListExpr>(Init)) && \"call-style init in class\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3513, __extension__
__PRETTY_FUNCTION__))
;
3514 ActOnFinishCXXInClassMemberInitializer(
3515 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3516
3517 if (auto *L = getASTMutationListener())
3518 L->DefaultMemberInitializerInstantiated(Instantiation);
3519
3520 // Return true if the in-class initializer is still missing.
3521 return !Instantiation->getInClassInitializer();
3522}
3523
3524namespace {
3525 /// A partial specialization whose template arguments have matched
3526 /// a given template-id.
3527 struct PartialSpecMatchResult {
3528 ClassTemplatePartialSpecializationDecl *Partial;
3529 TemplateArgumentList *Args;
3530 };
3531}
3532
3533bool Sema::usesPartialOrExplicitSpecialization(
3534 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3535 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3536 TSK_ExplicitSpecialization)
3537 return true;
3538
3539 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3540 ClassTemplateSpec->getSpecializedTemplate()
3541 ->getPartialSpecializations(PartialSpecs);
3542 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3543 TemplateDeductionInfo Info(Loc);
3544 if (!DeduceTemplateArguments(PartialSpecs[I],
3545 ClassTemplateSpec->getTemplateArgs(), Info))
3546 return true;
3547 }
3548
3549 return false;
3550}
3551
3552/// Get the instantiation pattern to use to instantiate the definition of a
3553/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3554/// template or of a partial specialization).
3555static ActionResult<CXXRecordDecl *>
3556getPatternForClassTemplateSpecialization(
3557 Sema &S, SourceLocation PointOfInstantiation,
3558 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3559 TemplateSpecializationKind TSK) {
3560 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3561 if (Inst.isInvalid())
3562 return {/*Invalid=*/true};
3563 if (Inst.isAlreadyInstantiating())
3564 return {/*Invalid=*/false};
3565
3566 llvm::PointerUnion<ClassTemplateDecl *,
3567 ClassTemplatePartialSpecializationDecl *>
3568 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3569 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
3570 // Find best matching specialization.
3571 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3572
3573 // C++ [temp.class.spec.match]p1:
3574 // When a class template is used in a context that requires an
3575 // instantiation of the class, it is necessary to determine
3576 // whether the instantiation is to be generated using the primary
3577 // template or one of the partial specializations. This is done by
3578 // matching the template arguments of the class template
3579 // specialization with the template argument lists of the partial
3580 // specializations.
3581 typedef PartialSpecMatchResult MatchResult;
3582 SmallVector<MatchResult, 4> Matched;
3583 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3584 Template->getPartialSpecializations(PartialSpecs);
3585 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3586 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3587 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3588 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3589 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
3590 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
3591 // Store the failed-deduction information for use in diagnostics, later.
3592 // TODO: Actually use the failed-deduction info?
3593 FailedCandidates.addCandidate().set(
3594 DeclAccessPair::make(Template, AS_public), Partial,
3595 MakeDeductionFailureInfo(S.Context, Result, Info));
3596 (void)Result;
3597 } else {
3598 Matched.push_back(PartialSpecMatchResult());
3599 Matched.back().Partial = Partial;
3600 Matched.back().Args = Info.takeCanonical();
3601 }
3602 }
3603
3604 // If we're dealing with a member template where the template parameters
3605 // have been instantiated, this provides the original template parameters
3606 // from which the member template's parameters were instantiated.
3607
3608 if (Matched.size() >= 1) {
3609 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3610 if (Matched.size() == 1) {
3611 // -- If exactly one matching specialization is found, the
3612 // instantiation is generated from that specialization.
3613 // We don't need to do anything for this.
3614 } else {
3615 // -- If more than one matching specialization is found, the
3616 // partial order rules (14.5.4.2) are used to determine
3617 // whether one of the specializations is more specialized
3618 // than the others. If none of the specializations is more
3619 // specialized than all of the other matching
3620 // specializations, then the use of the class template is
3621 // ambiguous and the program is ill-formed.
3622 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
3623 PEnd = Matched.end();
3624 P != PEnd; ++P) {
3625 if (S.getMoreSpecializedPartialSpecialization(
3626 P->Partial, Best->Partial, PointOfInstantiation) ==
3627 P->Partial)
3628 Best = P;
3629 }
3630
3631 // Determine if the best partial specialization is more specialized than
3632 // the others.
3633 bool Ambiguous = false;
3634 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3635 PEnd = Matched.end();
3636 P != PEnd; ++P) {
3637 if (P != Best && S.getMoreSpecializedPartialSpecialization(
3638 P->Partial, Best->Partial,
3639 PointOfInstantiation) != Best->Partial) {
3640 Ambiguous = true;
3641 break;
3642 }
3643 }
3644
3645 if (Ambiguous) {
3646 // Partial ordering did not produce a clear winner. Complain.
3647 Inst.Clear();
3648 ClassTemplateSpec->setInvalidDecl();
3649 S.Diag(PointOfInstantiation,
3650 diag::err_partial_spec_ordering_ambiguous)
3651 << ClassTemplateSpec;
3652
3653 // Print the matching partial specializations.
3654 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3655 PEnd = Matched.end();
3656 P != PEnd; ++P)
3657 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
3658 << S.getTemplateArgumentBindingsText(
3659 P->Partial->getTemplateParameters(), *P->Args);
3660
3661 return {/*Invalid=*/true};
3662 }
3663 }
3664
3665 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
3666 } else {
3667 // -- If no matches are found, the instantiation is generated
3668 // from the primary template.
3669 }
3670 }
3671
3672 CXXRecordDecl *Pattern = nullptr;
3673 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3674 if (auto *PartialSpec =
3675 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
3676 // Instantiate using the best class template partial specialization.
3677 while (PartialSpec->getInstantiatedFromMember()) {
3678 // If we've found an explicit specialization of this class template,
3679 // stop here and use that as the pattern.
3680 if (PartialSpec->isMemberSpecialization())
3681 break;
3682
3683 PartialSpec = PartialSpec->getInstantiatedFromMember();
3684 }
3685 Pattern = PartialSpec;
3686 } else {
3687 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3688 while (Template->getInstantiatedFromMemberTemplate()) {
3689 // If we've found an explicit specialization of this class template,
3690 // stop here and use that as the pattern.
3691 if (Template->isMemberSpecialization())
3692 break;
3693
3694 Template = Template->getInstantiatedFromMemberTemplate();
3695 }
3696 Pattern = Template->getTemplatedDecl();
3697 }
3698
3699 return Pattern;
3700}
3701
3702bool Sema::InstantiateClassTemplateSpecialization(
3703 SourceLocation PointOfInstantiation,
3704 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3705 TemplateSpecializationKind TSK, bool Complain) {
3706 // Perform the actual instantiation on the canonical declaration.
3707 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
3708 ClassTemplateSpec->getCanonicalDecl());
3709 if (ClassTemplateSpec->isInvalidDecl())
3710 return true;
3711
3712 ActionResult<CXXRecordDecl *> Pattern =
3713 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
3714 ClassTemplateSpec, TSK);
3715 if (!Pattern.isUsable())
3716 return Pattern.isInvalid();
3717
3718 return InstantiateClass(
3719 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
3720 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
3721}
3722
3723/// Instantiates the definitions of all of the member
3724/// of the given class, which is an instantiation of a class template
3725/// or a member class of a template.
3726void
3727Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
3728 CXXRecordDecl *Instantiation,
3729 const MultiLevelTemplateArgumentList &TemplateArgs,
3730 TemplateSpecializationKind TSK) {
3731 // FIXME: We need to notify the ASTMutationListener that we did all of these
3732 // things, in case we have an explicit instantiation definition in a PCM, a
3733 // module, or preamble, and the declaration is in an imported AST.
3734 assert((static_cast <bool> ((TSK == TSK_ExplicitInstantiationDefinition
|| TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation
&& Instantiation->isLocalClass())) && "Unexpected template specialization kind!"
) ? void (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3738, __extension__
__PRETTY_FUNCTION__))
3735 (TSK == TSK_ExplicitInstantiationDefinition ||(static_cast <bool> ((TSK == TSK_ExplicitInstantiationDefinition
|| TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation
&& Instantiation->isLocalClass())) && "Unexpected template specialization kind!"
) ? void (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3738, __extension__
__PRETTY_FUNCTION__))
3736 TSK == TSK_ExplicitInstantiationDeclaration ||(static_cast <bool> ((TSK == TSK_ExplicitInstantiationDefinition
|| TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation
&& Instantiation->isLocalClass())) && "Unexpected template specialization kind!"
) ? void (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3738, __extension__
__PRETTY_FUNCTION__))
3737 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&(static_cast <bool> ((TSK == TSK_ExplicitInstantiationDefinition
|| TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation
&& Instantiation->isLocalClass())) && "Unexpected template specialization kind!"
) ? void (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3738, __extension__
__PRETTY_FUNCTION__))
3738 "Unexpected template specialization kind!")(static_cast <bool> ((TSK == TSK_ExplicitInstantiationDefinition
|| TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation
&& Instantiation->isLocalClass())) && "Unexpected template specialization kind!"
) ? void (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3738, __extension__
__PRETTY_FUNCTION__))
;
3739 for (auto *D : Instantiation->decls()) {
3740 bool SuppressNew = false;
3741 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
3742 if (FunctionDecl *Pattern =
3743 Function->getInstantiatedFromMemberFunction()) {
3744
3745 if (Function->isIneligibleOrNotSelected())
3746 continue;
3747
3748 if (Function->getTrailingRequiresClause()) {
3749 ConstraintSatisfaction Satisfaction;
3750 if (CheckFunctionConstraints(Function, Satisfaction) ||
3751 !Satisfaction.IsSatisfied) {
3752 continue;
3753 }
3754 }
3755
3756 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3757 continue;
3758
3759 MemberSpecializationInfo *MSInfo =
3760 Function->getMemberSpecializationInfo();
3761 assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?"
) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3761, __extension__
__PRETTY_FUNCTION__))
;
3762 if (MSInfo->getTemplateSpecializationKind()
3763 == TSK_ExplicitSpecialization)
3764 continue;
3765
3766 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3767 Function,
3768 MSInfo->getTemplateSpecializationKind(),
3769 MSInfo->getPointOfInstantiation(),
3770 SuppressNew) ||
3771 SuppressNew)
3772 continue;
3773
3774 // C++11 [temp.explicit]p8:
3775 // An explicit instantiation definition that names a class template
3776 // specialization explicitly instantiates the class template
3777 // specialization and is only an explicit instantiation definition
3778 // of members whose definition is visible at the point of
3779 // instantiation.
3780 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
3781 continue;
3782
3783 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3784
3785 if (Function->isDefined()) {
3786 // Let the ASTConsumer know that this function has been explicitly
3787 // instantiated now, and its linkage might have changed.
3788 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
3789 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
3790 InstantiateFunctionDefinition(PointOfInstantiation, Function);
3791 } else if (TSK == TSK_ImplicitInstantiation) {
3792 PendingLocalImplicitInstantiations.push_back(
3793 std::make_pair(Function, PointOfInstantiation));
3794 }
3795 }
3796 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
3797 if (isa<VarTemplateSpecializationDecl>(Var))
3798 continue;
3799
3800 if (Var->isStaticDataMember()) {
3801 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3802 continue;
3803
3804 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
3805 assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?"
) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3805, __extension__
__PRETTY_FUNCTION__))
;
3806 if (MSInfo->getTemplateSpecializationKind()
3807 == TSK_ExplicitSpecialization)
3808 continue;
3809
3810 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3811 Var,
3812 MSInfo->getTemplateSpecializationKind(),
3813 MSInfo->getPointOfInstantiation(),
3814 SuppressNew) ||
3815 SuppressNew)
3816 continue;
3817
3818 if (TSK == TSK_ExplicitInstantiationDefinition) {
3819 // C++0x [temp.explicit]p8:
3820 // An explicit instantiation definition that names a class template
3821 // specialization explicitly instantiates the class template
3822 // specialization and is only an explicit instantiation definition
3823 // of members whose definition is visible at the point of
3824 // instantiation.
3825 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
3826 continue;
3827
3828 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3829 InstantiateVariableDefinition(PointOfInstantiation, Var);
3830 } else {
3831 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3832 }
3833 }
3834 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
3835 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3836 continue;
3837
3838 // Always skip the injected-class-name, along with any
3839 // redeclarations of nested classes, since both would cause us
3840 // to try to instantiate the members of a class twice.
3841 // Skip closure types; they'll get instantiated when we instantiate
3842 // the corresponding lambda-expression.
3843 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
3844 Record->isLambda())
3845 continue;
3846
3847 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
3848 assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?"
) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3848, __extension__
__PRETTY_FUNCTION__))
;
3849
3850 if (MSInfo->getTemplateSpecializationKind()
3851 == TSK_ExplicitSpecialization)
3852 continue;
3853
3854 if (Context.getTargetInfo().getTriple().isOSWindows() &&
3855 TSK == TSK_ExplicitInstantiationDeclaration) {
3856 // On Windows, explicit instantiation decl of the outer class doesn't
3857 // affect the inner class. Typically extern template declarations are
3858 // used in combination with dll import/export annotations, but those
3859 // are not propagated from the outer class templates to inner classes.
3860 // Therefore, do not instantiate inner classes on this platform, so
3861 // that users don't end up with undefined symbols during linking.
3862 continue;
3863 }
3864
3865 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3866 Record,
3867 MSInfo->getTemplateSpecializationKind(),
3868 MSInfo->getPointOfInstantiation(),
3869 SuppressNew) ||
3870 SuppressNew)
3871 continue;
3872
3873 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3874 assert(Pattern && "Missing instantiated-from-template information")(static_cast <bool> (Pattern && "Missing instantiated-from-template information"
) ? void (0) : __assert_fail ("Pattern && \"Missing instantiated-from-template information\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3874, __extension__
__PRETTY_FUNCTION__))
;
3875
3876 if (!Record->getDefinition()) {
3877 if (!Pattern->getDefinition()) {
3878 // C++0x [temp.explicit]p8:
3879 // An explicit instantiation definition that names a class template
3880 // specialization explicitly instantiates the class template
3881 // specialization and is only an explicit instantiation definition
3882 // of members whose definition is visible at the point of
3883 // instantiation.
3884 if (TSK == TSK_ExplicitInstantiationDeclaration) {
3885 MSInfo->setTemplateSpecializationKind(TSK);
3886 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3887 }
3888
3889 continue;
3890 }
3891
3892 InstantiateClass(PointOfInstantiation, Record, Pattern,
3893 TemplateArgs,
3894 TSK);
3895 } else {
3896 if (TSK == TSK_ExplicitInstantiationDefinition &&
3897 Record->getTemplateSpecializationKind() ==
3898 TSK_ExplicitInstantiationDeclaration) {
3899 Record->setTemplateSpecializationKind(TSK);
3900 MarkVTableUsed(PointOfInstantiation, Record, true);
3901 }
3902 }
3903
3904 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
3905 if (Pattern)
3906 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
3907 TSK);
3908 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
3909 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
3910 assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?"
) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3910, __extension__
__PRETTY_FUNCTION__))
;
3911
3912 if (MSInfo->getTemplateSpecializationKind()
3913 == TSK_ExplicitSpecialization)
3914 continue;
3915
3916 if (CheckSpecializationInstantiationRedecl(
3917 PointOfInstantiation, TSK, Enum,
3918 MSInfo->getTemplateSpecializationKind(),
3919 MSInfo->getPointOfInstantiation(), SuppressNew) ||
3920 SuppressNew)
3921 continue;
3922
3923 if (Enum->getDefinition())
3924 continue;
3925
3926 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
3927 assert(Pattern && "Missing instantiated-from-template information")(static_cast <bool> (Pattern && "Missing instantiated-from-template information"
) ? void (0) : __assert_fail ("Pattern && \"Missing instantiated-from-template information\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3927, __extension__
__PRETTY_FUNCTION__))
;
3928
3929 if (TSK == TSK_ExplicitInstantiationDefinition) {
3930 if (!Pattern->getDefinition())
3931 continue;
3932
3933 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
3934 } else {
3935 MSInfo->setTemplateSpecializationKind(TSK);
3936 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3937 }
3938 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3939 // No need to instantiate in-class initializers during explicit
3940 // instantiation.
3941 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
3942 CXXRecordDecl *ClassPattern =
3943 Instantiation->getTemplateInstantiationPattern();
3944 DeclContext::lookup_result Lookup =
3945 ClassPattern->lookup(Field->getDeclName());
3946 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
3947 assert(Pattern)(static_cast <bool> (Pattern) ? void (0) : __assert_fail
("Pattern", "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3947
, __extension__ __PRETTY_FUNCTION__))
;
3948 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
3949 TemplateArgs);
3950 }
3951 }
3952 }
3953}
3954
3955/// Instantiate the definitions of all of the members of the
3956/// given class template specialization, which was named as part of an
3957/// explicit instantiation.
3958void
3959Sema::InstantiateClassTemplateSpecializationMembers(
3960 SourceLocation PointOfInstantiation,
3961 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3962 TemplateSpecializationKind TSK) {
3963 // C++0x [temp.explicit]p7:
3964 // An explicit instantiation that names a class template
3965 // specialization is an explicit instantion of the same kind
3966 // (declaration or definition) of each of its members (not
3967 // including members inherited from base classes) that has not
3968 // been previously explicitly specialized in the translation unit
3969 // containing the explicit instantiation, except as described
3970 // below.
3971 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
3972 getTemplateInstantiationArgs(ClassTemplateSpec),
3973 TSK);
3974}
3975
3976StmtResult
3977Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
3978 if (!S)
3979 return S;
3980
3981 TemplateInstantiator Instantiator(*this, TemplateArgs,
3982 SourceLocation(),
3983 DeclarationName());
3984 return Instantiator.TransformStmt(S);
3985}
3986
3987bool Sema::SubstTemplateArguments(
3988 ArrayRef<TemplateArgumentLoc> Args,
3989 const MultiLevelTemplateArgumentList &TemplateArgs,
3990 TemplateArgumentListInfo &Out) {
3991 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
3992 DeclarationName());
3993 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
3994}
3995
3996ExprResult
3997Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
3998 if (!E)
3999 return E;
4000
4001 TemplateInstantiator Instantiator(*this, TemplateArgs,
4002 SourceLocation(),
4003 DeclarationName());
4004 return Instantiator.TransformExpr(E);
4005}
4006
4007ExprResult
4008Sema::SubstConstraintExpr(Expr *E,
4009 const MultiLevelTemplateArgumentList &TemplateArgs) {
4010 if (!E)
4011 return E;
4012
4013 // This is where we need to make sure we 'know' constraint checking needs to
4014 // happen.
4015 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4016 DeclarationName());
4017 return Instantiator.TransformExpr(E);
4018}
4019
4020ExprResult Sema::SubstInitializer(Expr *Init,
4021 const MultiLevelTemplateArgumentList &TemplateArgs,
4022 bool CXXDirectInit) {
4023 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4024 DeclarationName());
4025 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4026}
4027
4028bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4029 const MultiLevelTemplateArgumentList &TemplateArgs,
4030 SmallVectorImpl<Expr *> &Outputs) {
4031 if (Exprs.empty())
4032 return false;
4033
4034 TemplateInstantiator Instantiator(*this, TemplateArgs,
4035 SourceLocation(),
4036 DeclarationName());
4037 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4038 IsCall, Outputs);
4039}
4040
4041NestedNameSpecifierLoc
4042Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
4043 const MultiLevelTemplateArgumentList &TemplateArgs) {
4044 if (!NNS)
4045 return NestedNameSpecifierLoc();
4046
4047 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4048 DeclarationName());
4049 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4050}
4051
4052/// Do template substitution on declaration name info.
4053DeclarationNameInfo
4054Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
4055 const MultiLevelTemplateArgumentList &TemplateArgs) {
4056 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4057 NameInfo.getName());
4058 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4059}
4060
4061TemplateName
4062Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
4063 TemplateName Name, SourceLocation Loc,
4064 const MultiLevelTemplateArgumentList &TemplateArgs) {
4065 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
4066 DeclarationName());
4067 CXXScopeSpec SS;
4068 SS.Adopt(QualifierLoc);
4069 return Instantiator.TransformTemplateName(SS, Name, Loc);
4070}
4071
4072static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4073 // When storing ParmVarDecls in the local instantiation scope, we always
4074 // want to use the ParmVarDecl from the canonical function declaration,
4075 // since the map is then valid for any redeclaration or definition of that
4076 // function.
4077 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4078 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4079 unsigned i = PV->getFunctionScopeIndex();
4080 // This parameter might be from a freestanding function type within the
4081 // function and isn't necessarily referring to one of FD's parameters.
4082 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4083 return FD->getCanonicalDecl()->getParamDecl(i);
4084 }
4085 }
4086 return D;
4087}
4088
4089
4090llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4091LocalInstantiationScope::findInstantiationOf(const Decl *D) {
4092 D = getCanonicalParmVarDecl(D);
4093 for (LocalInstantiationScope *Current = this; Current;
4094 Current = Current->Outer) {
4095
4096 // Check if we found something within this scope.
4097 const Decl *CheckD = D;
4098 do {
4099 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4100 if (Found != Current->LocalDecls.end())
4101 return &Found->second;
4102
4103 // If this is a tag declaration, it's possible that we need to look for
4104 // a previous declaration.
4105 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4106 CheckD = Tag->getPreviousDecl();
4107 else
4108 CheckD = nullptr;
4109 } while (CheckD);
4110
4111 // If we aren't combined with our outer scope, we're done.
4112 if (!Current->CombineWithOuterScope)
4113 break;
4114 }
4115
4116 // If we're performing a partial substitution during template argument
4117 // deduction, we may not have values for template parameters yet.
4118 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4119 isa<TemplateTemplateParmDecl>(D))
4120 return nullptr;
4121
4122 // Local types referenced prior to definition may require instantiation.
4123 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4124 if (RD->isLocalClass())
4125 return nullptr;
4126
4127 // Enumeration types referenced prior to definition may appear as a result of
4128 // error recovery.
4129 if (isa<EnumDecl>(D))
4130 return nullptr;
4131
4132 // Materialized typedefs/type alias for implicit deduction guides may require
4133 // instantiation.
4134 if (isa<TypedefNameDecl>(D) &&
4135 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
4136 return nullptr;
4137
4138 // If we didn't find the decl, then we either have a sema bug, or we have a
4139 // forward reference to a label declaration. Return null to indicate that
4140 // we have an uninstantiated label.
4141 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope")(static_cast <bool> (isa<LabelDecl>(D) &&
"declaration not instantiated in this scope") ? void (0) : __assert_fail
("isa<LabelDecl>(D) && \"declaration not instantiated in this scope\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4141, __extension__
__PRETTY_FUNCTION__))
;
4142 return nullptr;
4143}
4144
4145void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
4146 D = getCanonicalParmVarDecl(D);
4147 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4148 if (Stored.isNull()) {
4149#ifndef NDEBUG
4150 // It should not be present in any surrounding scope either.
4151 LocalInstantiationScope *Current = this;
4152 while (Current->CombineWithOuterScope && Current->Outer) {
4153 Current = Current->Outer;
4154 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&(static_cast <bool> (Current->LocalDecls.find(D) == Current
->LocalDecls.end() && "Instantiated local in inner and outer scopes"
) ? void (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Instantiated local in inner and outer scopes\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4155, __extension__
__PRETTY_FUNCTION__))
4155 "Instantiated local in inner and outer scopes")(static_cast <bool> (Current->LocalDecls.find(D) == Current
->LocalDecls.end() && "Instantiated local in inner and outer scopes"
) ? void (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Instantiated local in inner and outer scopes\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4155, __extension__
__PRETTY_FUNCTION__))
;
4156 }
4157#endif
4158 Stored = Inst;
4159 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
4160 Pack->push_back(cast<VarDecl>(Inst));
4161 } else {
4162 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local")(static_cast <bool> (Stored.get<Decl *>() == Inst
&& "Already instantiated this local") ? void (0) : __assert_fail
("Stored.get<Decl *>() == Inst && \"Already instantiated this local\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4162, __extension__
__PRETTY_FUNCTION__))
;
4163 }
4164}
4165
4166void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
4167 VarDecl *Inst) {
4168 D = getCanonicalParmVarDecl(D);
4169 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
4170 Pack->push_back(Inst);
4171}
4172
4173void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
4174#ifndef NDEBUG
4175 // This should be the first time we've been told about this decl.
4176 for (LocalInstantiationScope *Current = this;
4177 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4178 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&(static_cast <bool> (Current->LocalDecls.find(D) == Current
->LocalDecls.end() && "Creating local pack after instantiation of local"
) ? void (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Creating local pack after instantiation of local\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4179, __extension__
__PRETTY_FUNCTION__))
4179 "Creating local pack after instantiation of local")(static_cast <bool> (Current->LocalDecls.find(D) == Current
->LocalDecls.end() && "Creating local pack after instantiation of local"
) ? void (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Creating local pack after instantiation of local\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4179, __extension__
__PRETTY_FUNCTION__))
;
4180#endif
4181
4182 D = getCanonicalParmVarDecl(D);
4183 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4184 DeclArgumentPack *Pack = new DeclArgumentPack;
4185 Stored = Pack;
4186 ArgumentPacks.push_back(Pack);
4187}
4188
4189bool LocalInstantiationScope::isLocalPackExpansion(const Decl *D) {
4190 for (DeclArgumentPack *Pack : ArgumentPacks)
4191 if (llvm::is_contained(*Pack, D))
4192 return true;
4193 return false;
4194}
4195
4196void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
4197 const TemplateArgument *ExplicitArgs,
4198 unsigned NumExplicitArgs) {
4199 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&(static_cast <bool> ((!PartiallySubstitutedPack || PartiallySubstitutedPack
== Pack) && "Already have a partially-substituted pack"
) ? void (0) : __assert_fail ("(!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && \"Already have a partially-substituted pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4200, __extension__
__PRETTY_FUNCTION__))
4200 "Already have a partially-substituted pack")(static_cast <bool> ((!PartiallySubstitutedPack || PartiallySubstitutedPack
== Pack) && "Already have a partially-substituted pack"
) ? void (0) : __assert_fail ("(!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && \"Already have a partially-substituted pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4200, __extension__
__PRETTY_FUNCTION__))
;
4201 assert((!PartiallySubstitutedPack(static_cast <bool> ((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? void (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4203, __extension__
__PRETTY_FUNCTION__))
4202 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&(static_cast <bool> ((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? void (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4203, __extension__
__PRETTY_FUNCTION__))
4203 "Wrong number of arguments in partially-substituted pack")(static_cast <bool> ((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? void (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4203, __extension__
__PRETTY_FUNCTION__))
;
4204 PartiallySubstitutedPack = Pack;
4205 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4206 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4207}
4208
4209NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
4210 const TemplateArgument **ExplicitArgs,
4211 unsigned *NumExplicitArgs) const {
4212 if (ExplicitArgs)
4213 *ExplicitArgs = nullptr;
4214 if (NumExplicitArgs)
4215 *NumExplicitArgs = 0;
4216
4217 for (const LocalInstantiationScope *Current = this; Current;
4218 Current = Current->Outer) {
4219 if (Current->PartiallySubstitutedPack) {
4220 if (ExplicitArgs)
4221 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4222 if (NumExplicitArgs)
4223 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4224
4225 return Current->PartiallySubstitutedPack;
4226 }
4227
4228 if (!Current->CombineWithOuterScope)
4229 break;
4230 }
4231
4232 return nullptr;
4233}

/build/source/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/ExprConcepts.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExprOpenMP.h"
26#include "clang/AST/OpenMPClause.h"
27#include "clang/AST/Stmt.h"
28#include "clang/AST/StmtCXX.h"
29#include "clang/AST/StmtObjC.h"
30#include "clang/AST/StmtOpenMP.h"
31#include "clang/Basic/DiagnosticParse.h"
32#include "clang/Basic/OpenMPKinds.h"
33#include "clang/Sema/Designator.h"
34#include "clang/Sema/EnterExpressionEvaluationContext.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/Ownership.h"
37#include "clang/Sema/ParsedTemplate.h"
38#include "clang/Sema/ScopeInfo.h"
39#include "clang/Sema/SemaDiagnostic.h"
40#include "clang/Sema/SemaInternal.h"
41#include "llvm/ADT/ArrayRef.h"
42#include "llvm/Support/ErrorHandling.h"
43#include <algorithm>
44#include <optional>
45
46using namespace llvm::omp;
47
48namespace clang {
49using namespace sema;
50
51/// A semantic tree transformation that allows one to transform one
52/// abstract syntax tree into another.
53///
54/// A new tree transformation is defined by creating a new subclass \c X of
55/// \c TreeTransform<X> and then overriding certain operations to provide
56/// behavior specific to that transformation. For example, template
57/// instantiation is implemented as a tree transformation where the
58/// transformation of TemplateTypeParmType nodes involves substituting the
59/// template arguments for their corresponding template parameters; a similar
60/// transformation is performed for non-type template parameters and
61/// template template parameters.
62///
63/// This tree-transformation template uses static polymorphism to allow
64/// subclasses to customize any of its operations. Thus, a subclass can
65/// override any of the transformation or rebuild operators by providing an
66/// operation with the same signature as the default implementation. The
67/// overriding function should not be virtual.
68///
69/// Semantic tree transformations are split into two stages, either of which
70/// can be replaced by a subclass. The "transform" step transforms an AST node
71/// or the parts of an AST node using the various transformation functions,
72/// then passes the pieces on to the "rebuild" step, which constructs a new AST
73/// node of the appropriate kind from the pieces. The default transformation
74/// routines recursively transform the operands to composite AST nodes (e.g.,
75/// the pointee type of a PointerType node) and, if any of those operand nodes
76/// were changed by the transformation, invokes the rebuild operation to create
77/// a new AST node.
78///
79/// Subclasses can customize the transformation at various levels. The
80/// most coarse-grained transformations involve replacing TransformType(),
81/// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
82/// TransformTemplateName(), or TransformTemplateArgument() with entirely
83/// new implementations.
84///
85/// For more fine-grained transformations, subclasses can replace any of the
86/// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
87/// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
88/// replacing TransformTemplateTypeParmType() allows template instantiation
89/// to substitute template arguments for their corresponding template
90/// parameters. Additionally, subclasses can override the \c RebuildXXX
91/// functions to control how AST nodes are rebuilt when their operands change.
92/// By default, \c TreeTransform will invoke semantic analysis to rebuild
93/// AST nodes. However, certain other tree transformations (e.g, cloning) may
94/// be able to use more efficient rebuild steps.
95///
96/// There are a handful of other functions that can be overridden, allowing one
97/// to avoid traversing nodes that don't need any transformation
98/// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
99/// operands have not changed (\c AlwaysRebuild()), and customize the
100/// default locations and entity names used for type-checking
101/// (\c getBaseLocation(), \c getBaseEntity()).
102template<typename Derived>
103class TreeTransform {
104 /// Private RAII object that helps us forget and then re-remember
105 /// the template argument corresponding to a partially-substituted parameter
106 /// pack.
107 class ForgetPartiallySubstitutedPackRAII {
108 Derived &Self;
109 TemplateArgument Old;
110
111 public:
112 ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
113 Old = Self.ForgetPartiallySubstitutedPack();
114 }
115
116 ~ForgetPartiallySubstitutedPackRAII() {
117 Self.RememberPartiallySubstitutedPack(Old);
118 }
119 };
120
121protected:
122 Sema &SemaRef;
123
124 /// The set of local declarations that have been transformed, for
125 /// cases where we are forced to build new declarations within the transformer
126 /// rather than in the subclass (e.g., lambda closure types).
127 llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
128
129public:
130 /// Initializes a new tree transformer.
131 TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
132
133 /// Retrieves a reference to the derived class.
134 Derived &getDerived() { return static_cast<Derived&>(*this); }
135
136 /// Retrieves a reference to the derived class.
137 const Derived &getDerived() const {
138 return static_cast<const Derived&>(*this);
139 }
140
141 static inline ExprResult Owned(Expr *E) { return E; }
142 static inline StmtResult Owned(Stmt *S) { return S; }
143
144 /// Retrieves a reference to the semantic analysis object used for
145 /// this tree transform.
146 Sema &getSema() const { return SemaRef; }
147
148 /// Whether the transformation should always rebuild AST nodes, even
149 /// if none of the children have changed.
150 ///
151 /// Subclasses may override this function to specify when the transformation
152 /// should rebuild all AST nodes.
153 ///
154 /// We must always rebuild all AST nodes when performing variadic template
155 /// pack expansion, in order to avoid violating the AST invariant that each
156 /// statement node appears at most once in its containing declaration.
157 bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
158
159 /// Whether the transformation is forming an expression or statement that
160 /// replaces the original. In this case, we'll reuse mangling numbers from
161 /// existing lambdas.
162 bool ReplacingOriginal() { return false; }
163
164 /// Wether CXXConstructExpr can be skipped when they are implicit.
165 /// They will be reconstructed when used if needed.
166 /// This is useful when the user that cause rebuilding of the
167 /// CXXConstructExpr is outside of the expression at which the TreeTransform
168 /// started.
169 bool AllowSkippingCXXConstructExpr() { return true; }
170
171 /// Returns the location of the entity being transformed, if that
172 /// information was not available elsewhere in the AST.
173 ///
174 /// By default, returns no source-location information. Subclasses can
175 /// provide an alternative implementation that provides better location
176 /// information.
177 SourceLocation getBaseLocation() { return SourceLocation(); }
178
179 /// Returns the name of the entity being transformed, if that
180 /// information was not available elsewhere in the AST.
181 ///
182 /// By default, returns an empty name. Subclasses can provide an alternative
183 /// implementation with a more precise name.
184 DeclarationName getBaseEntity() { return DeclarationName(); }
185
186 /// Sets the "base" location and entity when that
187 /// information is known based on another transformation.
188 ///
189 /// By default, the source location and entity are ignored. Subclasses can
190 /// override this function to provide a customized implementation.
191 void setBase(SourceLocation Loc, DeclarationName Entity) { }
192
193 /// RAII object that temporarily sets the base location and entity
194 /// used for reporting diagnostics in types.
195 class TemporaryBase {
196 TreeTransform &Self;
197 SourceLocation OldLocation;
198 DeclarationName OldEntity;
199
200 public:
201 TemporaryBase(TreeTransform &Self, SourceLocation Location,
202 DeclarationName Entity) : Self(Self) {
203 OldLocation = Self.getDerived().getBaseLocation();
204 OldEntity = Self.getDerived().getBaseEntity();
205
206 if (Location.isValid())
207 Self.getDerived().setBase(Location, Entity);
208 }
209
210 ~TemporaryBase() {
211 Self.getDerived().setBase(OldLocation, OldEntity);
212 }
213 };
214
215 /// Determine whether the given type \p T has already been
216 /// transformed.
217 ///
218 /// Subclasses can provide an alternative implementation of this routine
219 /// to short-circuit evaluation when it is known that a given type will
220 /// not change. For example, template instantiation need not traverse
221 /// non-dependent types.
222 bool AlreadyTransformed(QualType T) {
223 return T.isNull();
224 }
225
226 /// Transform a template parameter depth level.
227 ///
228 /// During a transformation that transforms template parameters, this maps
229 /// an old template parameter depth to a new depth.
230 unsigned TransformTemplateDepth(unsigned Depth) {
231 return Depth;
232 }
233
234 /// Determine whether the given call argument should be dropped, e.g.,
235 /// because it is a default argument.
236 ///
237 /// Subclasses can provide an alternative implementation of this routine to
238 /// determine which kinds of call arguments get dropped. By default,
239 /// CXXDefaultArgument nodes are dropped (prior to transformation).
240 bool DropCallArgument(Expr *E) {
241 return E->isDefaultArgument();
242 }
243
244 /// Determine whether we should expand a pack expansion with the
245 /// given set of parameter packs into separate arguments by repeatedly
246 /// transforming the pattern.
247 ///
248 /// By default, the transformer never tries to expand pack expansions.
249 /// Subclasses can override this routine to provide different behavior.
250 ///
251 /// \param EllipsisLoc The location of the ellipsis that identifies the
252 /// pack expansion.
253 ///
254 /// \param PatternRange The source range that covers the entire pattern of
255 /// the pack expansion.
256 ///
257 /// \param Unexpanded The set of unexpanded parameter packs within the
258 /// pattern.
259 ///
260 /// \param ShouldExpand Will be set to \c true if the transformer should
261 /// expand the corresponding pack expansions into separate arguments. When
262 /// set, \c NumExpansions must also be set.
263 ///
264 /// \param RetainExpansion Whether the caller should add an unexpanded
265 /// pack expansion after all of the expanded arguments. This is used
266 /// when extending explicitly-specified template argument packs per
267 /// C++0x [temp.arg.explicit]p9.
268 ///
269 /// \param NumExpansions The number of separate arguments that will be in
270 /// the expanded form of the corresponding pack expansion. This is both an
271 /// input and an output parameter, which can be set by the caller if the
272 /// number of expansions is known a priori (e.g., due to a prior substitution)
273 /// and will be set by the callee when the number of expansions is known.
274 /// The callee must set this value when \c ShouldExpand is \c true; it may
275 /// set this value in other cases.
276 ///
277 /// \returns true if an error occurred (e.g., because the parameter packs
278 /// are to be instantiated with arguments of different lengths), false
279 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
280 /// must be set.
281 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
282 SourceRange PatternRange,
283 ArrayRef<UnexpandedParameterPack> Unexpanded,
284 bool &ShouldExpand, bool &RetainExpansion,
285 std::optional<unsigned> &NumExpansions) {
286 ShouldExpand = false;
287 return false;
288 }
289
290 /// "Forget" about the partially-substituted pack template argument,
291 /// when performing an instantiation that must preserve the parameter pack
292 /// use.
293 ///
294 /// This routine is meant to be overridden by the template instantiator.
295 TemplateArgument ForgetPartiallySubstitutedPack() {
296 return TemplateArgument();
297 }
298
299 /// "Remember" the partially-substituted pack template argument
300 /// after performing an instantiation that must preserve the parameter pack
301 /// use.
302 ///
303 /// This routine is meant to be overridden by the template instantiator.
304 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
305
306 /// Note to the derived class when a function parameter pack is
307 /// being expanded.
308 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
309
310 /// Transforms the given type into another type.
311 ///
312 /// By default, this routine transforms a type by creating a
313 /// TypeSourceInfo for it and delegating to the appropriate
314 /// function. This is expensive, but we don't mind, because
315 /// this method is deprecated anyway; all users should be
316 /// switched to storing TypeSourceInfos.
317 ///
318 /// \returns the transformed type.
319 QualType TransformType(QualType T);
320
321 /// Transforms the given type-with-location into a new
322 /// type-with-location.
323 ///
324 /// By default, this routine transforms a type by delegating to the
325 /// appropriate TransformXXXType to build a new type. Subclasses
326 /// may override this function (to take over all type
327 /// transformations) or some set of the TransformXXXType functions
328 /// to alter the transformation.
329 TypeSourceInfo *TransformType(TypeSourceInfo *DI);
330
331 /// Transform the given type-with-location into a new
332 /// type, collecting location information in the given builder
333 /// as necessary.
334 ///
335 QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
336
337 /// Transform a type that is permitted to produce a
338 /// DeducedTemplateSpecializationType.
339 ///
340 /// This is used in the (relatively rare) contexts where it is acceptable
341 /// for transformation to produce a class template type with deduced
342 /// template arguments.
343 /// @{
344 QualType TransformTypeWithDeducedTST(QualType T);
345 TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
346 /// @}
347
348 /// The reason why the value of a statement is not discarded, if any.
349 enum StmtDiscardKind {
350 SDK_Discarded,
351 SDK_NotDiscarded,
352 SDK_StmtExprResult,
353 };
354
355 /// Transform the given statement.
356 ///
357 /// By default, this routine transforms a statement by delegating to the
358 /// appropriate TransformXXXStmt function to transform a specific kind of
359 /// statement or the TransformExpr() function to transform an expression.
360 /// Subclasses may override this function to transform statements using some
361 /// other mechanism.
362 ///
363 /// \returns the transformed statement.
364 StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
365
366 /// Transform the given statement.
367 ///
368 /// By default, this routine transforms a statement by delegating to the
369 /// appropriate TransformOMPXXXClause function to transform a specific kind
370 /// of clause. Subclasses may override this function to transform statements
371 /// using some other mechanism.
372 ///
373 /// \returns the transformed OpenMP clause.
374 OMPClause *TransformOMPClause(OMPClause *S);
375
376 /// Transform the given attribute.
377 ///
378 /// By default, this routine transforms a statement by delegating to the
379 /// appropriate TransformXXXAttr function to transform a specific kind
380 /// of attribute. Subclasses may override this function to transform
381 /// attributed statements/types using some other mechanism.
382 ///
383 /// \returns the transformed attribute
384 const Attr *TransformAttr(const Attr *S);
385
386 // Transform the given statement attribute.
387 //
388 // Delegates to the appropriate TransformXXXAttr function to transform a
389 // specific kind of statement attribute. Unlike the non-statement taking
390 // version of this, this implements all attributes, not just pragmas.
391 const Attr *TransformStmtAttr(const Stmt *OrigS, const Stmt *InstS,
392 const Attr *A);
393
394 // Transform the specified attribute.
395 //
396 // Subclasses should override the transformation of attributes with a pragma
397 // spelling to transform expressions stored within the attribute.
398 //
399 // \returns the transformed attribute.
400#define ATTR(X) \
401 const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
402#include "clang/Basic/AttrList.inc"
403
404 // Transform the specified attribute.
405 //
406 // Subclasses should override the transformation of attributes to do
407 // transformation and checking of statement attributes. By default, this
408 // delegates to the non-statement taking version.
409 //
410 // \returns the transformed attribute.
411#define ATTR(X) \
412 const X##Attr *TransformStmt##X##Attr(const Stmt *, const Stmt *, \
413 const X##Attr *A) { \
414 return getDerived().Transform##X##Attr(A); \
415 }
416#include "clang/Basic/AttrList.inc"
417
418 /// Transform the given expression.
419 ///
420 /// By default, this routine transforms an expression by delegating to the
421 /// appropriate TransformXXXExpr function to build a new expression.
422 /// Subclasses may override this function to transform expressions using some
423 /// other mechanism.
424 ///
425 /// \returns the transformed expression.
426 ExprResult TransformExpr(Expr *E);
427
428 /// Transform the given initializer.
429 ///
430 /// By default, this routine transforms an initializer by stripping off the
431 /// semantic nodes added by initialization, then passing the result to
432 /// TransformExpr or TransformExprs.
433 ///
434 /// \returns the transformed initializer.
435 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
436
437 /// Transform the given list of expressions.
438 ///
439 /// This routine transforms a list of expressions by invoking
440 /// \c TransformExpr() for each subexpression. However, it also provides
441 /// support for variadic templates by expanding any pack expansions (if the
442 /// derived class permits such expansion) along the way. When pack expansions
443 /// are present, the number of outputs may not equal the number of inputs.
444 ///
445 /// \param Inputs The set of expressions to be transformed.
446 ///
447 /// \param NumInputs The number of expressions in \c Inputs.
448 ///
449 /// \param IsCall If \c true, then this transform is being performed on
450 /// function-call arguments, and any arguments that should be dropped, will
451 /// be.
452 ///
453 /// \param Outputs The transformed input expressions will be added to this
454 /// vector.
455 ///
456 /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
457 /// due to transformation.
458 ///
459 /// \returns true if an error occurred, false otherwise.
460 bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
461 SmallVectorImpl<Expr *> &Outputs,
462 bool *ArgChanged = nullptr);
463
464 /// Transform the given declaration, which is referenced from a type
465 /// or expression.
466 ///
467 /// By default, acts as the identity function on declarations, unless the
468 /// transformer has had to transform the declaration itself. Subclasses
469 /// may override this function to provide alternate behavior.
470 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
471 llvm::DenseMap<Decl *, Decl *>::iterator Known
472 = TransformedLocalDecls.find(D);
473 if (Known != TransformedLocalDecls.end())
474 return Known->second;
475
476 return D;
477 }
478
479 /// Transform the specified condition.
480 ///
481 /// By default, this transforms the variable and expression and rebuilds
482 /// the condition.
483 Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
484 Expr *Expr,
485 Sema::ConditionKind Kind);
486
487 /// Transform the attributes associated with the given declaration and
488 /// place them on the new declaration.
489 ///
490 /// By default, this operation does nothing. Subclasses may override this
491 /// behavior to transform attributes.
492 void transformAttrs(Decl *Old, Decl *New) { }
493
494 /// Note that a local declaration has been transformed by this
495 /// transformer.
496 ///
497 /// Local declarations are typically transformed via a call to
498 /// TransformDefinition. However, in some cases (e.g., lambda expressions),
499 /// the transformer itself has to transform the declarations. This routine
500 /// can be overridden by a subclass that keeps track of such mappings.
501 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
502 assert(New.size() == 1 &&(static_cast <bool> (New.size() == 1 && "must override transformedLocalDecl if performing pack expansion"
) ? void (0) : __assert_fail ("New.size() == 1 && \"must override transformedLocalDecl if performing pack expansion\""
, "clang/lib/Sema/TreeTransform.h", 503, __extension__ __PRETTY_FUNCTION__
))
503 "must override transformedLocalDecl if performing pack expansion")(static_cast <bool> (New.size() == 1 && "must override transformedLocalDecl if performing pack expansion"
) ? void (0) : __assert_fail ("New.size() == 1 && \"must override transformedLocalDecl if performing pack expansion\""
, "clang/lib/Sema/TreeTransform.h", 503, __extension__ __PRETTY_FUNCTION__
))
;
504 TransformedLocalDecls[Old] = New.front();
505 }
506
507 /// Transform the definition of the given declaration.
508 ///
509 /// By default, invokes TransformDecl() to transform the declaration.
510 /// Subclasses may override this function to provide alternate behavior.
511 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
512 return getDerived().TransformDecl(Loc, D);
513 }
514
515 /// Transform the given declaration, which was the first part of a
516 /// nested-name-specifier in a member access expression.
517 ///
518 /// This specific declaration transformation only applies to the first
519 /// identifier in a nested-name-specifier of a member access expression, e.g.,
520 /// the \c T in \c x->T::member
521 ///
522 /// By default, invokes TransformDecl() to transform the declaration.
523 /// Subclasses may override this function to provide alternate behavior.
524 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
525 return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
526 }
527
528 /// Transform the set of declarations in an OverloadExpr.
529 bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
530 LookupResult &R);
531
532 /// Transform the given nested-name-specifier with source-location
533 /// information.
534 ///
535 /// By default, transforms all of the types and declarations within the
536 /// nested-name-specifier. Subclasses may override this function to provide
537 /// alternate behavior.
538 NestedNameSpecifierLoc
539 TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
540 QualType ObjectType = QualType(),
541 NamedDecl *FirstQualifierInScope = nullptr);
542
543 /// Transform the given declaration name.
544 ///
545 /// By default, transforms the types of conversion function, constructor,
546 /// and destructor names and then (if needed) rebuilds the declaration name.
547 /// Identifiers and selectors are returned unmodified. Subclasses may
548 /// override this function to provide alternate behavior.
549 DeclarationNameInfo
550 TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
551
552 bool TransformRequiresExprRequirements(ArrayRef<concepts::Requirement *> Reqs,
553 llvm::SmallVectorImpl<concepts::Requirement *> &Transformed);
554 concepts::TypeRequirement *
555 TransformTypeRequirement(concepts::TypeRequirement *Req);
556 concepts::ExprRequirement *
557 TransformExprRequirement(concepts::ExprRequirement *Req);
558 concepts::NestedRequirement *
559 TransformNestedRequirement(concepts::NestedRequirement *Req);
560
561 /// Transform the given template name.
562 ///
563 /// \param SS The nested-name-specifier that qualifies the template
564 /// name. This nested-name-specifier must already have been transformed.
565 ///
566 /// \param Name The template name to transform.
567 ///
568 /// \param NameLoc The source location of the template name.
569 ///
570 /// \param ObjectType If we're translating a template name within a member
571 /// access expression, this is the type of the object whose member template
572 /// is being referenced.
573 ///
574 /// \param FirstQualifierInScope If the first part of a nested-name-specifier
575 /// also refers to a name within the current (lexical) scope, this is the
576 /// declaration it refers to.
577 ///
578 /// By default, transforms the template name by transforming the declarations
579 /// and nested-name-specifiers that occur within the template name.
580 /// Subclasses may override this function to provide alternate behavior.
581 TemplateName
582 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
583 SourceLocation NameLoc,
584 QualType ObjectType = QualType(),
585 NamedDecl *FirstQualifierInScope = nullptr,
586 bool AllowInjectedClassName = false);
587
588 /// Transform the given template argument.
589 ///
590 /// By default, this operation transforms the type, expression, or
591 /// declaration stored within the template argument and constructs a
592 /// new template argument from the transformed result. Subclasses may
593 /// override this function to provide alternate behavior.
594 ///
595 /// Returns true if there was an error.
596 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
597 TemplateArgumentLoc &Output,
598 bool Uneval = false);
599
600 /// Transform the given set of template arguments.
601 ///
602 /// By default, this operation transforms all of the template arguments
603 /// in the input set using \c TransformTemplateArgument(), and appends
604 /// the transformed arguments to the output list.
605 ///
606 /// Note that this overload of \c TransformTemplateArguments() is merely
607 /// a convenience function. Subclasses that wish to override this behavior
608 /// should override the iterator-based member template version.
609 ///
610 /// \param Inputs The set of template arguments to be transformed.
611 ///
612 /// \param NumInputs The number of template arguments in \p Inputs.
613 ///
614 /// \param Outputs The set of transformed template arguments output by this
615 /// routine.
616 ///
617 /// Returns true if an error occurred.
618 bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
619 unsigned NumInputs,
620 TemplateArgumentListInfo &Outputs,
621 bool Uneval = false) {
622 return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
623 Uneval);
624 }
625
626 /// Transform the given set of template arguments.
627 ///
628 /// By default, this operation transforms all of the template arguments
629 /// in the input set using \c TransformTemplateArgument(), and appends
630 /// the transformed arguments to the output list.
631 ///
632 /// \param First An iterator to the first template argument.
633 ///
634 /// \param Last An iterator one step past the last template argument.
635 ///
636 /// \param Outputs The set of transformed template arguments output by this
637 /// routine.
638 ///
639 /// Returns true if an error occurred.
640 template<typename InputIterator>
641 bool TransformTemplateArguments(InputIterator First,
642 InputIterator Last,
643 TemplateArgumentListInfo &Outputs,
644 bool Uneval = false);
645
646 /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
647 void InventTemplateArgumentLoc(const TemplateArgument &Arg,
648 TemplateArgumentLoc &ArgLoc);
649
650 /// Fakes up a TypeSourceInfo for a type.
651 TypeSourceInfo *InventTypeSourceInfo(QualType T) {
652 return SemaRef.Context.getTrivialTypeSourceInfo(T,
653 getDerived().getBaseLocation());
654 }
655
656#define ABSTRACT_TYPELOC(CLASS, PARENT)
657#define TYPELOC(CLASS, PARENT) \
658 QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
659#include "clang/AST/TypeLocNodes.def"
660
661 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
662 TemplateTypeParmTypeLoc TL,
663 bool SuppressObjCLifetime);
664 QualType
665 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
666 SubstTemplateTypeParmPackTypeLoc TL,
667 bool SuppressObjCLifetime);
668
669 template<typename Fn>
670 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
671 FunctionProtoTypeLoc TL,
672 CXXRecordDecl *ThisContext,
673 Qualifiers ThisTypeQuals,
674 Fn TransformExceptionSpec);
675
676 bool TransformExceptionSpec(SourceLocation Loc,
677 FunctionProtoType::ExceptionSpecInfo &ESI,
678 SmallVectorImpl<QualType> &Exceptions,
679 bool &Changed);
680
681 StmtResult TransformSEHHandler(Stmt *Handler);
682
683 QualType
684 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
685 TemplateSpecializationTypeLoc TL,
686 TemplateName Template);
687
688 QualType
689 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
690 DependentTemplateSpecializationTypeLoc TL,
691 TemplateName Template,
692 CXXScopeSpec &SS);
693
694 QualType TransformDependentTemplateSpecializationType(
695 TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
696 NestedNameSpecifierLoc QualifierLoc);
697
698 /// Transforms the parameters of a function type into the
699 /// given vectors.
700 ///
701 /// The result vectors should be kept in sync; null entries in the
702 /// variables vector are acceptable.
703 ///
704 /// LastParamTransformed, if non-null, will be set to the index of the last
705 /// parameter on which transfromation was started. In the event of an error,
706 /// this will contain the parameter which failed to instantiate.
707 ///
708 /// Return true on error.
709 bool TransformFunctionTypeParams(
710 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
711 const QualType *ParamTypes,
712 const FunctionProtoType::ExtParameterInfo *ParamInfos,
713 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
714 Sema::ExtParameterInfoBuilder &PInfos, unsigned *LastParamTransformed);
715
716 bool TransformFunctionTypeParams(
717 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
718 const QualType *ParamTypes,
719 const FunctionProtoType::ExtParameterInfo *ParamInfos,
720 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
721 Sema::ExtParameterInfoBuilder &PInfos) {
722 return getDerived().TransformFunctionTypeParams(
723 Loc, Params, ParamTypes, ParamInfos, PTypes, PVars, PInfos, nullptr);
724 }
725
726 /// Transforms the parameters of a requires expresison into the given vectors.
727 ///
728 /// The result vectors should be kept in sync; null entries in the
729 /// variables vector are acceptable.
730 ///
731 /// Returns an unset ExprResult on success. Returns an ExprResult the 'not
732 /// satisfied' RequiresExpr if subsitution failed, OR an ExprError, both of
733 /// which are cases where transformation shouldn't continue.
734 ExprResult TransformRequiresTypeParams(
735 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
736 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
737 SmallVectorImpl<QualType> &PTypes,
738 SmallVectorImpl<ParmVarDecl *> &TransParams,
739 Sema::ExtParameterInfoBuilder &PInfos) {
740 if (getDerived().TransformFunctionTypeParams(
741 KWLoc, Params, /*ParamTypes=*/nullptr,
742 /*ParamInfos=*/nullptr, PTypes, &TransParams, PInfos))
743 return ExprError();
744
745 return ExprResult{};
746 }
747
748 /// Transforms a single function-type parameter. Return null
749 /// on error.
750 ///
751 /// \param indexAdjustment - A number to add to the parameter's
752 /// scope index; can be negative
753 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
754 int indexAdjustment,
755 std::optional<unsigned> NumExpansions,
756 bool ExpectParameterPack);
757
758 /// Transform the body of a lambda-expression.
759 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
760 /// Alternative implementation of TransformLambdaBody that skips transforming
761 /// the body.
762 StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
763
764 QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
765
766 StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
767 ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
768
769 TemplateParameterList *TransformTemplateParameterList(
770 TemplateParameterList *TPL) {
771 return TPL;
772 }
773
774 ExprResult TransformAddressOfOperand(Expr *E);
775
776 ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
777 bool IsAddressOfOperand,
778 TypeSourceInfo **RecoveryTSI);
779
780 ExprResult TransformParenDependentScopeDeclRefExpr(
781 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
782 TypeSourceInfo **RecoveryTSI);
783
784 StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
785
786// FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
787// amount of stack usage with clang.
788#define STMT(Node, Parent) \
789 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
790 StmtResult Transform##Node(Node *S);
791#define VALUESTMT(Node, Parent) \
792 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
793 StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
794#define EXPR(Node, Parent) \
795 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
796 ExprResult Transform##Node(Node *E);
797#define ABSTRACT_STMT(Stmt)
798#include "clang/AST/StmtNodes.inc"
799
800#define GEN_CLANG_CLAUSE_CLASS
801#define CLAUSE_CLASS(Enum, Str, Class) \
802 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
803 OMPClause *Transform##Class(Class *S);
804#include "llvm/Frontend/OpenMP/OMP.inc"
805
806 /// Build a new qualified type given its unqualified type and type location.
807 ///
808 /// By default, this routine adds type qualifiers only to types that can
809 /// have qualifiers, and silently suppresses those qualifiers that are not
810 /// permitted. Subclasses may override this routine to provide different
811 /// behavior.
812 QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
813
814 /// Build a new pointer type given its pointee type.
815 ///
816 /// By default, performs semantic analysis when building the pointer type.
817 /// Subclasses may override this routine to provide different behavior.
818 QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
819
820 /// Build a new block pointer type given its pointee type.
821 ///
822 /// By default, performs semantic analysis when building the block pointer
823 /// type. Subclasses may override this routine to provide different behavior.
824 QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
825
826 /// Build a new reference type given the type it references.
827 ///
828 /// By default, performs semantic analysis when building the
829 /// reference type. Subclasses may override this routine to provide
830 /// different behavior.
831 ///
832 /// \param LValue whether the type was written with an lvalue sigil
833 /// or an rvalue sigil.
834 QualType RebuildReferenceType(QualType ReferentType,
835 bool LValue,
836 SourceLocation Sigil);
837
838 /// Build a new member pointer type given the pointee type and the
839 /// class type it refers into.
840 ///
841 /// By default, performs semantic analysis when building the member pointer
842 /// type. Subclasses may override this routine to provide different behavior.
843 QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
844 SourceLocation Sigil);
845
846 QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
847 SourceLocation ProtocolLAngleLoc,
848 ArrayRef<ObjCProtocolDecl *> Protocols,
849 ArrayRef<SourceLocation> ProtocolLocs,
850 SourceLocation ProtocolRAngleLoc);
851
852 /// Build an Objective-C object type.
853 ///
854 /// By default, performs semantic analysis when building the object type.
855 /// Subclasses may override this routine to provide different behavior.
856 QualType RebuildObjCObjectType(QualType BaseType,
857 SourceLocation Loc,
858 SourceLocation TypeArgsLAngleLoc,
859 ArrayRef<TypeSourceInfo *> TypeArgs,
860 SourceLocation TypeArgsRAngleLoc,
861 SourceLocation ProtocolLAngleLoc,
862 ArrayRef<ObjCProtocolDecl *> Protocols,
863 ArrayRef<SourceLocation> ProtocolLocs,
864 SourceLocation ProtocolRAngleLoc);
865
866 /// Build a new Objective-C object pointer type given the pointee type.
867 ///
868 /// By default, directly builds the pointer type, with no additional semantic
869 /// analysis.
870 QualType RebuildObjCObjectPointerType(QualType PointeeType,
871 SourceLocation Star);
872
873 /// Build a new array type given the element type, size
874 /// modifier, size of the array (if known), size expression, and index type
875 /// qualifiers.
876 ///
877 /// By default, performs semantic analysis when building the array type.
878 /// Subclasses may override this routine to provide different behavior.
879 /// Also by default, all of the other Rebuild*Array
880 QualType RebuildArrayType(QualType ElementType,
881 ArrayType::ArraySizeModifier SizeMod,
882 const llvm::APInt *Size,
883 Expr *SizeExpr,
884 unsigned IndexTypeQuals,
885 SourceRange BracketsRange);
886
887 /// Build a new constant array type given the element type, size
888 /// modifier, (known) size of the array, and index type qualifiers.
889 ///
890 /// By default, performs semantic analysis when building the array type.
891 /// Subclasses may override this routine to provide different behavior.
892 QualType RebuildConstantArrayType(QualType ElementType,
893 ArrayType::ArraySizeModifier SizeMod,
894 const llvm::APInt &Size,
895 Expr *SizeExpr,
896 unsigned IndexTypeQuals,
897 SourceRange BracketsRange);
898
899 /// Build a new incomplete array type given the element type, size
900 /// modifier, and index type qualifiers.
901 ///
902 /// By default, performs semantic analysis when building the array type.
903 /// Subclasses may override this routine to provide different behavior.
904 QualType RebuildIncompleteArrayType(QualType ElementType,
905 ArrayType::ArraySizeModifier SizeMod,
906 unsigned IndexTypeQuals,
907 SourceRange BracketsRange);
908
909 /// Build a new variable-length array type given the element type,
910 /// size modifier, size expression, and index type qualifiers.
911 ///
912 /// By default, performs semantic analysis when building the array type.
913 /// Subclasses may override this routine to provide different behavior.
914 QualType RebuildVariableArrayType(QualType ElementType,
915 ArrayType::ArraySizeModifier SizeMod,
916 Expr *SizeExpr,
917 unsigned IndexTypeQuals,
918 SourceRange BracketsRange);
919
920 /// Build a new dependent-sized array type given the element type,
921 /// size modifier, size expression, and index type qualifiers.
922 ///
923 /// By default, performs semantic analysis when building the array type.
924 /// Subclasses may override this routine to provide different behavior.
925 QualType RebuildDependentSizedArrayType(QualType ElementType,
926 ArrayType::ArraySizeModifier SizeMod,
927 Expr *SizeExpr,
928 unsigned IndexTypeQuals,
929 SourceRange BracketsRange);
930
931 /// Build a new vector type given the element type and
932 /// number of elements.
933 ///
934 /// By default, performs semantic analysis when building the vector type.
935 /// Subclasses may override this routine to provide different behavior.
936 QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
937 VectorType::VectorKind VecKind);
938
939 /// Build a new potentially dependently-sized extended vector type
940 /// given the element type and number of elements.
941 ///
942 /// By default, performs semantic analysis when building the vector type.
943 /// Subclasses may override this routine to provide different behavior.
944 QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
945 SourceLocation AttributeLoc,
946 VectorType::VectorKind);
947
948 /// Build a new extended vector type given the element type and
949 /// number of elements.
950 ///
951 /// By default, performs semantic analysis when building the vector type.
952 /// Subclasses may override this routine to provide different behavior.
953 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
954 SourceLocation AttributeLoc);
955
956 /// Build a new potentially dependently-sized extended vector type
957 /// given the element type and number of elements.
958 ///
959 /// By default, performs semantic analysis when building the vector type.
960 /// Subclasses may override this routine to provide different behavior.
961 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
962 Expr *SizeExpr,
963 SourceLocation AttributeLoc);
964
965 /// Build a new matrix type given the element type and dimensions.
966 QualType RebuildConstantMatrixType(QualType ElementType, unsigned NumRows,
967 unsigned NumColumns);
968
969 /// Build a new matrix type given the type and dependently-defined
970 /// dimensions.
971 QualType RebuildDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
972 Expr *ColumnExpr,
973 SourceLocation AttributeLoc);
974
975 /// Build a new DependentAddressSpaceType or return the pointee
976 /// type variable with the correct address space (retrieved from
977 /// AddrSpaceExpr) applied to it. The former will be returned in cases
978 /// where the address space remains dependent.
979 ///
980 /// By default, performs semantic analysis when building the type with address
981 /// space applied. Subclasses may override this routine to provide different
982 /// behavior.
983 QualType RebuildDependentAddressSpaceType(QualType PointeeType,
984 Expr *AddrSpaceExpr,
985 SourceLocation AttributeLoc);
986
987 /// Build a new function type.
988 ///
989 /// By default, performs semantic analysis when building the function type.
990 /// Subclasses may override this routine to provide different behavior.
991 QualType RebuildFunctionProtoType(QualType T,
992 MutableArrayRef<QualType> ParamTypes,
993 const FunctionProtoType::ExtProtoInfo &EPI);
994
995 /// Build a new unprototyped function type.
996 QualType RebuildFunctionNoProtoType(QualType ResultType);
997
998 /// Rebuild an unresolved typename type, given the decl that
999 /// the UnresolvedUsingTypenameDecl was transformed to.
1000 QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
1001
1002 /// Build a new type found via an alias.
1003 QualType RebuildUsingType(UsingShadowDecl *Found, QualType Underlying) {
1004 return SemaRef.Context.getUsingType(Found, Underlying);
1005 }
1006
1007 /// Build a new typedef type.
1008 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
1009 return SemaRef.Context.getTypeDeclType(Typedef);
1010 }
1011
1012 /// Build a new MacroDefined type.
1013 QualType RebuildMacroQualifiedType(QualType T,
1014 const IdentifierInfo *MacroII) {
1015 return SemaRef.Context.getMacroQualifiedType(T, MacroII);
1016 }
1017
1018 /// Build a new class/struct/union type.
1019 QualType RebuildRecordType(RecordDecl *Record) {
1020 return SemaRef.Context.getTypeDeclType(Record);
1021 }
1022
1023 /// Build a new Enum type.
1024 QualType RebuildEnumType(EnumDecl *Enum) {
1025 return SemaRef.Context.getTypeDeclType(Enum);
1026 }
1027
1028 /// Build a new typeof(expr) type.
1029 ///
1030 /// By default, performs semantic analysis when building the typeof type.
1031 /// Subclasses may override this routine to provide different behavior.
1032 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc,
1033 TypeOfKind Kind);
1034
1035 /// Build a new typeof(type) type.
1036 ///
1037 /// By default, builds a new TypeOfType with the given underlying type.
1038 QualType RebuildTypeOfType(QualType Underlying, TypeOfKind Kind);
1039
1040 /// Build a new unary transform type.
1041 QualType RebuildUnaryTransformType(QualType BaseType,
1042 UnaryTransformType::UTTKind UKind,
1043 SourceLocation Loc);
1044
1045 /// Build a new C++11 decltype type.
1046 ///
1047 /// By default, performs semantic analysis when building the decltype type.
1048 /// Subclasses may override this routine to provide different behavior.
1049 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
1050
1051 /// Build a new C++11 auto type.
1052 ///
1053 /// By default, builds a new AutoType with the given deduced type.
1054 QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword,
1055 ConceptDecl *TypeConstraintConcept,
1056 ArrayRef<TemplateArgument> TypeConstraintArgs) {
1057 // Note, IsDependent is always false here: we implicitly convert an 'auto'
1058 // which has been deduced to a dependent type into an undeduced 'auto', so
1059 // that we'll retry deduction after the transformation.
1060 return SemaRef.Context.getAutoType(Deduced, Keyword,
1061 /*IsDependent*/ false, /*IsPack=*/false,
1062 TypeConstraintConcept,
1063 TypeConstraintArgs);
1064 }
1065
1066 /// By default, builds a new DeducedTemplateSpecializationType with the given
1067 /// deduced type.
1068 QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
1069 QualType Deduced) {
1070 return SemaRef.Context.getDeducedTemplateSpecializationType(
1071 Template, Deduced, /*IsDependent*/ false);
1072 }
1073
1074 /// Build a new template specialization type.
1075 ///
1076 /// By default, performs semantic analysis when building the template
1077 /// specialization type. Subclasses may override this routine to provide
1078 /// different behavior.
1079 QualType RebuildTemplateSpecializationType(TemplateName Template,
1080 SourceLocation TemplateLoc,
1081 TemplateArgumentListInfo &Args);
1082
1083 /// Build a new parenthesized type.
1084 ///
1085 /// By default, builds a new ParenType type from the inner type.
1086 /// Subclasses may override this routine to provide different behavior.
1087 QualType RebuildParenType(QualType InnerType) {
1088 return SemaRef.BuildParenType(InnerType);
1089 }
1090
1091 /// Build a new qualified name type.
1092 ///
1093 /// By default, builds a new ElaboratedType type from the keyword,
1094 /// the nested-name-specifier and the named type.
1095 /// Subclasses may override this routine to provide different behavior.
1096 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1097 ElaboratedTypeKeyword Keyword,
1098 NestedNameSpecifierLoc QualifierLoc,
1099 QualType Named) {
1100 return SemaRef.Context.getElaboratedType(Keyword,
1101 QualifierLoc.getNestedNameSpecifier(),
1102 Named);
1103 }
1104
1105 /// Build a new typename type that refers to a template-id.
1106 ///
1107 /// By default, builds a new DependentNameType type from the
1108 /// nested-name-specifier and the given type. Subclasses may override
1109 /// this routine to provide different behavior.
1110 QualType RebuildDependentTemplateSpecializationType(
1111 ElaboratedTypeKeyword Keyword,
1112 NestedNameSpecifierLoc QualifierLoc,
1113 SourceLocation TemplateKWLoc,
1114 const IdentifierInfo *Name,
1115 SourceLocation NameLoc,
1116 TemplateArgumentListInfo &Args,
1117 bool AllowInjectedClassName) {
1118 // Rebuild the template name.
1119 // TODO: avoid TemplateName abstraction
1120 CXXScopeSpec SS;
1121 SS.Adopt(QualifierLoc);
1122 TemplateName InstName = getDerived().RebuildTemplateName(
1123 SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1124 AllowInjectedClassName);
1125
1126 if (InstName.isNull())
1127 return QualType();
1128
1129 // If it's still dependent, make a dependent specialization.
1130 if (InstName.getAsDependentTemplateName())
1131 return SemaRef.Context.getDependentTemplateSpecializationType(
1132 Keyword, QualifierLoc.getNestedNameSpecifier(), Name,
1133 Args.arguments());
1134
1135 // Otherwise, make an elaborated type wrapping a non-dependent
1136 // specialization.
1137 QualType T =
1138 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1139 if (T.isNull())
1140 return QualType();
1141 return SemaRef.Context.getElaboratedType(
1142 Keyword, QualifierLoc.getNestedNameSpecifier(), T);
1143 }
1144
1145 /// Build a new typename type that refers to an identifier.
1146 ///
1147 /// By default, performs semantic analysis when building the typename type
1148 /// (or elaborated type). Subclasses may override this routine to provide
1149 /// different behavior.
1150 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1151 SourceLocation KeywordLoc,
1152 NestedNameSpecifierLoc QualifierLoc,
1153 const IdentifierInfo *Id,
1154 SourceLocation IdLoc,
1155 bool DeducedTSTContext) {
1156 CXXScopeSpec SS;
1157 SS.Adopt(QualifierLoc);
1158
1159 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1160 // If the name is still dependent, just build a new dependent name type.
1161 if (!SemaRef.computeDeclContext(SS))
1162 return SemaRef.Context.getDependentNameType(Keyword,
1163 QualifierLoc.getNestedNameSpecifier(),
1164 Id);
1165 }
1166
1167 if (Keyword == ETK_None || Keyword == ETK_Typename) {
1168 return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1169 *Id, IdLoc, DeducedTSTContext);
1170 }
1171
1172 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1173
1174 // We had a dependent elaborated-type-specifier that has been transformed
1175 // into a non-dependent elaborated-type-specifier. Find the tag we're
1176 // referring to.
1177 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1178 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1179 if (!DC)
1180 return QualType();
1181
1182 if (SemaRef.RequireCompleteDeclContext(SS, DC))
1183 return QualType();
1184
1185 TagDecl *Tag = nullptr;
1186 SemaRef.LookupQualifiedName(Result, DC);
1187 switch (Result.getResultKind()) {
1188 case LookupResult::NotFound:
1189 case LookupResult::NotFoundInCurrentInstantiation:
1190 break;
1191
1192 case LookupResult::Found:
1193 Tag = Result.getAsSingle<TagDecl>();
1194 break;
1195
1196 case LookupResult::FoundOverloaded:
1197 case LookupResult::FoundUnresolvedValue:
1198 llvm_unreachable("Tag lookup cannot find non-tags")::llvm::llvm_unreachable_internal("Tag lookup cannot find non-tags"
, "clang/lib/Sema/TreeTransform.h", 1198)
;
1199
1200 case LookupResult::Ambiguous:
1201 // Let the LookupResult structure handle ambiguities.
1202 return QualType();
1203 }
1204
1205 if (!Tag) {
1206 // Check where the name exists but isn't a tag type and use that to emit
1207 // better diagnostics.
1208 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1209 SemaRef.LookupQualifiedName(Result, DC);
1210 switch (Result.getResultKind()) {
1211 case LookupResult::Found:
1212 case LookupResult::FoundOverloaded:
1213 case LookupResult::FoundUnresolvedValue: {
1214 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1215 Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1216 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1217 << NTK << Kind;
1218 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1219 break;
1220 }
1221 default:
1222 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1223 << Kind << Id << DC << QualifierLoc.getSourceRange();
1224 break;
1225 }
1226 return QualType();
1227 }
1228
1229 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1230 IdLoc, Id)) {
1231 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1232 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1233 return QualType();
1234 }
1235
1236 // Build the elaborated-type-specifier type.
1237 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1238 return SemaRef.Context.getElaboratedType(Keyword,
1239 QualifierLoc.getNestedNameSpecifier(),
1240 T);
1241 }
1242
1243 /// Build a new pack expansion type.
1244 ///
1245 /// By default, builds a new PackExpansionType type from the given pattern.
1246 /// Subclasses may override this routine to provide different behavior.
1247 QualType RebuildPackExpansionType(QualType Pattern, SourceRange PatternRange,
1248 SourceLocation EllipsisLoc,
1249 std::optional<unsigned> NumExpansions) {
1250 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1251 NumExpansions);
1252 }
1253
1254 /// Build a new atomic type given its value type.
1255 ///
1256 /// By default, performs semantic analysis when building the atomic type.
1257 /// Subclasses may override this routine to provide different behavior.
1258 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1259
1260 /// Build a new pipe type given its value type.
1261 QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1262 bool isReadPipe);
1263
1264 /// Build a bit-precise int given its value type.
1265 QualType RebuildBitIntType(bool IsUnsigned, unsigned NumBits,
1266 SourceLocation Loc);
1267
1268 /// Build a dependent bit-precise int given its value type.
1269 QualType RebuildDependentBitIntType(bool IsUnsigned, Expr *NumBitsExpr,
1270 SourceLocation Loc);
1271
1272 /// Build a new template name given a nested name specifier, a flag
1273 /// indicating whether the "template" keyword was provided, and the template
1274 /// that the template name refers to.
1275 ///
1276 /// By default, builds the new template name directly. Subclasses may override
1277 /// this routine to provide different behavior.
1278 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1279 bool TemplateKW,
1280 TemplateDecl *Template);
1281
1282 /// Build a new template name given a nested name specifier and the
1283 /// name that is referred to as a template.
1284 ///
1285 /// By default, performs semantic analysis to determine whether the name can
1286 /// be resolved to a specific template, then builds the appropriate kind of
1287 /// template name. Subclasses may override this routine to provide different
1288 /// behavior.
1289 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1290 SourceLocation TemplateKWLoc,
1291 const IdentifierInfo &Name,
1292 SourceLocation NameLoc, QualType ObjectType,
1293 NamedDecl *FirstQualifierInScope,
1294 bool AllowInjectedClassName);
1295
1296 /// Build a new template name given a nested name specifier and the
1297 /// overloaded operator name that is referred to as a template.
1298 ///
1299 /// By default, performs semantic analysis to determine whether the name can
1300 /// be resolved to a specific template, then builds the appropriate kind of
1301 /// template name. Subclasses may override this routine to provide different
1302 /// behavior.
1303 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1304 SourceLocation TemplateKWLoc,
1305 OverloadedOperatorKind Operator,
1306 SourceLocation NameLoc, QualType ObjectType,
1307 bool AllowInjectedClassName);
1308
1309 /// Build a new template name given a template template parameter pack
1310 /// and the
1311 ///
1312 /// By default, performs semantic analysis to determine whether the name can
1313 /// be resolved to a specific template, then builds the appropriate kind of
1314 /// template name. Subclasses may override this routine to provide different
1315 /// behavior.
1316 TemplateName RebuildTemplateName(const TemplateArgument &ArgPack,
1317 Decl *AssociatedDecl, unsigned Index,
1318 bool Final) {
1319 return getSema().Context.getSubstTemplateTemplateParmPack(
1320 ArgPack, AssociatedDecl, Index, Final);
1321 }
1322
1323 /// Build a new compound statement.
1324 ///
1325 /// By default, performs semantic analysis to build the new statement.
1326 /// Subclasses may override this routine to provide different behavior.
1327 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1328 MultiStmtArg Statements,
1329 SourceLocation RBraceLoc,
1330 bool IsStmtExpr) {
1331 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1332 IsStmtExpr);
1333 }
1334
1335 /// Build a new case statement.
1336 ///
1337 /// By default, performs semantic analysis to build the new statement.
1338 /// Subclasses may override this routine to provide different behavior.
1339 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1340 Expr *LHS,
1341 SourceLocation EllipsisLoc,
1342 Expr *RHS,
1343 SourceLocation ColonLoc) {
1344 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1345 ColonLoc);
1346 }
1347
1348 /// Attach the body to a new case statement.
1349 ///
1350 /// By default, performs semantic analysis to build the new statement.
1351 /// Subclasses may override this routine to provide different behavior.
1352 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1353 getSema().ActOnCaseStmtBody(S, Body);
1354 return S;
1355 }
1356
1357 /// Build a new default statement.
1358 ///
1359 /// By default, performs semantic analysis to build the new statement.
1360 /// Subclasses may override this routine to provide different behavior.
1361 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1362 SourceLocation ColonLoc,
1363 Stmt *SubStmt) {
1364 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1365 /*CurScope=*/nullptr);
1366 }
1367
1368 /// Build a new label 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 RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1373 SourceLocation ColonLoc, Stmt *SubStmt) {
1374 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1375 }
1376
1377 /// Build a new attributed statement.
1378 ///
1379 /// By default, performs semantic analysis to build the new statement.
1380 /// Subclasses may override this routine to provide different behavior.
1381 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1382 ArrayRef<const Attr *> Attrs,
1383 Stmt *SubStmt) {
1384 return SemaRef.BuildAttributedStmt(AttrLoc, Attrs, SubStmt);
1385 }
1386
1387 /// Build a new "if" statement.
1388 ///
1389 /// By default, performs semantic analysis to build the new statement.
1390 /// Subclasses may override this routine to provide different behavior.
1391 StmtResult RebuildIfStmt(SourceLocation IfLoc, IfStatementKind Kind,
1392 SourceLocation LParenLoc, Sema::ConditionResult Cond,
1393 SourceLocation RParenLoc, Stmt *Init, Stmt *Then,
1394 SourceLocation ElseLoc, Stmt *Else) {
1395 return getSema().ActOnIfStmt(IfLoc, Kind, LParenLoc, Init, Cond, RParenLoc,
1396 Then, ElseLoc, Else);
1397 }
1398
1399 /// Start building a new switch statement.
1400 ///
1401 /// By default, performs semantic analysis to build the new statement.
1402 /// Subclasses may override this routine to provide different behavior.
1403 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1404 SourceLocation LParenLoc, Stmt *Init,
1405 Sema::ConditionResult Cond,
1406 SourceLocation RParenLoc) {
1407 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, LParenLoc, Init, Cond,
1408 RParenLoc);
1409 }
1410
1411 /// Attach the body to the switch 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 RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1416 Stmt *Switch, Stmt *Body) {
1417 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1418 }
1419
1420 /// Build a new while statement.
1421 ///
1422 /// By default, performs semantic analysis to build the new statement.
1423 /// Subclasses may override this routine to provide different behavior.
1424 StmtResult RebuildWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
1425 Sema::ConditionResult Cond,
1426 SourceLocation RParenLoc, Stmt *Body) {
1427 return getSema().ActOnWhileStmt(WhileLoc, LParenLoc, Cond, RParenLoc, Body);
1428 }
1429
1430 /// Build a new do-while statement.
1431 ///
1432 /// By default, performs semantic analysis to build the new statement.
1433 /// Subclasses may override this routine to provide different behavior.
1434 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1435 SourceLocation WhileLoc, SourceLocation LParenLoc,
1436 Expr *Cond, SourceLocation RParenLoc) {
1437 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1438 Cond, RParenLoc);
1439 }
1440
1441 /// Build a new for statement.
1442 ///
1443 /// By default, performs semantic analysis to build the new statement.
1444 /// Subclasses may override this routine to provide different behavior.
1445 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1446 Stmt *Init, Sema::ConditionResult Cond,
1447 Sema::FullExprArg Inc, SourceLocation RParenLoc,
1448 Stmt *Body) {
1449 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1450 Inc, RParenLoc, Body);
1451 }
1452
1453 /// Build a new goto statement.
1454 ///
1455 /// By default, performs semantic analysis to build the new statement.
1456 /// Subclasses may override this routine to provide different behavior.
1457 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1458 LabelDecl *Label) {
1459 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1460 }
1461
1462 /// Build a new indirect goto statement.
1463 ///
1464 /// By default, performs semantic analysis to build the new statement.
1465 /// Subclasses may override this routine to provide different behavior.
1466 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1467 SourceLocation StarLoc,
1468 Expr *Target) {
1469 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1470 }
1471
1472 /// Build a new return statement.
1473 ///
1474 /// By default, performs semantic analysis to build the new statement.
1475 /// Subclasses may override this routine to provide different behavior.
1476 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1477 return getSema().BuildReturnStmt(ReturnLoc, Result);
1478 }
1479
1480 /// Build a new declaration statement.
1481 ///
1482 /// By default, performs semantic analysis to build the new statement.
1483 /// Subclasses may override this routine to provide different behavior.
1484 StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1485 SourceLocation StartLoc, SourceLocation EndLoc) {
1486 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1487 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1488 }
1489
1490 /// Build a new inline asm statement.
1491 ///
1492 /// By default, performs semantic analysis to build the new statement.
1493 /// Subclasses may override this routine to provide different behavior.
1494 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1495 bool IsVolatile, unsigned NumOutputs,
1496 unsigned NumInputs, IdentifierInfo **Names,
1497 MultiExprArg Constraints, MultiExprArg Exprs,
1498 Expr *AsmString, MultiExprArg Clobbers,
1499 unsigned NumLabels,
1500 SourceLocation RParenLoc) {
1501 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1502 NumInputs, Names, Constraints, Exprs,
1503 AsmString, Clobbers, NumLabels, RParenLoc);
1504 }
1505
1506 /// Build a new MS style inline asm statement.
1507 ///
1508 /// By default, performs semantic analysis to build the new statement.
1509 /// Subclasses may override this routine to provide different behavior.
1510 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1511 ArrayRef<Token> AsmToks,
1512 StringRef AsmString,
1513 unsigned NumOutputs, unsigned NumInputs,
1514 ArrayRef<StringRef> Constraints,
1515 ArrayRef<StringRef> Clobbers,
1516 ArrayRef<Expr*> Exprs,
1517 SourceLocation EndLoc) {
1518 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1519 NumOutputs, NumInputs,
1520 Constraints, Clobbers, Exprs, EndLoc);
1521 }
1522
1523 /// Build a new co_return statement.
1524 ///
1525 /// By default, performs semantic analysis to build the new statement.
1526 /// Subclasses may override this routine to provide different behavior.
1527 StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1528 bool IsImplicit) {
1529 return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1530 }
1531
1532 /// Build a new co_await expression.
1533 ///
1534 /// By default, performs semantic analysis to build the new expression.
1535 /// Subclasses may override this routine to provide different behavior.
1536 ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Operand,
1537 UnresolvedLookupExpr *OpCoawaitLookup,
1538 bool IsImplicit) {
1539 // This function rebuilds a coawait-expr given its operator.
1540 // For an explicit coawait-expr, the rebuild involves the full set
1541 // of transformations performed by BuildUnresolvedCoawaitExpr(),
1542 // including calling await_transform().
1543 // For an implicit coawait-expr, we need to rebuild the "operator
1544 // coawait" but not await_transform(), so use BuildResolvedCoawaitExpr().
1545 // This mirrors how the implicit CoawaitExpr is originally created
1546 // in Sema::ActOnCoroutineBodyStart().
1547 if (IsImplicit) {
1548 ExprResult Suspend = getSema().BuildOperatorCoawaitCall(
1549 CoawaitLoc, Operand, OpCoawaitLookup);
1550 if (Suspend.isInvalid())
1551 return ExprError();
1552 return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Operand,
1553 Suspend.get(), true);
1554 }
1555
1556 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Operand,
1557 OpCoawaitLookup);
1558 }
1559
1560 /// Build a new co_await expression.
1561 ///
1562 /// By default, performs semantic analysis to build the new expression.
1563 /// Subclasses may override this routine to provide different behavior.
1564 ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1565 Expr *Result,
1566 UnresolvedLookupExpr *Lookup) {
1567 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1568 }
1569
1570 /// Build a new co_yield expression.
1571 ///
1572 /// By default, performs semantic analysis to build the new expression.
1573 /// Subclasses may override this routine to provide different behavior.
1574 ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1575 return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1576 }
1577
1578 StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1579 return getSema().BuildCoroutineBodyStmt(Args);
1580 }
1581
1582 /// Build a new Objective-C \@try statement.
1583 ///
1584 /// By default, performs semantic analysis to build the new statement.
1585 /// Subclasses may override this routine to provide different behavior.
1586 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1587 Stmt *TryBody,
1588 MultiStmtArg CatchStmts,
1589 Stmt *Finally) {
1590 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1591 Finally);
1592 }
1593
1594 /// Rebuild an Objective-C exception declaration.
1595 ///
1596 /// By default, performs semantic analysis to build the new declaration.
1597 /// Subclasses may override this routine to provide different behavior.
1598 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1599 TypeSourceInfo *TInfo, QualType T) {
1600 return getSema().BuildObjCExceptionDecl(TInfo, T,
1601 ExceptionDecl->getInnerLocStart(),
1602 ExceptionDecl->getLocation(),
1603 ExceptionDecl->getIdentifier());
1604 }
1605
1606 /// Build a new Objective-C \@catch statement.
1607 ///
1608 /// By default, performs semantic analysis to build the new statement.
1609 /// Subclasses may override this routine to provide different behavior.
1610 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1611 SourceLocation RParenLoc,
1612 VarDecl *Var,
1613 Stmt *Body) {
1614 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1615 Var, Body);
1616 }
1617
1618 /// Build a new Objective-C \@finally statement.
1619 ///
1620 /// By default, performs semantic analysis to build the new statement.
1621 /// Subclasses may override this routine to provide different behavior.
1622 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1623 Stmt *Body) {
1624 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1625 }
1626
1627 /// Build a new Objective-C \@throw statement.
1628 ///
1629 /// By default, performs semantic analysis to build the new statement.
1630 /// Subclasses may override this routine to provide different behavior.
1631 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1632 Expr *Operand) {
1633 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1634 }
1635
1636 /// Build a new OpenMP Canonical loop.
1637 ///
1638 /// Ensures that the outermost loop in @p LoopStmt is wrapped by a
1639 /// OMPCanonicalLoop.
1640 StmtResult RebuildOMPCanonicalLoop(Stmt *LoopStmt) {
1641 return getSema().ActOnOpenMPCanonicalLoop(LoopStmt);
1642 }
1643
1644 /// Build a new OpenMP executable directive.
1645 ///
1646 /// By default, performs semantic analysis to build the new statement.
1647 /// Subclasses may override this routine to provide different behavior.
1648 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1649 DeclarationNameInfo DirName,
1650 OpenMPDirectiveKind CancelRegion,
1651 ArrayRef<OMPClause *> Clauses,
1652 Stmt *AStmt, SourceLocation StartLoc,
1653 SourceLocation EndLoc) {
1654 return getSema().ActOnOpenMPExecutableDirective(
1655 Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1656 }
1657
1658 /// Build a new OpenMP 'if' clause.
1659 ///
1660 /// By default, performs semantic analysis to build the new OpenMP clause.
1661 /// Subclasses may override this routine to provide different behavior.
1662 OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1663 Expr *Condition, SourceLocation StartLoc,
1664 SourceLocation LParenLoc,
1665 SourceLocation NameModifierLoc,
1666 SourceLocation ColonLoc,
1667 SourceLocation EndLoc) {
1668 return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1669 LParenLoc, NameModifierLoc, ColonLoc,
1670 EndLoc);
1671 }
1672
1673 /// Build a new OpenMP 'final' clause.
1674 ///
1675 /// By default, performs semantic analysis to build the new OpenMP clause.
1676 /// Subclasses may override this routine to provide different behavior.
1677 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1678 SourceLocation LParenLoc,
1679 SourceLocation EndLoc) {
1680 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1681 EndLoc);
1682 }
1683
1684 /// Build a new OpenMP 'num_threads' 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 *RebuildOMPNumThreadsClause(Expr *NumThreads,
1689 SourceLocation StartLoc,
1690 SourceLocation LParenLoc,
1691 SourceLocation EndLoc) {
1692 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1693 LParenLoc, EndLoc);
1694 }
1695
1696 /// Build a new OpenMP 'safelen' clause.
1697 ///
1698 /// By default, performs semantic analysis to build the new OpenMP clause.
1699 /// Subclasses may override this routine to provide different behavior.
1700 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1701 SourceLocation LParenLoc,
1702 SourceLocation EndLoc) {
1703 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1704 }
1705
1706 /// Build a new OpenMP 'simdlen' clause.
1707 ///
1708 /// By default, performs semantic analysis to build the new OpenMP clause.
1709 /// Subclasses may override this routine to provide different behavior.
1710 OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1711 SourceLocation LParenLoc,
1712 SourceLocation EndLoc) {
1713 return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1714 }
1715
1716 OMPClause *RebuildOMPSizesClause(ArrayRef<Expr *> Sizes,
1717 SourceLocation StartLoc,
1718 SourceLocation LParenLoc,
1719 SourceLocation EndLoc) {
1720 return getSema().ActOnOpenMPSizesClause(Sizes, StartLoc, LParenLoc, EndLoc);
1721 }
1722
1723 /// Build a new OpenMP 'full' clause.
1724 OMPClause *RebuildOMPFullClause(SourceLocation StartLoc,
1725 SourceLocation EndLoc) {
1726 return getSema().ActOnOpenMPFullClause(StartLoc, EndLoc);
1727 }
1728
1729 /// Build a new OpenMP 'partial' clause.
1730 OMPClause *RebuildOMPPartialClause(Expr *Factor, SourceLocation StartLoc,
1731 SourceLocation LParenLoc,
1732 SourceLocation EndLoc) {
1733 return getSema().ActOnOpenMPPartialClause(Factor, StartLoc, LParenLoc,
1734 EndLoc);
1735 }
1736
1737 /// Build a new OpenMP 'allocator' clause.
1738 ///
1739 /// By default, performs semantic analysis to build the new OpenMP clause.
1740 /// Subclasses may override this routine to provide different behavior.
1741 OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1742 SourceLocation LParenLoc,
1743 SourceLocation EndLoc) {
1744 return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1745 }
1746
1747 /// Build a new OpenMP 'collapse' clause.
1748 ///
1749 /// By default, performs semantic analysis to build the new OpenMP clause.
1750 /// Subclasses may override this routine to provide different behavior.
1751 OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1752 SourceLocation LParenLoc,
1753 SourceLocation EndLoc) {
1754 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1755 EndLoc);
1756 }
1757
1758 /// Build a new OpenMP 'default' clause.
1759 ///
1760 /// By default, performs semantic analysis to build the new OpenMP clause.
1761 /// Subclasses may override this routine to provide different behavior.
1762 OMPClause *RebuildOMPDefaultClause(DefaultKind Kind, SourceLocation KindKwLoc,
1763 SourceLocation StartLoc,
1764 SourceLocation LParenLoc,
1765 SourceLocation EndLoc) {
1766 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1767 StartLoc, LParenLoc, EndLoc);
1768 }
1769
1770 /// Build a new OpenMP 'proc_bind' clause.
1771 ///
1772 /// By default, performs semantic analysis to build the new OpenMP clause.
1773 /// Subclasses may override this routine to provide different behavior.
1774 OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1775 SourceLocation KindKwLoc,
1776 SourceLocation StartLoc,
1777 SourceLocation LParenLoc,
1778 SourceLocation EndLoc) {
1779 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1780 StartLoc, LParenLoc, EndLoc);
1781 }
1782
1783 /// Build a new OpenMP 'schedule' clause.
1784 ///
1785 /// By default, performs semantic analysis to build the new OpenMP clause.
1786 /// Subclasses may override this routine to provide different behavior.
1787 OMPClause *RebuildOMPScheduleClause(
1788 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1789 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1790 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1791 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1792 return getSema().ActOnOpenMPScheduleClause(
1793 M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1794 CommaLoc, EndLoc);
1795 }
1796
1797 /// Build a new OpenMP 'ordered' 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 *RebuildOMPOrderedClause(SourceLocation StartLoc,
1802 SourceLocation EndLoc,
1803 SourceLocation LParenLoc, Expr *Num) {
1804 return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1805 }
1806
1807 /// Build a new OpenMP 'private' clause.
1808 ///
1809 /// By default, performs semantic analysis to build the new OpenMP clause.
1810 /// Subclasses may override this routine to provide different behavior.
1811 OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1812 SourceLocation StartLoc,
1813 SourceLocation LParenLoc,
1814 SourceLocation EndLoc) {
1815 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1816 EndLoc);
1817 }
1818
1819 /// Build a new OpenMP 'firstprivate' clause.
1820 ///
1821 /// By default, performs semantic analysis to build the new OpenMP clause.
1822 /// Subclasses may override this routine to provide different behavior.
1823 OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1824 SourceLocation StartLoc,
1825 SourceLocation LParenLoc,
1826 SourceLocation EndLoc) {
1827 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1828 EndLoc);
1829 }
1830
1831 /// Build a new OpenMP 'lastprivate' clause.
1832 ///
1833 /// By default, performs semantic analysis to build the new OpenMP clause.
1834 /// Subclasses may override this routine to provide different behavior.
1835 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1836 OpenMPLastprivateModifier LPKind,
1837 SourceLocation LPKindLoc,
1838 SourceLocation ColonLoc,
1839 SourceLocation StartLoc,
1840 SourceLocation LParenLoc,
1841 SourceLocation EndLoc) {
1842 return getSema().ActOnOpenMPLastprivateClause(
1843 VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1844 }
1845
1846 /// Build a new OpenMP 'shared' clause.
1847 ///
1848 /// By default, performs semantic analysis to build the new OpenMP clause.
1849 /// Subclasses may override this routine to provide different behavior.
1850 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1851 SourceLocation StartLoc,
1852 SourceLocation LParenLoc,
1853 SourceLocation EndLoc) {
1854 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1855 EndLoc);
1856 }
1857
1858 /// Build a new OpenMP 'reduction' clause.
1859 ///
1860 /// By default, performs semantic analysis to build the new statement.
1861 /// Subclasses may override this routine to provide different behavior.
1862 OMPClause *RebuildOMPReductionClause(
1863 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
1864 SourceLocation StartLoc, SourceLocation LParenLoc,
1865 SourceLocation ModifierLoc, SourceLocation ColonLoc,
1866 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
1867 const DeclarationNameInfo &ReductionId,
1868 ArrayRef<Expr *> UnresolvedReductions) {
1869 return getSema().ActOnOpenMPReductionClause(
1870 VarList, Modifier, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc,
1871 ReductionIdScopeSpec, ReductionId, UnresolvedReductions);
1872 }
1873
1874 /// Build a new OpenMP 'task_reduction' 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 *RebuildOMPTaskReductionClause(
1879 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1880 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1881 CXXScopeSpec &ReductionIdScopeSpec,
1882 const DeclarationNameInfo &ReductionId,
1883 ArrayRef<Expr *> UnresolvedReductions) {
1884 return getSema().ActOnOpenMPTaskReductionClause(
1885 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1886 ReductionId, UnresolvedReductions);
1887 }
1888
1889 /// Build a new OpenMP 'in_reduction' clause.
1890 ///
1891 /// By default, performs semantic analysis to build the new statement.
1892 /// Subclasses may override this routine to provide different behavior.
1893 OMPClause *
1894 RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1895 SourceLocation LParenLoc, SourceLocation ColonLoc,
1896 SourceLocation EndLoc,
1897 CXXScopeSpec &ReductionIdScopeSpec,
1898 const DeclarationNameInfo &ReductionId,
1899 ArrayRef<Expr *> UnresolvedReductions) {
1900 return getSema().ActOnOpenMPInReductionClause(
1901 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1902 ReductionId, UnresolvedReductions);
1903 }
1904
1905 /// Build a new OpenMP 'linear' clause.
1906 ///
1907 /// By default, performs semantic analysis to build the new OpenMP clause.
1908 /// Subclasses may override this routine to provide different behavior.
1909 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1910 SourceLocation StartLoc,
1911 SourceLocation LParenLoc,
1912 OpenMPLinearClauseKind Modifier,
1913 SourceLocation ModifierLoc,
1914 SourceLocation ColonLoc,
1915 SourceLocation EndLoc) {
1916 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1917 Modifier, ModifierLoc, ColonLoc,
1918 EndLoc);
1919 }
1920
1921 /// Build a new OpenMP 'aligned' clause.
1922 ///
1923 /// By default, performs semantic analysis to build the new OpenMP clause.
1924 /// Subclasses may override this routine to provide different behavior.
1925 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1926 SourceLocation StartLoc,
1927 SourceLocation LParenLoc,
1928 SourceLocation ColonLoc,
1929 SourceLocation EndLoc) {
1930 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1931 LParenLoc, ColonLoc, EndLoc);
1932 }
1933
1934 /// Build a new OpenMP 'copyin' clause.
1935 ///
1936 /// By default, performs semantic analysis to build the new OpenMP clause.
1937 /// Subclasses may override this routine to provide different behavior.
1938 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1939 SourceLocation StartLoc,
1940 SourceLocation LParenLoc,
1941 SourceLocation EndLoc) {
1942 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1943 EndLoc);
1944 }
1945
1946 /// Build a new OpenMP 'copyprivate' clause.
1947 ///
1948 /// By default, performs semantic analysis to build the new OpenMP clause.
1949 /// Subclasses may override this routine to provide different behavior.
1950 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1951 SourceLocation StartLoc,
1952 SourceLocation LParenLoc,
1953 SourceLocation EndLoc) {
1954 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1955 EndLoc);
1956 }
1957
1958 /// Build a new OpenMP 'flush' pseudo clause.
1959 ///
1960 /// By default, performs semantic analysis to build the new OpenMP clause.
1961 /// Subclasses may override this routine to provide different behavior.
1962 OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1963 SourceLocation StartLoc,
1964 SourceLocation LParenLoc,
1965 SourceLocation EndLoc) {
1966 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1967 EndLoc);
1968 }
1969
1970 /// Build a new OpenMP 'depobj' pseudo clause.
1971 ///
1972 /// By default, performs semantic analysis to build the new OpenMP clause.
1973 /// Subclasses may override this routine to provide different behavior.
1974 OMPClause *RebuildOMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
1975 SourceLocation LParenLoc,
1976 SourceLocation EndLoc) {
1977 return getSema().ActOnOpenMPDepobjClause(Depobj, StartLoc, LParenLoc,
1978 EndLoc);
1979 }
1980
1981 /// Build a new OpenMP 'depend' pseudo clause.
1982 ///
1983 /// By default, performs semantic analysis to build the new OpenMP clause.
1984 /// Subclasses may override this routine to provide different behavior.
1985 OMPClause *RebuildOMPDependClause(OMPDependClause::DependDataTy Data,
1986 Expr *DepModifier, ArrayRef<Expr *> VarList,
1987 SourceLocation StartLoc,
1988 SourceLocation LParenLoc,
1989 SourceLocation EndLoc) {
1990 return getSema().ActOnOpenMPDependClause(Data, DepModifier, VarList,
1991 StartLoc, LParenLoc, EndLoc);
1992 }
1993
1994 /// Build a new OpenMP 'device' clause.
1995 ///
1996 /// By default, performs semantic analysis to build the new statement.
1997 /// Subclasses may override this routine to provide different behavior.
1998 OMPClause *RebuildOMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
1999 Expr *Device, SourceLocation StartLoc,
2000 SourceLocation LParenLoc,
2001 SourceLocation ModifierLoc,
2002 SourceLocation EndLoc) {
2003 return getSema().ActOnOpenMPDeviceClause(Modifier, Device, StartLoc,
2004 LParenLoc, ModifierLoc, EndLoc);
2005 }
2006
2007 /// Build a new OpenMP 'map' clause.
2008 ///
2009 /// By default, performs semantic analysis to build the new OpenMP clause.
2010 /// Subclasses may override this routine to provide different behavior.
2011 OMPClause *RebuildOMPMapClause(
2012 Expr *IteratorModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
2013 ArrayRef<SourceLocation> MapTypeModifiersLoc,
2014 CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
2015 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
2016 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
2017 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
2018 return getSema().ActOnOpenMPMapClause(
2019 IteratorModifier, MapTypeModifiers, MapTypeModifiersLoc,
2020 MapperIdScopeSpec, MapperId, MapType, IsMapTypeImplicit, MapLoc,
2021 ColonLoc, VarList, Locs,
2022 /*NoDiagnose=*/false, UnresolvedMappers);
2023 }
2024
2025 /// Build a new OpenMP 'allocate' clause.
2026 ///
2027 /// By default, performs semantic analysis to build the new OpenMP clause.
2028 /// Subclasses may override this routine to provide different behavior.
2029 OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
2030 SourceLocation StartLoc,
2031 SourceLocation LParenLoc,
2032 SourceLocation ColonLoc,
2033 SourceLocation EndLoc) {
2034 return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
2035 LParenLoc, ColonLoc, EndLoc);
2036 }
2037
2038 /// Build a new OpenMP 'num_teams' clause.
2039 ///
2040 /// By default, performs semantic analysis to build the new statement.
2041 /// Subclasses may override this routine to provide different behavior.
2042 OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
2043 SourceLocation LParenLoc,
2044 SourceLocation EndLoc) {
2045 return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
2046 EndLoc);
2047 }
2048
2049 /// Build a new OpenMP 'thread_limit' clause.
2050 ///
2051 /// By default, performs semantic analysis to build the new statement.
2052 /// Subclasses may override this routine to provide different behavior.
2053 OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
2054 SourceLocation StartLoc,
2055 SourceLocation LParenLoc,
2056 SourceLocation EndLoc) {
2057 return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
2058 LParenLoc, EndLoc);
2059 }
2060
2061 /// Build a new OpenMP 'priority' clause.
2062 ///
2063 /// By default, performs semantic analysis to build the new statement.
2064 /// Subclasses may override this routine to provide different behavior.
2065 OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
2066 SourceLocation LParenLoc,
2067 SourceLocation EndLoc) {
2068 return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
2069 EndLoc);
2070 }
2071
2072 /// Build a new OpenMP 'grainsize' clause.
2073 ///
2074 /// By default, performs semantic analysis to build the new statement.
2075 /// Subclasses may override this routine to provide different behavior.
2076 OMPClause *RebuildOMPGrainsizeClause(OpenMPGrainsizeClauseModifier Modifier,
2077 Expr *Device, SourceLocation StartLoc,
2078 SourceLocation LParenLoc,
2079 SourceLocation ModifierLoc,
2080 SourceLocation EndLoc) {
2081 return getSema().ActOnOpenMPGrainsizeClause(Modifier, Device, StartLoc,
2082 LParenLoc, ModifierLoc, EndLoc);
2083 }
2084
2085 /// Build a new OpenMP 'num_tasks' clause.
2086 ///
2087 /// By default, performs semantic analysis to build the new statement.
2088 /// Subclasses may override this routine to provide different behavior.
2089 OMPClause *RebuildOMPNumTasksClause(OpenMPNumTasksClauseModifier Modifier,
2090 Expr *NumTasks, SourceLocation StartLoc,
2091 SourceLocation LParenLoc,
2092 SourceLocation ModifierLoc,
2093 SourceLocation EndLoc) {
2094 return getSema().ActOnOpenMPNumTasksClause(Modifier, NumTasks, StartLoc,
2095 LParenLoc, ModifierLoc, EndLoc);
2096 }
2097
2098 /// Build a new OpenMP 'hint' clause.
2099 ///
2100 /// By default, performs semantic analysis to build the new statement.
2101 /// Subclasses may override this routine to provide different behavior.
2102 OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
2103 SourceLocation LParenLoc,
2104 SourceLocation EndLoc) {
2105 return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
2106 }
2107
2108 /// Build a new OpenMP 'detach' clause.
2109 ///
2110 /// By default, performs semantic analysis to build the new statement.
2111 /// Subclasses may override this routine to provide different behavior.
2112 OMPClause *RebuildOMPDetachClause(Expr *Evt, SourceLocation StartLoc,
2113 SourceLocation LParenLoc,
2114 SourceLocation EndLoc) {
2115 return getSema().ActOnOpenMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
2116 }
2117
2118 /// Build a new OpenMP 'dist_schedule' clause.
2119 ///
2120 /// By default, performs semantic analysis to build the new OpenMP clause.
2121 /// Subclasses may override this routine to provide different behavior.
2122 OMPClause *
2123 RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
2124 Expr *ChunkSize, SourceLocation StartLoc,
2125 SourceLocation LParenLoc, SourceLocation KindLoc,
2126 SourceLocation CommaLoc, SourceLocation EndLoc) {
2127 return getSema().ActOnOpenMPDistScheduleClause(
2128 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
2129 }
2130
2131 /// Build a new OpenMP 'to' clause.
2132 ///
2133 /// By default, performs semantic analysis to build the new statement.
2134 /// Subclasses may override this routine to provide different behavior.
2135 OMPClause *
2136 RebuildOMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2137 ArrayRef<SourceLocation> MotionModifiersLoc,
2138 CXXScopeSpec &MapperIdScopeSpec,
2139 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2140 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2141 ArrayRef<Expr *> UnresolvedMappers) {
2142 return getSema().ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
2143 MapperIdScopeSpec, MapperId, ColonLoc,
2144 VarList, Locs, UnresolvedMappers);
2145 }
2146
2147 /// Build a new OpenMP 'from' clause.
2148 ///
2149 /// By default, performs semantic analysis to build the new statement.
2150 /// Subclasses may override this routine to provide different behavior.
2151 OMPClause *
2152 RebuildOMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2153 ArrayRef<SourceLocation> MotionModifiersLoc,
2154 CXXScopeSpec &MapperIdScopeSpec,
2155 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2156 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2157 ArrayRef<Expr *> UnresolvedMappers) {
2158 return getSema().ActOnOpenMPFromClause(
2159 MotionModifiers, MotionModifiersLoc, MapperIdScopeSpec, MapperId,
2160 ColonLoc, VarList, Locs, UnresolvedMappers);
2161 }
2162
2163 /// Build a new OpenMP 'use_device_ptr' clause.
2164 ///
2165 /// By default, performs semantic analysis to build the new OpenMP clause.
2166 /// Subclasses may override this routine to provide different behavior.
2167 OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
2168 const OMPVarListLocTy &Locs) {
2169 return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
2170 }
2171
2172 /// Build a new OpenMP 'use_device_addr' clause.
2173 ///
2174 /// By default, performs semantic analysis to build the new OpenMP clause.
2175 /// Subclasses may override this routine to provide different behavior.
2176 OMPClause *RebuildOMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
2177 const OMPVarListLocTy &Locs) {
2178 return getSema().ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
2179 }
2180
2181 /// Build a new OpenMP 'is_device_ptr' clause.
2182 ///
2183 /// By default, performs semantic analysis to build the new OpenMP clause.
2184 /// Subclasses may override this routine to provide different behavior.
2185 OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
2186 const OMPVarListLocTy &Locs) {
2187 return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
2188 }
2189
2190 /// Build a new OpenMP 'has_device_addr' clause.
2191 ///
2192 /// By default, performs semantic analysis to build the new OpenMP clause.
2193 /// Subclasses may override this routine to provide different behavior.
2194 OMPClause *RebuildOMPHasDeviceAddrClause(ArrayRef<Expr *> VarList,
2195 const OMPVarListLocTy &Locs) {
2196 return getSema().ActOnOpenMPHasDeviceAddrClause(VarList, Locs);
2197 }
2198
2199 /// Build a new OpenMP 'defaultmap' clause.
2200 ///
2201 /// By default, performs semantic analysis to build the new OpenMP clause.
2202 /// Subclasses may override this routine to provide different behavior.
2203 OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
2204 OpenMPDefaultmapClauseKind Kind,
2205 SourceLocation StartLoc,
2206 SourceLocation LParenLoc,
2207 SourceLocation MLoc,
2208 SourceLocation KindLoc,
2209 SourceLocation EndLoc) {
2210 return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2211 MLoc, KindLoc, EndLoc);
2212 }
2213
2214 /// Build a new OpenMP 'nontemporal' clause.
2215 ///
2216 /// By default, performs semantic analysis to build the new OpenMP clause.
2217 /// Subclasses may override this routine to provide different behavior.
2218 OMPClause *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2219 SourceLocation StartLoc,
2220 SourceLocation LParenLoc,
2221 SourceLocation EndLoc) {
2222 return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2223 EndLoc);
2224 }
2225
2226 /// Build a new OpenMP 'inclusive' clause.
2227 ///
2228 /// By default, performs semantic analysis to build the new OpenMP clause.
2229 /// Subclasses may override this routine to provide different behavior.
2230 OMPClause *RebuildOMPInclusiveClause(ArrayRef<Expr *> VarList,
2231 SourceLocation StartLoc,
2232 SourceLocation LParenLoc,
2233 SourceLocation EndLoc) {
2234 return getSema().ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc,
2235 EndLoc);
2236 }
2237
2238 /// Build a new OpenMP 'exclusive' clause.
2239 ///
2240 /// By default, performs semantic analysis to build the new OpenMP clause.
2241 /// Subclasses may override this routine to provide different behavior.
2242 OMPClause *RebuildOMPExclusiveClause(ArrayRef<Expr *> VarList,
2243 SourceLocation StartLoc,
2244 SourceLocation LParenLoc,
2245 SourceLocation EndLoc) {
2246 return getSema().ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc,
2247 EndLoc);
2248 }
2249
2250 /// Build a new OpenMP 'uses_allocators' clause.
2251 ///
2252 /// By default, performs semantic analysis to build the new OpenMP clause.
2253 /// Subclasses may override this routine to provide different behavior.
2254 OMPClause *RebuildOMPUsesAllocatorsClause(
2255 ArrayRef<Sema::UsesAllocatorsData> Data, SourceLocation StartLoc,
2256 SourceLocation LParenLoc, SourceLocation EndLoc) {
2257 return getSema().ActOnOpenMPUsesAllocatorClause(StartLoc, LParenLoc, EndLoc,
2258 Data);
2259 }
2260
2261 /// Build a new OpenMP 'affinity' clause.
2262 ///
2263 /// By default, performs semantic analysis to build the new OpenMP clause.
2264 /// Subclasses may override this routine to provide different behavior.
2265 OMPClause *RebuildOMPAffinityClause(SourceLocation StartLoc,
2266 SourceLocation LParenLoc,
2267 SourceLocation ColonLoc,
2268 SourceLocation EndLoc, Expr *Modifier,
2269 ArrayRef<Expr *> Locators) {
2270 return getSema().ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc,
2271 EndLoc, Modifier, Locators);
2272 }
2273
2274 /// Build a new OpenMP 'order' clause.
2275 ///
2276 /// By default, performs semantic analysis to build the new OpenMP clause.
2277 /// Subclasses may override this routine to provide different behavior.
2278 OMPClause *RebuildOMPOrderClause(
2279 OpenMPOrderClauseKind Kind, SourceLocation KindKwLoc,
2280 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
2281 OpenMPOrderClauseModifier Modifier, SourceLocation ModifierKwLoc) {
2282 return getSema().ActOnOpenMPOrderClause(Modifier, Kind, StartLoc, LParenLoc,
2283 ModifierKwLoc, KindKwLoc, EndLoc);
2284 }
2285
2286 /// Build a new OpenMP 'init' clause.
2287 ///
2288 /// By default, performs semantic analysis to build the new OpenMP clause.
2289 /// Subclasses may override this routine to provide different behavior.
2290 OMPClause *RebuildOMPInitClause(Expr *InteropVar, OMPInteropInfo &InteropInfo,
2291 SourceLocation StartLoc,
2292 SourceLocation LParenLoc,
2293 SourceLocation VarLoc,
2294 SourceLocation EndLoc) {
2295 return getSema().ActOnOpenMPInitClause(InteropVar, InteropInfo, StartLoc,
2296 LParenLoc, VarLoc, EndLoc);
2297 }
2298
2299 /// Build a new OpenMP 'use' clause.
2300 ///
2301 /// By default, performs semantic analysis to build the new OpenMP clause.
2302 /// Subclasses may override this routine to provide different behavior.
2303 OMPClause *RebuildOMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
2304 SourceLocation LParenLoc,
2305 SourceLocation VarLoc, SourceLocation EndLoc) {
2306 return getSema().ActOnOpenMPUseClause(InteropVar, StartLoc, LParenLoc,
2307 VarLoc, EndLoc);
2308 }
2309
2310 /// Build a new OpenMP 'destroy' clause.
2311 ///
2312 /// By default, performs semantic analysis to build the new OpenMP clause.
2313 /// Subclasses may override this routine to provide different behavior.
2314 OMPClause *RebuildOMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
2315 SourceLocation LParenLoc,
2316 SourceLocation VarLoc,
2317 SourceLocation EndLoc) {
2318 return getSema().ActOnOpenMPDestroyClause(InteropVar, StartLoc, LParenLoc,
2319 VarLoc, EndLoc);
2320 }
2321
2322 /// Build a new OpenMP 'novariants' clause.
2323 ///
2324 /// By default, performs semantic analysis to build the new OpenMP clause.
2325 /// Subclasses may override this routine to provide different behavior.
2326 OMPClause *RebuildOMPNovariantsClause(Expr *Condition,
2327 SourceLocation StartLoc,
2328 SourceLocation LParenLoc,
2329 SourceLocation EndLoc) {
2330 return getSema().ActOnOpenMPNovariantsClause(Condition, StartLoc, LParenLoc,
2331 EndLoc);
2332 }
2333
2334 /// Build a new OpenMP 'nocontext' clause.
2335 ///
2336 /// By default, performs semantic analysis to build the new OpenMP clause.
2337 /// Subclasses may override this routine to provide different behavior.
2338 OMPClause *RebuildOMPNocontextClause(Expr *Condition, SourceLocation StartLoc,
2339 SourceLocation LParenLoc,
2340 SourceLocation EndLoc) {
2341 return getSema().ActOnOpenMPNocontextClause(Condition, StartLoc, LParenLoc,
2342 EndLoc);
2343 }
2344
2345 /// Build a new OpenMP 'filter' clause.
2346 ///
2347 /// By default, performs semantic analysis to build the new OpenMP clause.
2348 /// Subclasses may override this routine to provide different behavior.
2349 OMPClause *RebuildOMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
2350 SourceLocation LParenLoc,
2351 SourceLocation EndLoc) {
2352 return getSema().ActOnOpenMPFilterClause(ThreadID, StartLoc, LParenLoc,
2353 EndLoc);
2354 }
2355
2356 /// Build a new OpenMP 'bind' clause.
2357 ///
2358 /// By default, performs semantic analysis to build the new OpenMP clause.
2359 /// Subclasses may override this routine to provide different behavior.
2360 OMPClause *RebuildOMPBindClause(OpenMPBindClauseKind Kind,
2361 SourceLocation KindLoc,
2362 SourceLocation StartLoc,
2363 SourceLocation LParenLoc,
2364 SourceLocation EndLoc) {
2365 return getSema().ActOnOpenMPBindClause(Kind, KindLoc, StartLoc, LParenLoc,
2366 EndLoc);
2367 }
2368
2369 /// Build a new OpenMP 'ompx_dyn_cgroup_mem' clause.
2370 ///
2371 /// By default, performs semantic analysis to build the new OpenMP clause.
2372 /// Subclasses may override this routine to provide different behavior.
2373 OMPClause *RebuildOMPXDynCGroupMemClause(Expr *Size, SourceLocation StartLoc,
2374 SourceLocation LParenLoc,
2375 SourceLocation EndLoc) {
2376 return getSema().ActOnOpenMPXDynCGroupMemClause(Size, StartLoc, LParenLoc,
2377 EndLoc);
2378 }
2379
2380 /// Build a new OpenMP 'align' clause.
2381 ///
2382 /// By default, performs semantic analysis to build the new OpenMP clause.
2383 /// Subclasses may override this routine to provide different behavior.
2384 OMPClause *RebuildOMPAlignClause(Expr *A, SourceLocation StartLoc,
2385 SourceLocation LParenLoc,
2386 SourceLocation EndLoc) {
2387 return getSema().ActOnOpenMPAlignClause(A, StartLoc, LParenLoc, EndLoc);
2388 }
2389
2390 /// Build a new OpenMP 'at' clause.
2391 ///
2392 /// By default, performs semantic analysis to build the new OpenMP clause.
2393 /// Subclasses may override this routine to provide different behavior.
2394 OMPClause *RebuildOMPAtClause(OpenMPAtClauseKind Kind, SourceLocation KwLoc,
2395 SourceLocation StartLoc,
2396 SourceLocation LParenLoc,
2397 SourceLocation EndLoc) {
2398 return getSema().ActOnOpenMPAtClause(Kind, KwLoc, StartLoc, LParenLoc,
2399 EndLoc);
2400 }
2401
2402 /// Build a new OpenMP 'severity' clause.
2403 ///
2404 /// By default, performs semantic analysis to build the new OpenMP clause.
2405 /// Subclasses may override this routine to provide different behavior.
2406 OMPClause *RebuildOMPSeverityClause(OpenMPSeverityClauseKind Kind,
2407 SourceLocation KwLoc,
2408 SourceLocation StartLoc,
2409 SourceLocation LParenLoc,
2410 SourceLocation EndLoc) {
2411 return getSema().ActOnOpenMPSeverityClause(Kind, KwLoc, StartLoc, LParenLoc,
2412 EndLoc);
2413 }
2414
2415 /// Build a new OpenMP 'message' clause.
2416 ///
2417 /// By default, performs semantic analysis to build the new OpenMP clause.
2418 /// Subclasses may override this routine to provide different behavior.
2419 OMPClause *RebuildOMPMessageClause(Expr *MS, SourceLocation StartLoc,
2420 SourceLocation LParenLoc,
2421 SourceLocation EndLoc) {
2422 return getSema().ActOnOpenMPMessageClause(MS, StartLoc, LParenLoc, EndLoc);
2423 }
2424
2425 /// Rebuild the operand to an Objective-C \@synchronized statement.
2426 ///
2427 /// By default, performs semantic analysis to build the new statement.
2428 /// Subclasses may override this routine to provide different behavior.
2429 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2430 Expr *object) {
2431 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2432 }
2433
2434 /// Build a new Objective-C \@synchronized statement.
2435 ///
2436 /// By default, performs semantic analysis to build the new statement.
2437 /// Subclasses may override this routine to provide different behavior.
2438 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2439 Expr *Object, Stmt *Body) {
2440 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2441 }
2442
2443 /// Build a new Objective-C \@autoreleasepool statement.
2444 ///
2445 /// By default, performs semantic analysis to build the new statement.
2446 /// Subclasses may override this routine to provide different behavior.
2447 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2448 Stmt *Body) {
2449 return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2450 }
2451
2452 /// Build a new Objective-C fast enumeration statement.
2453 ///
2454 /// By default, performs semantic analysis to build the new statement.
2455 /// Subclasses may override this routine to provide different behavior.
2456 StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2457 Stmt *Element,
2458 Expr *Collection,
2459 SourceLocation RParenLoc,
2460 Stmt *Body) {
2461 StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2462 Element,
2463 Collection,
2464 RParenLoc);
2465 if (ForEachStmt.isInvalid())
2466 return StmtError();
2467
2468 return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2469 }
2470
2471 /// Build a new C++ exception declaration.
2472 ///
2473 /// By default, performs semantic analysis to build the new decaration.
2474 /// Subclasses may override this routine to provide different behavior.
2475 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2476 TypeSourceInfo *Declarator,
2477 SourceLocation StartLoc,
2478 SourceLocation IdLoc,
2479 IdentifierInfo *Id) {
2480 VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2481 StartLoc, IdLoc, Id);
2482 if (Var)
2483 getSema().CurContext->addDecl(Var);
2484 return Var;
2485 }
2486
2487 /// Build a new C++ catch statement.
2488 ///
2489 /// By default, performs semantic analysis to build the new statement.
2490 /// Subclasses may override this routine to provide different behavior.
2491 StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2492 VarDecl *ExceptionDecl,
2493 Stmt *Handler) {
2494 return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2495 Handler));
2496 }
2497
2498 /// Build a new C++ try statement.
2499 ///
2500 /// By default, performs semantic analysis to build the new statement.
2501 /// Subclasses may override this routine to provide different behavior.
2502 StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2503 ArrayRef<Stmt *> Handlers) {
2504 return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2505 }
2506
2507 /// Build a new C++0x range-based for statement.
2508 ///
2509 /// By default, performs semantic analysis to build the new statement.
2510 /// Subclasses may override this routine to provide different behavior.
2511 StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2512 SourceLocation CoawaitLoc, Stmt *Init,
2513 SourceLocation ColonLoc, Stmt *Range,
2514 Stmt *Begin, Stmt *End, Expr *Cond,
2515 Expr *Inc, Stmt *LoopVar,
2516 SourceLocation RParenLoc) {
2517 // If we've just learned that the range is actually an Objective-C
2518 // collection, treat this as an Objective-C fast enumeration loop.
2519 if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2520 if (RangeStmt->isSingleDecl()) {
2521 if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2522 if (RangeVar->isInvalidDecl())
2523 return StmtError();
2524
2525 Expr *RangeExpr = RangeVar->getInit();
2526 if (!RangeExpr->isTypeDependent() &&
2527 RangeExpr->getType()->isObjCObjectPointerType()) {
2528 // FIXME: Support init-statements in Objective-C++20 ranged for
2529 // statement.
2530 if (Init) {
2531 return SemaRef.Diag(Init->getBeginLoc(),
2532 diag::err_objc_for_range_init_stmt)
2533 << Init->getSourceRange();
2534 }
2535 return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2536 RangeExpr, RParenLoc);
2537 }
2538 }
2539 }
2540 }
2541
2542 return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2543 Range, Begin, End, Cond, Inc, LoopVar,
2544 RParenLoc, Sema::BFRK_Rebuild);
2545 }
2546
2547 /// Build a new C++0x range-based for statement.
2548 ///
2549 /// By default, performs semantic analysis to build the new statement.
2550 /// Subclasses may override this routine to provide different behavior.
2551 StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2552 bool IsIfExists,
2553 NestedNameSpecifierLoc QualifierLoc,
2554 DeclarationNameInfo NameInfo,
2555 Stmt *Nested) {
2556 return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2557 QualifierLoc, NameInfo, Nested);
2558 }
2559
2560 /// Attach body to a C++0x range-based for statement.
2561 ///
2562 /// By default, performs semantic analysis to finish the new statement.
2563 /// Subclasses may override this routine to provide different behavior.
2564 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2565 return getSema().FinishCXXForRangeStmt(ForRange, Body);
2566 }
2567
2568 StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2569 Stmt *TryBlock, Stmt *Handler) {
2570 return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2571 }
2572
2573 StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2574 Stmt *Block) {
2575 return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2576 }
2577
2578 StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2579 return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2580 }
2581
2582 ExprResult RebuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
2583 SourceLocation LParen,
2584 SourceLocation RParen,
2585 TypeSourceInfo *TSI) {
2586 return getSema().BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
2587 }
2588
2589 /// Build a new predefined 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 RebuildPredefinedExpr(SourceLocation Loc,
2594 PredefinedExpr::IdentKind IK) {
2595 return getSema().BuildPredefinedExpr(Loc, IK);
2596 }
2597
2598 /// Build a new expression that references a declaration.
2599 ///
2600 /// By default, performs semantic analysis to build the new expression.
2601 /// Subclasses may override this routine to provide different behavior.
2602 ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2603 LookupResult &R,
2604 bool RequiresADL) {
2605 return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2606 }
2607
2608
2609 /// Build a new expression that references a declaration.
2610 ///
2611 /// By default, performs semantic analysis to build the new expression.
2612 /// Subclasses may override this routine to provide different behavior.
2613 ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2614 ValueDecl *VD,
2615 const DeclarationNameInfo &NameInfo,
2616 NamedDecl *Found,
2617 TemplateArgumentListInfo *TemplateArgs) {
2618 CXXScopeSpec SS;
2619 SS.Adopt(QualifierLoc);
2620 return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2621 TemplateArgs);
2622 }
2623
2624 /// Build a new expression in parentheses.
2625 ///
2626 /// By default, performs semantic analysis to build the new expression.
2627 /// Subclasses may override this routine to provide different behavior.
2628 ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2629 SourceLocation RParen) {
2630 return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2631 }
2632
2633 /// Build a new pseudo-destructor expression.
2634 ///
2635 /// By default, performs semantic analysis to build the new expression.
2636 /// Subclasses may override this routine to provide different behavior.
2637 ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2638 SourceLocation OperatorLoc,
2639 bool isArrow,
2640 CXXScopeSpec &SS,
2641 TypeSourceInfo *ScopeType,
2642 SourceLocation CCLoc,
2643 SourceLocation TildeLoc,
2644 PseudoDestructorTypeStorage Destroyed);
2645
2646 /// Build a new unary operator expression.
2647 ///
2648 /// By default, performs semantic analysis to build the new expression.
2649 /// Subclasses may override this routine to provide different behavior.
2650 ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2651 UnaryOperatorKind Opc,
2652 Expr *SubExpr) {
2653 return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2654 }
2655
2656 /// Build a new builtin offsetof expression.
2657 ///
2658 /// By default, performs semantic analysis to build the new expression.
2659 /// Subclasses may override this routine to provide different behavior.
2660 ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2661 TypeSourceInfo *Type,
2662 ArrayRef<Sema::OffsetOfComponent> Components,
2663 SourceLocation RParenLoc) {
2664 return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2665 RParenLoc);
2666 }
2667
2668 /// Build a new sizeof, alignof or vec_step expression with a
2669 /// type argument.
2670 ///
2671 /// By default, performs semantic analysis to build the new expression.
2672 /// Subclasses may override this routine to provide different behavior.
2673 ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2674 SourceLocation OpLoc,
2675 UnaryExprOrTypeTrait ExprKind,
2676 SourceRange R) {
2677 return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2678 }
2679
2680 /// Build a new sizeof, alignof or vec step expression with an
2681 /// expression argument.
2682 ///
2683 /// By default, performs semantic analysis to build the new expression.
2684 /// Subclasses may override this routine to provide different behavior.
2685 ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2686 UnaryExprOrTypeTrait ExprKind,
2687 SourceRange R) {
2688 ExprResult Result
2689 = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2690 if (Result.isInvalid())
2691 return ExprError();
2692
2693 return Result;
2694 }
2695
2696 /// Build a new array subscript expression.
2697 ///
2698 /// By default, performs semantic analysis to build the new expression.
2699 /// Subclasses may override this routine to provide different behavior.
2700 ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2701 SourceLocation LBracketLoc,
2702 Expr *RHS,
2703 SourceLocation RBracketLoc) {
2704 return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2705 LBracketLoc, RHS,
2706 RBracketLoc);
2707 }
2708
2709 /// Build a new matrix subscript expression.
2710 ///
2711 /// By default, performs semantic analysis to build the new expression.
2712 /// Subclasses may override this routine to provide different behavior.
2713 ExprResult RebuildMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
2714 Expr *ColumnIdx,
2715 SourceLocation RBracketLoc) {
2716 return getSema().CreateBuiltinMatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
2717 RBracketLoc);
2718 }
2719
2720 /// Build a new array section expression.
2721 ///
2722 /// By default, performs semantic analysis to build the new expression.
2723 /// Subclasses may override this routine to provide different behavior.
2724 ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2725 Expr *LowerBound,
2726 SourceLocation ColonLocFirst,
2727 SourceLocation ColonLocSecond,
2728 Expr *Length, Expr *Stride,
2729 SourceLocation RBracketLoc) {
2730 return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2731 ColonLocFirst, ColonLocSecond,
2732 Length, Stride, RBracketLoc);
2733 }
2734
2735 /// Build a new array shaping expression.
2736 ///
2737 /// By default, performs semantic analysis to build the new expression.
2738 /// Subclasses may override this routine to provide different behavior.
2739 ExprResult RebuildOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
2740 SourceLocation RParenLoc,
2741 ArrayRef<Expr *> Dims,
2742 ArrayRef<SourceRange> BracketsRanges) {
2743 return getSema().ActOnOMPArrayShapingExpr(Base, LParenLoc, RParenLoc, Dims,
2744 BracketsRanges);
2745 }
2746
2747 /// Build a new iterator expression.
2748 ///
2749 /// By default, performs semantic analysis to build the new expression.
2750 /// Subclasses may override this routine to provide different behavior.
2751 ExprResult RebuildOMPIteratorExpr(
2752 SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc,
2753 ArrayRef<Sema::OMPIteratorData> Data) {
2754 return getSema().ActOnOMPIteratorExpr(/*Scope=*/nullptr, IteratorKwLoc,
2755 LLoc, RLoc, Data);
2756 }
2757
2758 /// Build a new call expression.
2759 ///
2760 /// By default, performs semantic analysis to build the new expression.
2761 /// Subclasses may override this routine to provide different behavior.
2762 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2763 MultiExprArg Args,
2764 SourceLocation RParenLoc,
2765 Expr *ExecConfig = nullptr) {
2766 return getSema().ActOnCallExpr(
2767 /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc, ExecConfig);
2768 }
2769
2770 ExprResult RebuildCxxSubscriptExpr(Expr *Callee, SourceLocation LParenLoc,
2771 MultiExprArg Args,
2772 SourceLocation RParenLoc) {
2773 return getSema().ActOnArraySubscriptExpr(
2774 /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc);
2775 }
2776
2777 /// Build a new member access expression.
2778 ///
2779 /// By default, performs semantic analysis to build the new expression.
2780 /// Subclasses may override this routine to provide different behavior.
2781 ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2782 bool isArrow,
2783 NestedNameSpecifierLoc QualifierLoc,
2784 SourceLocation TemplateKWLoc,
2785 const DeclarationNameInfo &MemberNameInfo,
2786 ValueDecl *Member,
2787 NamedDecl *FoundDecl,
2788 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2789 NamedDecl *FirstQualifierInScope) {
2790 ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2791 isArrow);
2792 if (!Member->getDeclName()) {
2793 // We have a reference to an unnamed field. This is always the
2794 // base of an anonymous struct/union member access, i.e. the
2795 // field is always of record type.
2796 assert(Member->getType()->isRecordType() &&(static_cast <bool> (Member->getType()->isRecordType
() && "unnamed member not of record type?") ? void (0
) : __assert_fail ("Member->getType()->isRecordType() && \"unnamed member not of record type?\""
, "clang/lib/Sema/TreeTransform.h", 2797, __extension__ __PRETTY_FUNCTION__
))
2797 "unnamed member not of record type?")(static_cast <bool> (Member->getType()->isRecordType
() && "unnamed member not of record type?") ? void (0
) : __assert_fail ("Member->getType()->isRecordType() && \"unnamed member not of record type?\""
, "clang/lib/Sema/TreeTransform.h", 2797, __extension__ __PRETTY_FUNCTION__
))
;
2798
2799 BaseResult =
2800 getSema().PerformObjectMemberConversion(BaseResult.get(),
2801 QualifierLoc.getNestedNameSpecifier(),
2802 FoundDecl, Member);
2803 if (BaseResult.isInvalid())
2804 return ExprError();
2805 Base = BaseResult.get();
2806
2807 CXXScopeSpec EmptySS;
2808 return getSema().BuildFieldReferenceExpr(
2809 Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2810 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2811 }
2812
2813 CXXScopeSpec SS;
2814 SS.Adopt(QualifierLoc);
2815
2816 Base = BaseResult.get();
2817 QualType BaseType = Base->getType();
2818
2819 if (isArrow && !BaseType->isPointerType())
2820 return ExprError();
2821
2822 // FIXME: this involves duplicating earlier analysis in a lot of
2823 // cases; we should avoid this when possible.
2824 LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2825 R.addDecl(FoundDecl);
2826 R.resolveKind();
2827
2828 if (getSema().isUnevaluatedContext() && Base->isImplicitCXXThis() &&
2829 isa<FieldDecl, IndirectFieldDecl, MSPropertyDecl>(Member)) {
2830 if (auto *ThisClass = cast<CXXThisExpr>(Base)
2831 ->getType()
2832 ->getPointeeType()
2833 ->getAsCXXRecordDecl()) {
2834 auto *Class = cast<CXXRecordDecl>(Member->getDeclContext());
2835 // In unevaluated contexts, an expression supposed to be a member access
2836 // might reference a member in an unrelated class.
2837 if (!ThisClass->Equals(Class) && !ThisClass->isDerivedFrom(Class))
2838 return getSema().BuildDeclRefExpr(Member, Member->getType(),
2839 VK_LValue, Member->getLocation());
2840 }
2841 }
2842
2843 return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2844 SS, TemplateKWLoc,
2845 FirstQualifierInScope,
2846 R, ExplicitTemplateArgs,
2847 /*S*/nullptr);
2848 }
2849
2850 /// Build a new binary operator expression.
2851 ///
2852 /// By default, performs semantic analysis to build the new expression.
2853 /// Subclasses may override this routine to provide different behavior.
2854 ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2855 BinaryOperatorKind Opc,
2856 Expr *LHS, Expr *RHS) {
2857 return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2858 }
2859
2860 /// Build a new rewritten operator expression.
2861 ///
2862 /// By default, performs semantic analysis to build the new expression.
2863 /// Subclasses may override this routine to provide different behavior.
2864 ExprResult RebuildCXXRewrittenBinaryOperator(
2865 SourceLocation OpLoc, BinaryOperatorKind Opcode,
2866 const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2867 return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2868 RHS, /*RequiresADL*/false);
2869 }
2870
2871 /// Build a new conditional operator expression.
2872 ///
2873 /// By default, performs semantic analysis to build the new expression.
2874 /// Subclasses may override this routine to provide different behavior.
2875 ExprResult RebuildConditionalOperator(Expr *Cond,
2876 SourceLocation QuestionLoc,
2877 Expr *LHS,
2878 SourceLocation ColonLoc,
2879 Expr *RHS) {
2880 return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2881 LHS, RHS);
2882 }
2883
2884 /// Build a new C-style cast expression.
2885 ///
2886 /// By default, performs semantic analysis to build the new expression.
2887 /// Subclasses may override this routine to provide different behavior.
2888 ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2889 TypeSourceInfo *TInfo,
2890 SourceLocation RParenLoc,
2891 Expr *SubExpr) {
2892 return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2893 SubExpr);
2894 }
2895
2896 /// Build a new compound literal expression.
2897 ///
2898 /// By default, performs semantic analysis to build the new expression.
2899 /// Subclasses may override this routine to provide different behavior.
2900 ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2901 TypeSourceInfo *TInfo,
2902 SourceLocation RParenLoc,
2903 Expr *Init) {
2904 return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2905 Init);
2906 }
2907
2908 /// Build a new extended vector element access expression.
2909 ///
2910 /// By default, performs semantic analysis to build the new expression.
2911 /// Subclasses may override this routine to provide different behavior.
2912 ExprResult RebuildExtVectorElementExpr(Expr *Base, SourceLocation OpLoc,
2913 bool IsArrow,
2914 SourceLocation AccessorLoc,
2915 IdentifierInfo &Accessor) {
2916
2917 CXXScopeSpec SS;
2918 DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2919 return getSema().BuildMemberReferenceExpr(
2920 Base, Base->getType(), OpLoc, IsArrow, SS, SourceLocation(),
2921 /*FirstQualifierInScope*/ nullptr, NameInfo,
2922 /* TemplateArgs */ nullptr,
2923 /*S*/ nullptr);
2924 }
2925
2926 /// Build a new initializer list expression.
2927 ///
2928 /// By default, performs semantic analysis to build the new expression.
2929 /// Subclasses may override this routine to provide different behavior.
2930 ExprResult RebuildInitList(SourceLocation LBraceLoc,
2931 MultiExprArg Inits,
2932 SourceLocation RBraceLoc) {
2933 return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2934 }
2935
2936 /// Build a new designated initializer expression.
2937 ///
2938 /// By default, performs semantic analysis to build the new expression.
2939 /// Subclasses may override this routine to provide different behavior.
2940 ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2941 MultiExprArg ArrayExprs,
2942 SourceLocation EqualOrColonLoc,
2943 bool GNUSyntax,
2944 Expr *Init) {
2945 ExprResult Result
2946 = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2947 Init);
2948 if (Result.isInvalid())
2949 return ExprError();
2950
2951 return Result;
2952 }
2953
2954 /// Build a new value-initialized expression.
2955 ///
2956 /// By default, builds the implicit value initialization without performing
2957 /// any semantic analysis. Subclasses may override this routine to provide
2958 /// different behavior.
2959 ExprResult RebuildImplicitValueInitExpr(QualType T) {
2960 return new (SemaRef.Context) ImplicitValueInitExpr(T);
2961 }
2962
2963 /// Build a new \c va_arg expression.
2964 ///
2965 /// By default, performs semantic analysis to build the new expression.
2966 /// Subclasses may override this routine to provide different behavior.
2967 ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2968 Expr *SubExpr, TypeSourceInfo *TInfo,
2969 SourceLocation RParenLoc) {
2970 return getSema().BuildVAArgExpr(BuiltinLoc,
2971 SubExpr, TInfo,
2972 RParenLoc);
2973 }
2974
2975 /// Build a new expression list in parentheses.
2976 ///
2977 /// By default, performs semantic analysis to build the new expression.
2978 /// Subclasses may override this routine to provide different behavior.
2979 ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2980 MultiExprArg SubExprs,
2981 SourceLocation RParenLoc) {
2982 return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2983 }
2984
2985 /// Build a new address-of-label expression.
2986 ///
2987 /// By default, performs semantic analysis, using the name of the label
2988 /// rather than attempting to map the label statement itself.
2989 /// Subclasses may override this routine to provide different behavior.
2990 ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2991 SourceLocation LabelLoc, LabelDecl *Label) {
2992 return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2993 }
2994
2995 /// Build a new GNU statement expression.
2996 ///
2997 /// By default, performs semantic analysis to build the new expression.
2998 /// Subclasses may override this routine to provide different behavior.
2999 ExprResult RebuildStmtExpr(SourceLocation LParenLoc, Stmt *SubStmt,
3000 SourceLocation RParenLoc, unsigned TemplateDepth) {
3001 return getSema().BuildStmtExpr(LParenLoc, SubStmt, RParenLoc,
3002 TemplateDepth);
3003 }
3004
3005 /// Build a new __builtin_choose_expr expression.
3006 ///
3007 /// By default, performs semantic analysis to build the new expression.
3008 /// Subclasses may override this routine to provide different behavior.
3009 ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
3010 Expr *Cond, Expr *LHS, Expr *RHS,
3011 SourceLocation RParenLoc) {
3012 return SemaRef.ActOnChooseExpr(BuiltinLoc,
3013 Cond, LHS, RHS,
3014 RParenLoc);
3015 }
3016
3017 /// Build a new generic selection 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 RebuildGenericSelectionExpr(SourceLocation KeyLoc,
3022 SourceLocation DefaultLoc,
3023 SourceLocation RParenLoc,
3024 Expr *ControllingExpr,
3025 ArrayRef<TypeSourceInfo *> Types,
3026 ArrayRef<Expr *> Exprs) {
3027 return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
3028 ControllingExpr, Types, Exprs);
3029 }
3030
3031 /// Build a new overloaded operator call expression.
3032 ///
3033 /// By default, performs semantic analysis to build the new expression.
3034 /// The semantic analysis provides the behavior of template instantiation,
3035 /// copying with transformations that turn what looks like an overloaded
3036 /// operator call into a use of a builtin operator, performing
3037 /// argument-dependent lookup, etc. Subclasses may override this routine to
3038 /// provide different behavior.
3039 ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
3040 SourceLocation OpLoc,
3041 Expr *Callee,
3042 Expr *First,
3043 Expr *Second);
3044
3045 /// Build a new C++ "named" cast expression, such as static_cast or
3046 /// reinterpret_cast.
3047 ///
3048 /// By default, this routine dispatches to one of the more-specific routines
3049 /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
3050 /// Subclasses may override this routine to provide different behavior.
3051 ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
3052 Stmt::StmtClass Class,
3053 SourceLocation LAngleLoc,
3054 TypeSourceInfo *TInfo,
3055 SourceLocation RAngleLoc,
3056 SourceLocation LParenLoc,
3057 Expr *SubExpr,
3058 SourceLocation RParenLoc) {
3059 switch (Class) {
3060 case Stmt::CXXStaticCastExprClass:
3061 return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
3062 RAngleLoc, LParenLoc,
3063 SubExpr, RParenLoc);
3064
3065 case Stmt::CXXDynamicCastExprClass:
3066 return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
3067 RAngleLoc, LParenLoc,
3068 SubExpr, RParenLoc);
3069
3070 case Stmt::CXXReinterpretCastExprClass:
3071 return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
3072 RAngleLoc, LParenLoc,
3073 SubExpr,
3074 RParenLoc);
3075
3076 case Stmt::CXXConstCastExprClass:
3077 return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
3078 RAngleLoc, LParenLoc,
3079 SubExpr, RParenLoc);
3080
3081 case Stmt::CXXAddrspaceCastExprClass:
3082 return getDerived().RebuildCXXAddrspaceCastExpr(
3083 OpLoc, LAngleLoc, TInfo, RAngleLoc, LParenLoc, SubExpr, RParenLoc);
3084
3085 default:
3086 llvm_unreachable("Invalid C++ named cast")::llvm::llvm_unreachable_internal("Invalid C++ named cast", "clang/lib/Sema/TreeTransform.h"
, 3086)
;
3087 }
3088 }
3089
3090 /// Build a new C++ static_cast expression.
3091 ///
3092 /// By default, performs semantic analysis to build the new expression.
3093 /// Subclasses may override this routine to provide different behavior.
3094 ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
3095 SourceLocation LAngleLoc,
3096 TypeSourceInfo *TInfo,
3097 SourceLocation RAngleLoc,
3098 SourceLocation LParenLoc,
3099 Expr *SubExpr,
3100 SourceLocation RParenLoc) {
3101 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
3102 TInfo, SubExpr,
3103 SourceRange(LAngleLoc, RAngleLoc),
3104 SourceRange(LParenLoc, RParenLoc));
3105 }
3106
3107 /// Build a new C++ dynamic_cast expression.
3108 ///
3109 /// By default, performs semantic analysis to build the new expression.
3110 /// Subclasses may override this routine to provide different behavior.
3111 ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
3112 SourceLocation LAngleLoc,
3113 TypeSourceInfo *TInfo,
3114 SourceLocation RAngleLoc,
3115 SourceLocation LParenLoc,
3116 Expr *SubExpr,
3117 SourceLocation RParenLoc) {
3118 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
3119 TInfo, SubExpr,
3120 SourceRange(LAngleLoc, RAngleLoc),
3121 SourceRange(LParenLoc, RParenLoc));
3122 }
3123
3124 /// Build a new C++ reinterpret_cast expression.
3125 ///
3126 /// By default, performs semantic analysis to build the new expression.
3127 /// Subclasses may override this routine to provide different behavior.
3128 ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
3129 SourceLocation LAngleLoc,
3130 TypeSourceInfo *TInfo,
3131 SourceLocation RAngleLoc,
3132 SourceLocation LParenLoc,
3133 Expr *SubExpr,
3134 SourceLocation RParenLoc) {
3135 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
3136 TInfo, SubExpr,
3137 SourceRange(LAngleLoc, RAngleLoc),
3138 SourceRange(LParenLoc, RParenLoc));
3139 }
3140
3141 /// Build a new C++ const_cast expression.
3142 ///
3143 /// By default, performs semantic analysis to build the new expression.
3144 /// Subclasses may override this routine to provide different behavior.
3145 ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
3146 SourceLocation LAngleLoc,
3147 TypeSourceInfo *TInfo,
3148 SourceLocation RAngleLoc,
3149 SourceLocation LParenLoc,
3150 Expr *SubExpr,
3151 SourceLocation RParenLoc) {
3152 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
3153 TInfo, SubExpr,
3154 SourceRange(LAngleLoc, RAngleLoc),
3155 SourceRange(LParenLoc, RParenLoc));
3156 }
3157
3158 ExprResult
3159 RebuildCXXAddrspaceCastExpr(SourceLocation OpLoc, SourceLocation LAngleLoc,
3160 TypeSourceInfo *TInfo, SourceLocation RAngleLoc,
3161 SourceLocation LParenLoc, Expr *SubExpr,
3162 SourceLocation RParenLoc) {
3163 return getSema().BuildCXXNamedCast(
3164 OpLoc, tok::kw_addrspace_cast, TInfo, SubExpr,
3165 SourceRange(LAngleLoc, RAngleLoc), SourceRange(LParenLoc, RParenLoc));
3166 }
3167
3168 /// Build a new C++ functional-style cast expression.
3169 ///
3170 /// By default, performs semantic analysis to build the new expression.
3171 /// Subclasses may override this routine to provide different behavior.
3172 ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
3173 SourceLocation LParenLoc,
3174 Expr *Sub,
3175 SourceLocation RParenLoc,
3176 bool ListInitialization) {
3177 // If Sub is a ParenListExpr, then Sub is the syntatic form of a
3178 // CXXParenListInitExpr. Pass its expanded arguments so that the
3179 // CXXParenListInitExpr can be rebuilt.
3180 if (auto *PLE = dyn_cast<ParenListExpr>(Sub))
3181 return getSema().BuildCXXTypeConstructExpr(
3182 TInfo, LParenLoc, MultiExprArg(PLE->getExprs(), PLE->getNumExprs()),
3183 RParenLoc, ListInitialization);
3184 return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
3185 MultiExprArg(&Sub, 1), RParenLoc,
3186 ListInitialization);
3187 }
3188
3189 /// Build a new C++ __builtin_bit_cast expression.
3190 ///
3191 /// By default, performs semantic analysis to build the new expression.
3192 /// Subclasses may override this routine to provide different behavior.
3193 ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
3194 TypeSourceInfo *TSI, Expr *Sub,
3195 SourceLocation RParenLoc) {
3196 return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
3197 }
3198
3199 /// Build a new C++ typeid(type) expression.
3200 ///
3201 /// By default, performs semantic analysis to build the new expression.
3202 /// Subclasses may override this routine to provide different behavior.
3203 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3204 SourceLocation TypeidLoc,
3205 TypeSourceInfo *Operand,
3206 SourceLocation RParenLoc) {
3207 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3208 RParenLoc);
3209 }
3210
3211
3212 /// Build a new C++ typeid(expr) expression.
3213 ///
3214 /// By default, performs semantic analysis to build the new expression.
3215 /// Subclasses may override this routine to provide different behavior.
3216 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3217 SourceLocation TypeidLoc,
3218 Expr *Operand,
3219 SourceLocation RParenLoc) {
3220 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3221 RParenLoc);
3222 }
3223
3224 /// Build a new C++ __uuidof(type) expression.
3225 ///
3226 /// By default, performs semantic analysis to build the new expression.
3227 /// Subclasses may override this routine to provide different behavior.
3228 ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3229 TypeSourceInfo *Operand,
3230 SourceLocation RParenLoc) {
3231 return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3232 }
3233
3234 /// Build a new C++ __uuidof(expr) expression.
3235 ///
3236 /// By default, performs semantic analysis to build the new expression.
3237 /// Subclasses may override this routine to provide different behavior.
3238 ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3239 Expr *Operand, SourceLocation RParenLoc) {
3240 return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3241 }
3242
3243 /// Build a new C++ "this" expression.
3244 ///
3245 /// By default, builds a new "this" expression without performing any
3246 /// semantic analysis. Subclasses may override this routine to provide
3247 /// different behavior.
3248 ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
3249 QualType ThisType,
3250 bool isImplicit) {
3251 return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
3252 }
3253
3254 /// Build a new C++ throw expression.
3255 ///
3256 /// By default, performs semantic analysis to build the new expression.
3257 /// Subclasses may override this routine to provide different behavior.
3258 ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
3259 bool IsThrownVariableInScope) {
3260 return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
3261 }
3262
3263 /// Build a new C++ default-argument expression.
3264 ///
3265 /// By default, builds a new default-argument expression, which does not
3266 /// require any semantic analysis. Subclasses may override this routine to
3267 /// provide different behavior.
3268 ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param,
3269 Expr *RewrittenExpr) {
3270 return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
3271 RewrittenExpr, getSema().CurContext);
3272 }
3273
3274 /// Build a new C++11 default-initialization expression.
3275 ///
3276 /// By default, builds a new default field initialization expression, which
3277 /// does not require any semantic analysis. Subclasses may override this
3278 /// routine to provide different behavior.
3279 ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
3280 FieldDecl *Field) {
3281 return getSema().BuildCXXDefaultInitExpr(Loc, Field);
3282 }
3283
3284 /// Build a new C++ zero-initialization expression.
3285 ///
3286 /// By default, performs semantic analysis to build the new expression.
3287 /// Subclasses may override this routine to provide different behavior.
3288 ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
3289 SourceLocation LParenLoc,
3290 SourceLocation RParenLoc) {
3291 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, std::nullopt,
3292 RParenLoc,
3293 /*ListInitialization=*/false);
3294 }
3295
3296 /// Build a new C++ "new" expression.
3297 ///
3298 /// By default, performs semantic analysis to build the new expression.
3299 /// Subclasses may override this routine to provide different behavior.
3300 ExprResult RebuildCXXNewExpr(SourceLocation StartLoc, bool UseGlobal,
3301 SourceLocation PlacementLParen,
3302 MultiExprArg PlacementArgs,
3303 SourceLocation PlacementRParen,
3304 SourceRange TypeIdParens, QualType AllocatedType,
3305 TypeSourceInfo *AllocatedTypeInfo,
3306 std::optional<Expr *> ArraySize,
3307 SourceRange DirectInitRange, Expr *Initializer) {
3308 return getSema().BuildCXXNew(StartLoc, UseGlobal,
3309 PlacementLParen,
3310 PlacementArgs,
3311 PlacementRParen,
3312 TypeIdParens,
3313 AllocatedType,
3314 AllocatedTypeInfo,
3315 ArraySize,
3316 DirectInitRange,
3317 Initializer);
3318 }
3319
3320 /// Build a new C++ "delete" expression.
3321 ///
3322 /// By default, performs semantic analysis to build the new expression.
3323 /// Subclasses may override this routine to provide different behavior.
3324 ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
3325 bool IsGlobalDelete,
3326 bool IsArrayForm,
3327 Expr *Operand) {
3328 return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
3329 Operand);
3330 }
3331
3332 /// Build a new type trait expression.
3333 ///
3334 /// By default, performs semantic analysis to build the new expression.
3335 /// Subclasses may override this routine to provide different behavior.
3336 ExprResult RebuildTypeTrait(TypeTrait Trait,
3337 SourceLocation StartLoc,
3338 ArrayRef<TypeSourceInfo *> Args,
3339 SourceLocation RParenLoc) {
3340 return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
3341 }
3342
3343 /// Build a new array type trait expression.
3344 ///
3345 /// By default, performs semantic analysis to build the new expression.
3346 /// Subclasses may override this routine to provide different behavior.
3347 ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
3348 SourceLocation StartLoc,
3349 TypeSourceInfo *TSInfo,
3350 Expr *DimExpr,
3351 SourceLocation RParenLoc) {
3352 return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
3353 }
3354
3355 /// Build a new expression trait expression.
3356 ///
3357 /// By default, performs semantic analysis to build the new expression.
3358 /// Subclasses may override this routine to provide different behavior.
3359 ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
3360 SourceLocation StartLoc,
3361 Expr *Queried,
3362 SourceLocation RParenLoc) {
3363 return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
3364 }
3365
3366 /// Build a new (previously unresolved) declaration reference
3367 /// expression.
3368 ///
3369 /// By default, performs semantic analysis to build the new expression.
3370 /// Subclasses may override this routine to provide different behavior.
3371 ExprResult RebuildDependentScopeDeclRefExpr(
3372 NestedNameSpecifierLoc QualifierLoc,
3373 SourceLocation TemplateKWLoc,
3374 const DeclarationNameInfo &NameInfo,
3375 const TemplateArgumentListInfo *TemplateArgs,
3376 bool IsAddressOfOperand,
3377 TypeSourceInfo **RecoveryTSI) {
3378 CXXScopeSpec SS;
3379 SS.Adopt(QualifierLoc);
3380
3381 if (TemplateArgs || TemplateKWLoc.isValid())
3382 return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
3383 TemplateArgs);
3384
3385 return getSema().BuildQualifiedDeclarationNameExpr(
3386 SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
3387 }
3388
3389 /// Build a new template-id expression.
3390 ///
3391 /// By default, performs semantic analysis to build the new expression.
3392 /// Subclasses may override this routine to provide different behavior.
3393 ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
3394 SourceLocation TemplateKWLoc,
3395 LookupResult &R,
3396 bool RequiresADL,
3397 const TemplateArgumentListInfo *TemplateArgs) {
3398 return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
3399 TemplateArgs);
3400 }
3401
3402 /// Build a new object-construction expression.
3403 ///
3404 /// By default, performs semantic analysis to build the new expression.
3405 /// Subclasses may override this routine to provide different behavior.
3406 ExprResult RebuildCXXConstructExpr(QualType T,
3407 SourceLocation Loc,
3408 CXXConstructorDecl *Constructor,
3409 bool IsElidable,
3410 MultiExprArg Args,
3411 bool HadMultipleCandidates,
3412 bool ListInitialization,
3413 bool StdInitListInitialization,
3414 bool RequiresZeroInit,
3415 CXXConstructExpr::ConstructionKind ConstructKind,
3416 SourceRange ParenRange) {
3417 // Reconstruct the constructor we originally found, which might be
3418 // different if this is a call to an inherited constructor.
3419 CXXConstructorDecl *FoundCtor = Constructor;
3420 if (Constructor->isInheritingConstructor())
3421 FoundCtor = Constructor->getInheritedConstructor().getConstructor();
3422
3423 SmallVector<Expr *, 8> ConvertedArgs;
3424 if (getSema().CompleteConstructorCall(FoundCtor, T, Args, Loc,
3425 ConvertedArgs))
3426 return ExprError();
3427
3428 return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
3429 IsElidable,
3430 ConvertedArgs,
3431 HadMultipleCandidates,
3432 ListInitialization,
3433 StdInitListInitialization,
3434 RequiresZeroInit, ConstructKind,
3435 ParenRange);
3436 }
3437
3438 /// Build a new implicit construction via inherited constructor
3439 /// expression.
3440 ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
3441 CXXConstructorDecl *Constructor,
3442 bool ConstructsVBase,
3443 bool InheritedFromVBase) {
3444 return new (getSema().Context) CXXInheritedCtorInitExpr(
3445 Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
3446 }
3447
3448 /// Build a new object-construction expression.
3449 ///
3450 /// By default, performs semantic analysis to build the new expression.
3451 /// Subclasses may override this routine to provide different behavior.
3452 ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
3453 SourceLocation LParenOrBraceLoc,
3454 MultiExprArg Args,
3455 SourceLocation RParenOrBraceLoc,
3456 bool ListInitialization) {
3457 return getSema().BuildCXXTypeConstructExpr(
3458 TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
3459 }
3460
3461 /// Build a new object-construction expression.
3462 ///
3463 /// By default, performs semantic analysis to build the new expression.
3464 /// Subclasses may override this routine to provide different behavior.
3465 ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
3466 SourceLocation LParenLoc,
3467 MultiExprArg Args,
3468 SourceLocation RParenLoc,
3469 bool ListInitialization) {
3470 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
3471 RParenLoc, ListInitialization);
3472 }
3473
3474 /// Build a new member reference expression.
3475 ///
3476 /// By default, performs semantic analysis to build the new expression.
3477 /// Subclasses may override this routine to provide different behavior.
3478 ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
3479 QualType BaseType,
3480 bool IsArrow,
3481 SourceLocation OperatorLoc,
3482 NestedNameSpecifierLoc QualifierLoc,
3483 SourceLocation TemplateKWLoc,
3484 NamedDecl *FirstQualifierInScope,
3485 const DeclarationNameInfo &MemberNameInfo,
3486 const TemplateArgumentListInfo *TemplateArgs) {
3487 CXXScopeSpec SS;
3488 SS.Adopt(QualifierLoc);
3489
3490 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3491 OperatorLoc, IsArrow,
3492 SS, TemplateKWLoc,
3493 FirstQualifierInScope,
3494 MemberNameInfo,
3495 TemplateArgs, /*S*/nullptr);
3496 }
3497
3498 /// Build a new member reference expression.
3499 ///
3500 /// By default, performs semantic analysis to build the new expression.
3501 /// Subclasses may override this routine to provide different behavior.
3502 ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
3503 SourceLocation OperatorLoc,
3504 bool IsArrow,
3505 NestedNameSpecifierLoc QualifierLoc,
3506 SourceLocation TemplateKWLoc,
3507 NamedDecl *FirstQualifierInScope,
3508 LookupResult &R,
3509 const TemplateArgumentListInfo *TemplateArgs) {
3510 CXXScopeSpec SS;
3511 SS.Adopt(QualifierLoc);
3512
3513 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3514 OperatorLoc, IsArrow,
3515 SS, TemplateKWLoc,
3516 FirstQualifierInScope,
3517 R, TemplateArgs, /*S*/nullptr);
3518 }
3519
3520 /// Build a new noexcept expression.
3521 ///
3522 /// By default, performs semantic analysis to build the new expression.
3523 /// Subclasses may override this routine to provide different behavior.
3524 ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3525 return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3526 }
3527
3528 /// Build a new expression to compute the length of a parameter pack.
3529 ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack,
3530 SourceLocation PackLoc,
3531 SourceLocation RParenLoc,
3532 std::optional<unsigned> Length,
3533 ArrayRef<TemplateArgument> PartialArgs) {
3534 return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3535 RParenLoc, Length, PartialArgs);
3536 }
3537
3538 /// Build a new expression representing a call to a source location
3539 /// builtin.
3540 ///
3541 /// By default, performs semantic analysis to build the new expression.
3542 /// Subclasses may override this routine to provide different behavior.
3543 ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3544 QualType ResultTy, SourceLocation BuiltinLoc,
3545 SourceLocation RPLoc,
3546 DeclContext *ParentContext) {
3547 return getSema().BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc,
3548 ParentContext);
3549 }
3550
3551 /// Build a new Objective-C boxed expression.
3552 ///
3553 /// By default, performs semantic analysis to build the new expression.
3554 /// Subclasses may override this routine to provide different behavior.
3555 ExprResult RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3556 SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo,
3557 NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3558 TemplateArgumentListInfo *TALI) {
3559 CXXScopeSpec SS;
3560 SS.Adopt(NNS);
3561 ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3562 ConceptNameInfo,
3563 FoundDecl,
3564 NamedConcept, TALI);
3565 if (Result.isInvalid())
3566 return ExprError();
3567 return Result;
3568 }
3569
3570 /// \brief Build a new requires expression.
3571 ///
3572 /// By default, performs semantic analysis to build the new expression.
3573 /// Subclasses may override this routine to provide different behavior.
3574 ExprResult RebuildRequiresExpr(SourceLocation RequiresKWLoc,
3575 RequiresExprBodyDecl *Body,
3576 ArrayRef<ParmVarDecl *> LocalParameters,
3577 ArrayRef<concepts::Requirement *> Requirements,
3578 SourceLocation ClosingBraceLoc) {
3579 return RequiresExpr::Create(SemaRef.Context, RequiresKWLoc, Body,
3580 LocalParameters, Requirements, ClosingBraceLoc);
3581 }
3582
3583 concepts::TypeRequirement *
3584 RebuildTypeRequirement(
3585 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3586 return SemaRef.BuildTypeRequirement(SubstDiag);
3587 }
3588
3589 concepts::TypeRequirement *RebuildTypeRequirement(TypeSourceInfo *T) {
3590 return SemaRef.BuildTypeRequirement(T);
3591 }
3592
3593 concepts::ExprRequirement *
3594 RebuildExprRequirement(
3595 concepts::Requirement::SubstitutionDiagnostic *SubstDiag, bool IsSimple,
3596 SourceLocation NoexceptLoc,
3597 concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3598 return SemaRef.BuildExprRequirement(SubstDiag, IsSimple, NoexceptLoc,
3599 std::move(Ret));
3600 }
3601
3602 concepts::ExprRequirement *
3603 RebuildExprRequirement(Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
3604 concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3605 return SemaRef.BuildExprRequirement(E, IsSimple, NoexceptLoc,
3606 std::move(Ret));
3607 }
3608
3609 concepts::NestedRequirement *
3610 RebuildNestedRequirement(StringRef InvalidConstraintEntity,
3611 const ASTConstraintSatisfaction &Satisfaction) {
3612 return SemaRef.BuildNestedRequirement(InvalidConstraintEntity,
3613 Satisfaction);
3614 }
3615
3616 concepts::NestedRequirement *RebuildNestedRequirement(Expr *Constraint) {
3617 return SemaRef.BuildNestedRequirement(Constraint);
3618 }
3619
3620 /// \brief Build a new Objective-C boxed expression.
3621 ///
3622 /// By default, performs semantic analysis to build the new expression.
3623 /// Subclasses may override this routine to provide different behavior.
3624 ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3625 return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3626 }
3627
3628 /// Build a new Objective-C array literal.
3629 ///
3630 /// By default, performs semantic analysis to build the new expression.
3631 /// Subclasses may override this routine to provide different behavior.
3632 ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3633 Expr **Elements, unsigned NumElements) {
3634 return getSema().BuildObjCArrayLiteral(Range,
3635 MultiExprArg(Elements, NumElements));
3636 }
3637
3638 ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3639 Expr *Base, Expr *Key,
3640 ObjCMethodDecl *getterMethod,
3641 ObjCMethodDecl *setterMethod) {
3642 return getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3643 getterMethod, setterMethod);
3644 }
3645
3646 /// Build a new Objective-C dictionary literal.
3647 ///
3648 /// By default, performs semantic analysis to build the new expression.
3649 /// Subclasses may override this routine to provide different behavior.
3650 ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3651 MutableArrayRef<ObjCDictionaryElement> Elements) {
3652 return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3653 }
3654
3655 /// Build a new Objective-C \@encode expression.
3656 ///
3657 /// By default, performs semantic analysis to build the new expression.
3658 /// Subclasses may override this routine to provide different behavior.
3659 ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3660 TypeSourceInfo *EncodeTypeInfo,
3661 SourceLocation RParenLoc) {
3662 return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3663 }
3664
3665 /// Build a new Objective-C class message.
3666 ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3667 Selector Sel,
3668 ArrayRef<SourceLocation> SelectorLocs,
3669 ObjCMethodDecl *Method,
3670 SourceLocation LBracLoc,
3671 MultiExprArg Args,
3672 SourceLocation RBracLoc) {
3673 return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3674 ReceiverTypeInfo->getType(),
3675 /*SuperLoc=*/SourceLocation(),
3676 Sel, Method, LBracLoc, SelectorLocs,
3677 RBracLoc, Args);
3678 }
3679
3680 /// Build a new Objective-C instance message.
3681 ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3682 Selector Sel,
3683 ArrayRef<SourceLocation> SelectorLocs,
3684 ObjCMethodDecl *Method,
3685 SourceLocation LBracLoc,
3686 MultiExprArg Args,
3687 SourceLocation RBracLoc) {
3688 return SemaRef.BuildInstanceMessage(Receiver,
3689 Receiver->getType(),
3690 /*SuperLoc=*/SourceLocation(),
3691 Sel, Method, LBracLoc, SelectorLocs,
3692 RBracLoc, Args);
3693 }
3694
3695 /// Build a new Objective-C instance/class message to 'super'.
3696 ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3697 Selector Sel,
3698 ArrayRef<SourceLocation> SelectorLocs,
3699 QualType SuperType,
3700 ObjCMethodDecl *Method,
3701 SourceLocation LBracLoc,
3702 MultiExprArg Args,
3703 SourceLocation RBracLoc) {
3704 return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3705 SuperType,
3706 SuperLoc,
3707 Sel, Method, LBracLoc, SelectorLocs,
3708 RBracLoc, Args)
3709 : SemaRef.BuildClassMessage(nullptr,
3710 SuperType,
3711 SuperLoc,
3712 Sel, Method, LBracLoc, SelectorLocs,
3713 RBracLoc, Args);
3714
3715
3716 }
3717
3718 /// Build a new Objective-C ivar reference expression.
3719 ///
3720 /// By default, performs semantic analysis to build the new expression.
3721 /// Subclasses may override this routine to provide different behavior.
3722 ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3723 SourceLocation IvarLoc,
3724 bool IsArrow, bool IsFreeIvar) {
3725 CXXScopeSpec SS;
3726 DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3727 ExprResult Result = getSema().BuildMemberReferenceExpr(
3728 BaseArg, BaseArg->getType(),
3729 /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3730 /*FirstQualifierInScope=*/nullptr, NameInfo,
3731 /*TemplateArgs=*/nullptr,
3732 /*S=*/nullptr);
3733 if (IsFreeIvar && Result.isUsable())
3734 cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3735 return Result;
3736 }
3737
3738 /// Build a new Objective-C property reference expression.
3739 ///
3740 /// By default, performs semantic analysis to build the new expression.
3741 /// Subclasses may override this routine to provide different behavior.
3742 ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3743 ObjCPropertyDecl *Property,
3744 SourceLocation PropertyLoc) {
3745 CXXScopeSpec SS;
3746 DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3747 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3748 /*FIXME:*/PropertyLoc,
3749 /*IsArrow=*/false,
3750 SS, SourceLocation(),
3751 /*FirstQualifierInScope=*/nullptr,
3752 NameInfo,
3753 /*TemplateArgs=*/nullptr,
3754 /*S=*/nullptr);
3755 }
3756
3757 /// Build a new Objective-C property reference expression.
3758 ///
3759 /// By default, performs semantic analysis to build the new expression.
3760 /// Subclasses may override this routine to provide different behavior.
3761 ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3762 ObjCMethodDecl *Getter,
3763 ObjCMethodDecl *Setter,
3764 SourceLocation PropertyLoc) {
3765 // Since these expressions can only be value-dependent, we do not
3766 // need to perform semantic analysis again.
3767 return Owned(
3768 new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3769 VK_LValue, OK_ObjCProperty,
3770 PropertyLoc, Base));
3771 }
3772
3773 /// Build a new Objective-C "isa" expression.
3774 ///
3775 /// By default, performs semantic analysis to build the new expression.
3776 /// Subclasses may override this routine to provide different behavior.
3777 ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3778 SourceLocation OpLoc, bool IsArrow) {
3779 CXXScopeSpec SS;
3780 DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3781 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3782 OpLoc, IsArrow,
3783 SS, SourceLocation(),
3784 /*FirstQualifierInScope=*/nullptr,
3785 NameInfo,
3786 /*TemplateArgs=*/nullptr,
3787 /*S=*/nullptr);
3788 }
3789
3790 /// Build a new shuffle vector expression.
3791 ///
3792 /// By default, performs semantic analysis to build the new expression.
3793 /// Subclasses may override this routine to provide different behavior.
3794 ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3795 MultiExprArg SubExprs,
3796 SourceLocation RParenLoc) {
3797 // Find the declaration for __builtin_shufflevector
3798 const IdentifierInfo &Name
3799 = SemaRef.Context.Idents.get("__builtin_shufflevector");
3800 TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3801 DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3802 assert(!Lookup.empty() && "No __builtin_shufflevector?")(static_cast <bool> (!Lookup.empty() && "No __builtin_shufflevector?"
) ? void (0) : __assert_fail ("!Lookup.empty() && \"No __builtin_shufflevector?\""
, "clang/lib/Sema/TreeTransform.h", 3802, __extension__ __PRETTY_FUNCTION__
))
;
3803
3804 // Build a reference to the __builtin_shufflevector builtin
3805 FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3806 Expr *Callee = new (SemaRef.Context)
3807 DeclRefExpr(SemaRef.Context, Builtin, false,
3808 SemaRef.Context.BuiltinFnTy, VK_PRValue, BuiltinLoc);
3809 QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3810 Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3811 CK_BuiltinFnToFnPtr).get();
3812
3813 // Build the CallExpr
3814 ExprResult TheCall = CallExpr::Create(
3815 SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3816 Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc,
3817 FPOptionsOverride());
3818
3819 // Type-check the __builtin_shufflevector expression.
3820 return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3821 }
3822
3823 /// Build a new convert vector expression.
3824 ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3825 Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3826 SourceLocation RParenLoc) {
3827 return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3828 BuiltinLoc, RParenLoc);
3829 }
3830
3831 /// Build a new template argument pack expansion.
3832 ///
3833 /// By default, performs semantic analysis to build a new pack expansion
3834 /// for a template argument. Subclasses may override this routine to provide
3835 /// different behavior.
3836 TemplateArgumentLoc
3837 RebuildPackExpansion(TemplateArgumentLoc Pattern, SourceLocation EllipsisLoc,
3838 std::optional<unsigned> NumExpansions) {
3839 switch (Pattern.getArgument().getKind()) {
3840 case TemplateArgument::Expression: {
3841 ExprResult Result
3842 = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3843 EllipsisLoc, NumExpansions);
3844 if (Result.isInvalid())
3845 return TemplateArgumentLoc();
3846
3847 return TemplateArgumentLoc(Result.get(), Result.get());
3848 }
3849
3850 case TemplateArgument::Template:
3851 return TemplateArgumentLoc(
3852 SemaRef.Context,
3853 TemplateArgument(Pattern.getArgument().getAsTemplate(),
3854 NumExpansions),
3855 Pattern.getTemplateQualifierLoc(), Pattern.getTemplateNameLoc(),
3856 EllipsisLoc);
3857
3858 case TemplateArgument::Null:
3859 case TemplateArgument::Integral:
3860 case TemplateArgument::Declaration:
3861 case TemplateArgument::Pack:
3862 case TemplateArgument::TemplateExpansion:
3863 case TemplateArgument::NullPtr:
3864 llvm_unreachable("Pack expansion pattern has no parameter packs")::llvm::llvm_unreachable_internal("Pack expansion pattern has no parameter packs"
, "clang/lib/Sema/TreeTransform.h", 3864)
;
3865
3866 case TemplateArgument::Type:
3867 if (TypeSourceInfo *Expansion
3868 = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3869 EllipsisLoc,
3870 NumExpansions))
3871 return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3872 Expansion);
3873 break;
3874 }
3875
3876 return TemplateArgumentLoc();
3877 }
3878
3879 /// Build a new expression pack expansion.
3880 ///
3881 /// By default, performs semantic analysis to build a new pack expansion
3882 /// for an expression. Subclasses may override this routine to provide
3883 /// different behavior.
3884 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3885 std::optional<unsigned> NumExpansions) {
3886 return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3887 }
3888
3889 /// Build a new C++1z fold-expression.
3890 ///
3891 /// By default, performs semantic analysis in order to build a new fold
3892 /// expression.
3893 ExprResult RebuildCXXFoldExpr(UnresolvedLookupExpr *ULE,
3894 SourceLocation LParenLoc, Expr *LHS,
3895 BinaryOperatorKind Operator,
3896 SourceLocation EllipsisLoc, Expr *RHS,
3897 SourceLocation RParenLoc,
3898 std::optional<unsigned> NumExpansions) {
3899 return getSema().BuildCXXFoldExpr(ULE, LParenLoc, LHS, Operator,
3900 EllipsisLoc, RHS, RParenLoc,
3901 NumExpansions);
3902 }
3903
3904 /// Build an empty C++1z fold-expression with the given operator.
3905 ///
3906 /// By default, produces the fallback value for the fold-expression, or
3907 /// produce an error if there is no fallback value.
3908 ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3909 BinaryOperatorKind Operator) {
3910 return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3911 }
3912
3913 /// Build a new atomic operation expression.
3914 ///
3915 /// By default, performs semantic analysis to build the new expression.
3916 /// Subclasses may override this routine to provide different behavior.
3917 ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3918 AtomicExpr::AtomicOp Op,
3919 SourceLocation RParenLoc) {
3920 // Use this for all of the locations, since we don't know the difference
3921 // between the call and the expr at this point.
3922 SourceRange Range{BuiltinLoc, RParenLoc};
3923 return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3924 Sema::AtomicArgumentOrder::AST);
3925 }
3926
3927 ExprResult RebuildRecoveryExpr(SourceLocation BeginLoc, SourceLocation EndLoc,
3928 ArrayRef<Expr *> SubExprs, QualType Type) {
3929 return getSema().CreateRecoveryExpr(BeginLoc, EndLoc, SubExprs, Type);
3930 }
3931
3932private:
3933 TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3934 QualType ObjectType,
3935 NamedDecl *FirstQualifierInScope,
3936 CXXScopeSpec &SS);
3937
3938 TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3939 QualType ObjectType,
3940 NamedDecl *FirstQualifierInScope,
3941 CXXScopeSpec &SS);
3942
3943 TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3944 NamedDecl *FirstQualifierInScope,
3945 CXXScopeSpec &SS);
3946
3947 QualType TransformDependentNameType(TypeLocBuilder &TLB,
3948 DependentNameTypeLoc TL,
3949 bool DeducibleTSTContext);
3950};
3951
3952template <typename Derived>
3953StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3954 if (!S)
3955 return S;
3956
3957 switch (S->getStmtClass()) {
3958 case Stmt::NoStmtClass: break;
3959
3960 // Transform individual statement nodes
3961 // Pass SDK into statements that can produce a value
3962#define STMT(Node, Parent) \
3963 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3964#define VALUESTMT(Node, Parent) \
3965 case Stmt::Node##Class: \
3966 return getDerived().Transform##Node(cast<Node>(S), SDK);
3967#define ABSTRACT_STMT(Node)
3968#define EXPR(Node, Parent)
3969#include "clang/AST/StmtNodes.inc"
3970
3971 // Transform expressions by calling TransformExpr.
3972#define STMT(Node, Parent)
3973#define ABSTRACT_STMT(Stmt)
3974#define EXPR(Node, Parent) case Stmt::Node##Class:
3975#include "clang/AST/StmtNodes.inc"
3976 {
3977 ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3978
3979 if (SDK == SDK_StmtExprResult)
3980 E = getSema().ActOnStmtExprResult(E);
3981 return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3982 }
3983 }
3984
3985 return S;
3986}
3987
3988template<typename Derived>
3989OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3990 if (!S)
3991 return S;
3992
3993 switch (S->getClauseKind()) {
3994 default: break;
3995 // Transform individual clause nodes
3996#define GEN_CLANG_CLAUSE_CLASS
3997#define CLAUSE_CLASS(Enum, Str, Class) \
3998 case Enum: \
3999 return getDerived().Transform##Class(cast<Class>(S));
4000#include "llvm/Frontend/OpenMP/OMP.inc"
4001 }
4002
4003 return S;
4004}
4005
4006
4007template<typename Derived>
4008ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
4009 if (!E)
4010 return E;
4011
4012 switch (E->getStmtClass()) {
4013 case Stmt::NoStmtClass: break;
4014#define STMT(Node, Parent) case Stmt::Node##Class: break;
4015#define ABSTRACT_STMT(Stmt)
4016#define EXPR(Node, Parent) \
4017 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
4018#include "clang/AST/StmtNodes.inc"
4019 }
4020
4021 return E;
4022}
4023
4024template<typename Derived>
4025ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
4026 bool NotCopyInit) {
4027 // Initializers are instantiated like expressions, except that various outer
4028 // layers are stripped.
4029 if (!Init)
4030 return Init;
4031
4032 if (auto *FE = dyn_cast<FullExpr>(Init))
4033 Init = FE->getSubExpr();
4034
4035 if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init)) {
4036 OpaqueValueExpr *OVE = AIL->getCommonExpr();
4037 Init = OVE->getSourceExpr();
4038 }
4039
4040 if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
4041 Init = MTE->getSubExpr();
4042
4043 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
4044 Init = Binder->getSubExpr();
4045
4046 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
4047 Init = ICE->getSubExprAsWritten();
4048
4049 if (CXXStdInitializerListExpr *ILE =
4050 dyn_cast<CXXStdInitializerListExpr>(Init))
4051 return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
4052
4053 // If this is copy-initialization, we only need to reconstruct
4054 // InitListExprs. Other forms of copy-initialization will be a no-op if
4055 // the initializer is already the right type.
4056 CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
4057 if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
4058 return getDerived().TransformExpr(Init);
4059
4060 // Revert value-initialization back to empty parens.
4061 if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
4062 SourceRange Parens = VIE->getSourceRange();
4063 return getDerived().RebuildParenListExpr(Parens.getBegin(), std::nullopt,
4064 Parens.getEnd());
4065 }
4066
4067 // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
4068 if (isa<ImplicitValueInitExpr>(Init))
4069 return getDerived().RebuildParenListExpr(SourceLocation(), std::nullopt,
4070 SourceLocation());
4071
4072 // Revert initialization by constructor back to a parenthesized or braced list
4073 // of expressions. Any other form of initializer can just be reused directly.
4074 if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
4075 return getDerived().TransformExpr(Init);
4076
4077 // If the initialization implicitly converted an initializer list to a
4078 // std::initializer_list object, unwrap the std::initializer_list too.
4079 if (Construct && Construct->isStdInitListInitialization())
4080 return TransformInitializer(Construct->getArg(0), NotCopyInit);
4081
4082 // Enter a list-init context if this was list initialization.
4083 EnterExpressionEvaluationContext Context(
4084 getSema(), EnterExpressionEvaluationContext::InitList,
4085 Construct->isListInitialization());
4086
4087 SmallVector<Expr*, 8> NewArgs;
4088 bool ArgChanged = false;
4089 if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
4090 /*IsCall*/true, NewArgs, &ArgChanged))
4091 return ExprError();
4092
4093 // If this was list initialization, revert to syntactic list form.
4094 if (Construct->isListInitialization())
4095 return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
4096 Construct->getEndLoc());
4097
4098 // Build a ParenListExpr to represent anything else.
4099 SourceRange Parens = Construct->getParenOrBraceRange();
4100 if (Parens.isInvalid()) {
4101 // This was a variable declaration's initialization for which no initializer
4102 // was specified.
4103 assert(NewArgs.empty() &&(static_cast <bool> (NewArgs.empty() && "no parens or braces but have direct init with arguments?"
) ? void (0) : __assert_fail ("NewArgs.empty() && \"no parens or braces but have direct init with arguments?\""
, "clang/lib/Sema/TreeTransform.h", 4104, __extension__ __PRETTY_FUNCTION__
))
4104 "no parens or braces but have direct init with arguments?")(static_cast <bool> (NewArgs.empty() && "no parens or braces but have direct init with arguments?"
) ? void (0) : __assert_fail ("NewArgs.empty() && \"no parens or braces but have direct init with arguments?\""
, "clang/lib/Sema/TreeTransform.h", 4104, __extension__ __PRETTY_FUNCTION__
))
;
4105 return ExprEmpty();
4106 }
4107 return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
4108 Parens.getEnd());
4109}
4110
4111template<typename Derived>
4112bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
4113 unsigned NumInputs,
4114 bool IsCall,
4115 SmallVectorImpl<Expr *> &Outputs,
4116 bool *ArgChanged) {
4117 for (unsigned I = 0; I != NumInputs; ++I) {
4118 // If requested, drop call arguments that need to be dropped.
4119 if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
4120 if (ArgChanged)
4121 *ArgChanged = true;
4122
4123 break;
4124 }
4125
4126 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
4127 Expr *Pattern = Expansion->getPattern();
4128
4129 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4130 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4131 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 4131, __extension__ __PRETTY_FUNCTION__
))
;
4132
4133 // Determine whether the set of unexpanded parameter packs can and should
4134 // be expanded.
4135 bool Expand = true;
4136 bool RetainExpansion = false;
4137 std::optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
4138 std::optional<unsigned> NumExpansions = OrigNumExpansions;
4139 if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
4140 Pattern->getSourceRange(),
4141 Unexpanded,
4142 Expand, RetainExpansion,
4143 NumExpansions))
4144 return true;
4145
4146 if (!Expand) {
4147 // The transform has determined that we should perform a simple
4148 // transformation on the pack expansion, producing another pack
4149 // expansion.
4150 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4151 ExprResult OutPattern = getDerived().TransformExpr(Pattern);
4152 if (OutPattern.isInvalid())
4153 return true;
4154
4155 ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
4156 Expansion->getEllipsisLoc(),
4157 NumExpansions);
4158 if (Out.isInvalid())
4159 return true;
4160
4161 if (ArgChanged)
4162 *ArgChanged = true;
4163 Outputs.push_back(Out.get());
4164 continue;
4165 }
4166
4167 // Record right away that the argument was changed. This needs
4168 // to happen even if the array expands to nothing.
4169 if (ArgChanged) *ArgChanged = true;
4170
4171 // The transform has determined that we should perform an elementwise
4172 // expansion of the pattern. Do so.
4173 for (unsigned I = 0; I != *NumExpansions; ++I) {
4174 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4175 ExprResult Out = getDerived().TransformExpr(Pattern);
4176 if (Out.isInvalid())
4177 return true;
4178
4179 if (Out.get()->containsUnexpandedParameterPack()) {
4180 Out = getDerived().RebuildPackExpansion(
4181 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4182 if (Out.isInvalid())
4183 return true;
4184 }
4185
4186 Outputs.push_back(Out.get());
4187 }
4188
4189 // If we're supposed to retain a pack expansion, do so by temporarily
4190 // forgetting the partially-substituted parameter pack.
4191 if (RetainExpansion) {
4192 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4193
4194 ExprResult Out = getDerived().TransformExpr(Pattern);
4195 if (Out.isInvalid())
4196 return true;
4197
4198 Out = getDerived().RebuildPackExpansion(
4199 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4200 if (Out.isInvalid())
4201 return true;
4202
4203 Outputs.push_back(Out.get());
4204 }
4205
4206 continue;
4207 }
4208
4209 ExprResult Result =
4210 IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
4211 : getDerived().TransformExpr(Inputs[I]);
4212 if (Result.isInvalid())
4213 return true;
4214
4215 if (Result.get() != Inputs[I] && ArgChanged)
4216 *ArgChanged = true;
4217
4218 Outputs.push_back(Result.get());
4219 }
4220
4221 return false;
4222}
4223
4224template <typename Derived>
4225Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
4226 SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
4227 if (Var) {
4228 VarDecl *ConditionVar = cast_or_null<VarDecl>(
4229 getDerived().TransformDefinition(Var->getLocation(), Var));
4230
4231 if (!ConditionVar)
4232 return Sema::ConditionError();
4233
4234 return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
4235 }
4236
4237 if (Expr) {
4238 ExprResult CondExpr = getDerived().TransformExpr(Expr);
4239
4240 if (CondExpr.isInvalid())
4241 return Sema::ConditionError();
4242
4243 return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind,
4244 /*MissingOK=*/true);
4245 }
4246
4247 return Sema::ConditionResult();
4248}
4249
4250template <typename Derived>
4251NestedNameSpecifierLoc TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
4252 NestedNameSpecifierLoc NNS, QualType ObjectType,
4253 NamedDecl *FirstQualifierInScope) {
4254 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
4255
4256 auto insertNNS = [&Qualifiers](NestedNameSpecifierLoc NNS) {
4257 for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
4258 Qualifier = Qualifier.getPrefix())
4259 Qualifiers.push_back(Qualifier);
4260 };
4261 insertNNS(NNS);
4262
4263 CXXScopeSpec SS;
4264 while (!Qualifiers.empty()) {
4265 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
4266 NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
4267
4268 switch (QNNS->getKind()) {
4269 case NestedNameSpecifier::Identifier: {
4270 Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
4271 Q.getLocalBeginLoc(), Q.getLocalEndLoc(),
4272 ObjectType);
4273 if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
4274 SS, FirstQualifierInScope, false))
4275 return NestedNameSpecifierLoc();
4276 break;
4277 }
4278
4279 case NestedNameSpecifier::Namespace: {
4280 NamespaceDecl *NS =
4281 cast_or_null<NamespaceDecl>(getDerived().TransformDecl(
4282 Q.getLocalBeginLoc(), QNNS->getAsNamespace()));
4283 SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
4284 break;
4285 }
4286
4287 case NestedNameSpecifier::NamespaceAlias: {
4288 NamespaceAliasDecl *Alias =
4289 cast_or_null<NamespaceAliasDecl>(getDerived().TransformDecl(
4290 Q.getLocalBeginLoc(), QNNS->getAsNamespaceAlias()));
4291 SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
4292 Q.getLocalEndLoc());
4293 break;
4294 }
4295
4296 case NestedNameSpecifier::Global:
4297 // There is no meaningful transformation that one could perform on the
4298 // global scope.
4299 SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
4300 break;
4301
4302 case NestedNameSpecifier::Super: {
4303 CXXRecordDecl *RD =
4304 cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
4305 SourceLocation(), QNNS->getAsRecordDecl()));
4306 SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
4307 break;
4308 }
4309
4310 case NestedNameSpecifier::TypeSpecWithTemplate:
4311 case NestedNameSpecifier::TypeSpec: {
4312 TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
4313 FirstQualifierInScope, SS);
4314
4315 if (!TL)
4316 return NestedNameSpecifierLoc();
4317
4318 QualType T = TL.getType();
4319 if (T->isDependentType() || T->isRecordType() ||
4320 (SemaRef.getLangOpts().CPlusPlus11 && T->isEnumeralType())) {
4321 if (T->isEnumeralType())
4322 SemaRef.Diag(TL.getBeginLoc(),
4323 diag::warn_cxx98_compat_enum_nested_name_spec);
4324
4325 if (const auto ETL = TL.getAs<ElaboratedTypeLoc>()) {
4326 SS.Adopt(ETL.getQualifierLoc());
4327 TL = ETL.getNamedTypeLoc();
4328 }
4329 SS.Extend(SemaRef.Context, /*FIXME:*/ SourceLocation(), TL,
4330 Q.getLocalEndLoc());
4331 break;
4332 }
4333 // If the nested-name-specifier is an invalid type def, don't emit an
4334 // error because a previous error should have already been emitted.
4335 TypedefTypeLoc TTL = TL.getAsAdjusted<TypedefTypeLoc>();
4336 if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
4337 SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
4338 << T << SS.getRange();
4339 }
4340 return NestedNameSpecifierLoc();
4341 }
4342 }
4343
4344 // The qualifier-in-scope and object type only apply to the leftmost entity.
4345 FirstQualifierInScope = nullptr;
4346 ObjectType = QualType();
4347 }
4348
4349 // Don't rebuild the nested-name-specifier if we don't have to.
4350 if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
4351 !getDerived().AlwaysRebuild())
4352 return NNS;
4353
4354 // If we can re-use the source-location data from the original
4355 // nested-name-specifier, do so.
4356 if (SS.location_size() == NNS.getDataLength() &&
4357 memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
4358 return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
4359
4360 // Allocate new nested-name-specifier location information.
4361 return SS.getWithLocInContext(SemaRef.Context);
4362}
4363
4364template<typename Derived>
4365DeclarationNameInfo
4366TreeTransform<Derived>
4367::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
4368 DeclarationName Name = NameInfo.getName();
4369 if (!Name)
4370 return DeclarationNameInfo();
4371
4372 switch (Name.getNameKind()) {
4373 case DeclarationName::Identifier:
4374 case DeclarationName::ObjCZeroArgSelector:
4375 case DeclarationName::ObjCOneArgSelector:
4376 case DeclarationName::ObjCMultiArgSelector:
4377 case DeclarationName::CXXOperatorName:
4378 case DeclarationName::CXXLiteralOperatorName:
4379 case DeclarationName::CXXUsingDirective:
4380 return NameInfo;
4381
4382 case DeclarationName::CXXDeductionGuideName: {
4383 TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
4384 TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
4385 getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
4386 if (!NewTemplate)
4387 return DeclarationNameInfo();
4388
4389 DeclarationNameInfo NewNameInfo(NameInfo);
4390 NewNameInfo.setName(
4391 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
4392 return NewNameInfo;
4393 }
4394
4395 case DeclarationName::CXXConstructorName:
4396 case DeclarationName::CXXDestructorName:
4397 case DeclarationName::CXXConversionFunctionName: {
4398 TypeSourceInfo *NewTInfo;
4399 CanQualType NewCanTy;
4400 if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
4401 NewTInfo = getDerived().TransformType(OldTInfo);
4402 if (!NewTInfo)
4403 return DeclarationNameInfo();
4404 NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
4405 }
4406 else {
4407 NewTInfo = nullptr;
4408 TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
4409 QualType NewT = getDerived().TransformType(Name.getCXXNameType());
4410 if (NewT.isNull())
4411 return DeclarationNameInfo();
4412 NewCanTy = SemaRef.Context.getCanonicalType(NewT);
4413 }
4414
4415 DeclarationName NewName
4416 = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
4417 NewCanTy);
4418 DeclarationNameInfo NewNameInfo(NameInfo);
4419 NewNameInfo.setName(NewName);
4420 NewNameInfo.setNamedTypeInfo(NewTInfo);
4421 return NewNameInfo;
4422 }
4423 }
4424
4425 llvm_unreachable("Unknown name kind.")::llvm::llvm_unreachable_internal("Unknown name kind.", "clang/lib/Sema/TreeTransform.h"
, 4425)
;
4426}
4427
4428template<typename Derived>
4429TemplateName
4430TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
4431 TemplateName Name,
4432 SourceLocation NameLoc,
4433 QualType ObjectType,
4434 NamedDecl *FirstQualifierInScope,
4435 bool AllowInjectedClassName) {
4436 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
4437 TemplateDecl *Template = QTN->getUnderlyingTemplate().getAsTemplateDecl();
4438 assert(Template && "qualified template name must refer to a template")(static_cast <bool> (Template && "qualified template name must refer to a template"
) ? void (0) : __assert_fail ("Template && \"qualified template name must refer to a template\""
, "clang/lib/Sema/TreeTransform.h", 4438, __extension__ __PRETTY_FUNCTION__
))
;
4439
4440 TemplateDecl *TransTemplate
4441 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4442 Template));
4443 if (!TransTemplate)
4444 return TemplateName();
4445
4446 if (!getDerived().AlwaysRebuild() &&
4447 SS.getScopeRep() == QTN->getQualifier() &&
4448 TransTemplate == Template)
4449 return Name;
4450
4451 return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
4452 TransTemplate);
4453 }
4454
4455 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
4456 if (SS.getScopeRep()) {
4457 // These apply to the scope specifier, not the template.
4458 ObjectType = QualType();
4459 FirstQualifierInScope = nullptr;
4460 }
4461
4462 if (!getDerived().AlwaysRebuild() &&
4463 SS.getScopeRep() == DTN->getQualifier() &&
4464 ObjectType.isNull())
4465 return Name;
4466
4467 // FIXME: Preserve the location of the "template" keyword.
4468 SourceLocation TemplateKWLoc = NameLoc;
4469
4470 if (DTN->isIdentifier()) {
4471 return getDerived().RebuildTemplateName(SS,
4472 TemplateKWLoc,
4473 *DTN->getIdentifier(),
4474 NameLoc,
4475 ObjectType,
4476 FirstQualifierInScope,
4477 AllowInjectedClassName);
4478 }
4479
4480 return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
4481 DTN->getOperator(), NameLoc,
4482 ObjectType, AllowInjectedClassName);
4483 }
4484
4485 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4486 TemplateDecl *TransTemplate
4487 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4488 Template));
4489 if (!TransTemplate)
4490 return TemplateName();
4491
4492 if (!getDerived().AlwaysRebuild() &&
4493 TransTemplate == Template)
4494 return Name;
4495
4496 return TemplateName(TransTemplate);
4497 }
4498
4499 if (SubstTemplateTemplateParmPackStorage *SubstPack
4500 = Name.getAsSubstTemplateTemplateParmPack()) {
4501 return getDerived().RebuildTemplateName(
4502 SubstPack->getArgumentPack(), SubstPack->getAssociatedDecl(),
4503 SubstPack->getIndex(), SubstPack->getFinal());
4504 }
4505
4506 // These should be getting filtered out before they reach the AST.
4507 llvm_unreachable("overloaded function decl survived to here")::llvm::llvm_unreachable_internal("overloaded function decl survived to here"
, "clang/lib/Sema/TreeTransform.h", 4507)
;
4508}
4509
4510template<typename Derived>
4511void TreeTransform<Derived>::InventTemplateArgumentLoc(
4512 const TemplateArgument &Arg,
4513 TemplateArgumentLoc &Output) {
4514 Output = getSema().getTrivialTemplateArgumentLoc(
4515 Arg, QualType(), getDerived().getBaseLocation());
4516}
4517
4518template <typename Derived>
4519bool TreeTransform<Derived>::TransformTemplateArgument(
4520 const TemplateArgumentLoc &Input, TemplateArgumentLoc &Output,
4521 bool Uneval) {
4522 const TemplateArgument &Arg = Input.getArgument();
4523 switch (Arg.getKind()) {
4524 case TemplateArgument::Null:
4525 case TemplateArgument::Pack:
4526 llvm_unreachable("Unexpected TemplateArgument")::llvm::llvm_unreachable_internal("Unexpected TemplateArgument"
, "clang/lib/Sema/TreeTransform.h", 4526)
;
4527
4528 case TemplateArgument::Integral:
4529 case TemplateArgument::NullPtr:
4530 case TemplateArgument::Declaration: {
4531 // Transform a resolved template argument straight to a resolved template
4532 // argument. We get here when substituting into an already-substituted
4533 // template type argument during concept satisfaction checking.
4534 QualType T = Arg.getNonTypeTemplateArgumentType();
4535 QualType NewT = getDerived().TransformType(T);
4536 if (NewT.isNull())
4537 return true;
4538
4539 ValueDecl *D = Arg.getKind() == TemplateArgument::Declaration
4540 ? Arg.getAsDecl()
4541 : nullptr;
4542 ValueDecl *NewD = D ? cast_or_null<ValueDecl>(getDerived().TransformDecl(
4543 getDerived().getBaseLocation(), D))
4544 : nullptr;
4545 if (D && !NewD)
4546 return true;
4547
4548 if (NewT == T && D == NewD)
4549 Output = Input;
4550 else if (Arg.getKind() == TemplateArgument::Integral)
4551 Output = TemplateArgumentLoc(
4552 TemplateArgument(getSema().Context, Arg.getAsIntegral(), NewT),
4553 TemplateArgumentLocInfo());
4554 else if (Arg.getKind() == TemplateArgument::NullPtr)
4555 Output = TemplateArgumentLoc(TemplateArgument(NewT, /*IsNullPtr=*/true),
4556 TemplateArgumentLocInfo());
4557 else
4558 Output = TemplateArgumentLoc(TemplateArgument(NewD, NewT),
4559 TemplateArgumentLocInfo());
4560
4561 return false;
4562 }
4563
4564 case TemplateArgument::Type: {
4565 TypeSourceInfo *DI = Input.getTypeSourceInfo();
4566 if (!DI)
4567 DI = InventTypeSourceInfo(Input.getArgument().getAsType());
4568
4569 DI = getDerived().TransformType(DI);
4570 if (!DI)
4571 return true;
4572
4573 Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4574 return false;
4575 }
4576
4577 case TemplateArgument::Template: {
4578 NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4579 if (QualifierLoc) {
4580 QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4581 if (!QualifierLoc)
4582 return true;
4583 }
4584
4585 CXXScopeSpec SS;
4586 SS.Adopt(QualifierLoc);
4587 TemplateName Template = getDerived().TransformTemplateName(
4588 SS, Arg.getAsTemplate(), Input.getTemplateNameLoc());
4589 if (Template.isNull())
4590 return true;
4591
4592 Output = TemplateArgumentLoc(SemaRef.Context, TemplateArgument(Template),
4593 QualifierLoc, Input.getTemplateNameLoc());
4594 return false;
4595 }
4596
4597 case TemplateArgument::TemplateExpansion:
4598 llvm_unreachable("Caller should expand pack expansions")::llvm::llvm_unreachable_internal("Caller should expand pack expansions"
, "clang/lib/Sema/TreeTransform.h", 4598)
;
4599
4600 case TemplateArgument::Expression: {
4601 // Template argument expressions are constant expressions.
4602 EnterExpressionEvaluationContext Unevaluated(
4603 getSema(),
4604 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4605 : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4606 Sema::ReuseLambdaContextDecl, /*ExprContext=*/
4607 Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4608
4609 Expr *InputExpr = Input.getSourceExpression();
4610 if (!InputExpr)
4611 InputExpr = Input.getArgument().getAsExpr();
4612
4613 ExprResult E = getDerived().TransformExpr(InputExpr);
4614 E = SemaRef.ActOnConstantExpression(E);
4615 if (E.isInvalid())
4616 return true;
4617 Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4618 return false;
4619 }
4620 }
4621
4622 // Work around bogus GCC warning
4623 return true;
4624}
4625
4626/// Iterator adaptor that invents template argument location information
4627/// for each of the template arguments in its underlying iterator.
4628template<typename Derived, typename InputIterator>
4629class TemplateArgumentLocInventIterator {
4630 TreeTransform<Derived> &Self;
4631 InputIterator Iter;
4632
4633public:
4634 typedef TemplateArgumentLoc value_type;
4635 typedef TemplateArgumentLoc reference;
4636 typedef typename std::iterator_traits<InputIterator>::difference_type
4637 difference_type;
4638 typedef std::input_iterator_tag iterator_category;
4639
4640 class pointer {
4641 TemplateArgumentLoc Arg;
4642
4643 public:
4644 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4645
4646 const TemplateArgumentLoc *operator->() const { return &Arg; }
4647 };
4648
4649 TemplateArgumentLocInventIterator() { }
4650
4651 explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4652 InputIterator Iter)
4653 : Self(Self), Iter(Iter) { }
4654
4655 TemplateArgumentLocInventIterator &operator++() {
4656 ++Iter;
4657 return *this;
4658 }
4659
4660 TemplateArgumentLocInventIterator operator++(int) {
4661 TemplateArgumentLocInventIterator Old(*this);
4662 ++(*this);
4663 return Old;
4664 }
4665
4666 reference operator*() const {
4667 TemplateArgumentLoc Result;
4668 Self.InventTemplateArgumentLoc(*Iter, Result);
4669 return Result;
4670 }
4671
4672 pointer operator->() const { return pointer(**this); }
4673
4674 friend bool operator==(const TemplateArgumentLocInventIterator &X,
4675 const TemplateArgumentLocInventIterator &Y) {
4676 return X.Iter == Y.Iter;
4677 }
4678
4679 friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4680 const TemplateArgumentLocInventIterator &Y) {
4681 return X.Iter != Y.Iter;
4682 }
4683};
4684
4685template<typename Derived>
4686template<typename InputIterator>
4687bool TreeTransform<Derived>::TransformTemplateArguments(
4688 InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4689 bool Uneval) {
4690 for (; First != Last; ++First) {
4691 TemplateArgumentLoc Out;
4692 TemplateArgumentLoc In = *First;
4693
4694 if (In.getArgument().getKind() == TemplateArgument::Pack) {
4695 // Unpack argument packs, which we translate them into separate
4696 // arguments.
4697 // FIXME: We could do much better if we could guarantee that the
4698 // TemplateArgumentLocInfo for the pack expansion would be usable for
4699 // all of the template arguments in the argument pack.
4700 typedef TemplateArgumentLocInventIterator<Derived,
4701 TemplateArgument::pack_iterator>
4702 PackLocIterator;
4703 if (TransformTemplateArguments(PackLocIterator(*this,
4704 In.getArgument().pack_begin()),
4705 PackLocIterator(*this,
4706 In.getArgument().pack_end()),
4707 Outputs, Uneval))
4708 return true;
4709
4710 continue;
4711 }
4712
4713 if (In.getArgument().isPackExpansion()) {
4714 // We have a pack expansion, for which we will be substituting into
4715 // the pattern.
4716 SourceLocation Ellipsis;
4717 std::optional<unsigned> OrigNumExpansions;
4718 TemplateArgumentLoc Pattern
4719 = getSema().getTemplateArgumentPackExpansionPattern(
4720 In, Ellipsis, OrigNumExpansions);
4721
4722 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4723 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4724 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 4724, __extension__ __PRETTY_FUNCTION__
))
;
4725
4726 // Determine whether the set of unexpanded parameter packs can and should
4727 // be expanded.
4728 bool Expand = true;
4729 bool RetainExpansion = false;
4730 std::optional<unsigned> NumExpansions = OrigNumExpansions;
4731 if (getDerived().TryExpandParameterPacks(Ellipsis,
4732 Pattern.getSourceRange(),
4733 Unexpanded,
4734 Expand,
4735 RetainExpansion,
4736 NumExpansions))
4737 return true;
4738
4739 if (!Expand) {
4740 // The transform has determined that we should perform a simple
4741 // transformation on the pack expansion, producing another pack
4742 // expansion.
4743 TemplateArgumentLoc OutPattern;
4744 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4745 if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4746 return true;
4747
4748 Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4749 NumExpansions);
4750 if (Out.getArgument().isNull())
4751 return true;
4752
4753 Outputs.addArgument(Out);
4754 continue;
4755 }
4756
4757 // The transform has determined that we should perform an elementwise
4758 // expansion of the pattern. Do so.
4759 for (unsigned I = 0; I != *NumExpansions; ++I) {
4760 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4761
4762 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4763 return true;
4764
4765 if (Out.getArgument().containsUnexpandedParameterPack()) {
4766 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4767 OrigNumExpansions);
4768 if (Out.getArgument().isNull())
4769 return true;
4770 }
4771
4772 Outputs.addArgument(Out);
4773 }
4774
4775 // If we're supposed to retain a pack expansion, do so by temporarily
4776 // forgetting the partially-substituted parameter pack.
4777 if (RetainExpansion) {
4778 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4779
4780 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4781 return true;
4782
4783 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4784 OrigNumExpansions);
4785 if (Out.getArgument().isNull())
4786 return true;
4787
4788 Outputs.addArgument(Out);
4789 }
4790
4791 continue;
4792 }
4793
4794 // The simple case:
4795 if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4796 return true;
4797
4798 Outputs.addArgument(Out);
4799 }
4800
4801 return false;
4802
4803}
4804
4805//===----------------------------------------------------------------------===//
4806// Type transformation
4807//===----------------------------------------------------------------------===//
4808
4809template<typename Derived>
4810QualType TreeTransform<Derived>::TransformType(QualType T) {
4811 if (getDerived().AlreadyTransformed(T))
4812 return T;
4813
4814 // Temporary workaround. All of these transformations should
4815 // eventually turn into transformations on TypeLocs.
4816 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4817 getDerived().getBaseLocation());
4818
4819 TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4820
4821 if (!NewDI)
4822 return QualType();
4823
4824 return NewDI->getType();
4825}
4826
4827template<typename Derived>
4828TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4829 // Refine the base location to the type's location.
4830 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4831 getDerived().getBaseEntity());
4832 if (getDerived().AlreadyTransformed(DI->getType()))
4833 return DI;
4834
4835 TypeLocBuilder TLB;
4836
4837 TypeLoc TL = DI->getTypeLoc();
4838 TLB.reserve(TL.getFullDataSize());
4839
4840 QualType Result = getDerived().TransformType(TLB, TL);
4841 if (Result.isNull())
4842 return nullptr;
4843
4844 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4845}
4846
4847template<typename Derived>
4848QualType
4849TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4850 switch (T.getTypeLocClass()) {
4851#define ABSTRACT_TYPELOC(CLASS, PARENT)
4852#define TYPELOC(CLASS, PARENT) \
4853 case TypeLoc::CLASS: \
4854 return getDerived().Transform##CLASS##Type(TLB, \
4855 T.castAs<CLASS##TypeLoc>());
4856#include "clang/AST/TypeLocNodes.def"
4857 }
4858
4859 llvm_unreachable("unhandled type loc!")::llvm::llvm_unreachable_internal("unhandled type loc!", "clang/lib/Sema/TreeTransform.h"
, 4859)
;
4860}
4861
4862template<typename Derived>
4863QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4864 if (!isa<DependentNameType>(T))
4865 return TransformType(T);
4866
4867 if (getDerived().AlreadyTransformed(T))
4868 return T;
4869 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4870 getDerived().getBaseLocation());
4871 TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4872 return NewDI ? NewDI->getType() : QualType();
4873}
4874
4875template<typename Derived>
4876TypeSourceInfo *
4877TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4878 if (!isa<DependentNameType>(DI->getType()))
4879 return TransformType(DI);
4880
4881 // Refine the base location to the type's location.
4882 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4883 getDerived().getBaseEntity());
4884 if (getDerived().AlreadyTransformed(DI->getType()))
4885 return DI;
4886
4887 TypeLocBuilder TLB;
4888
4889 TypeLoc TL = DI->getTypeLoc();
4890 TLB.reserve(TL.getFullDataSize());
4891
4892 auto QTL = TL.getAs<QualifiedTypeLoc>();
4893 if (QTL)
4894 TL = QTL.getUnqualifiedLoc();
4895
4896 auto DNTL = TL.castAs<DependentNameTypeLoc>();
4897
4898 QualType Result = getDerived().TransformDependentNameType(
4899 TLB, DNTL, /*DeducedTSTContext*/true);
4900 if (Result.isNull())
4901 return nullptr;
4902
4903 if (QTL) {
4904 Result = getDerived().RebuildQualifiedType(Result, QTL);
4905 if (Result.isNull())
4906 return nullptr;
4907 TLB.TypeWasModifiedSafely(Result);
4908 }
4909
4910 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4911}
4912
4913template<typename Derived>
4914QualType
4915TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4916 QualifiedTypeLoc T) {
4917 QualType Result;
4918 TypeLoc UnqualTL = T.getUnqualifiedLoc();
4919 auto SuppressObjCLifetime =
4920 T.getType().getLocalQualifiers().hasObjCLifetime();
4921 if (auto TTP = UnqualTL.getAs<TemplateTypeParmTypeLoc>()) {
4922 Result = getDerived().TransformTemplateTypeParmType(TLB, TTP,
4923 SuppressObjCLifetime);
4924 } else if (auto STTP = UnqualTL.getAs<SubstTemplateTypeParmPackTypeLoc>()) {
4925 Result = getDerived().TransformSubstTemplateTypeParmPackType(
4926 TLB, STTP, SuppressObjCLifetime);
4927 } else {
4928 Result = getDerived().TransformType(TLB, UnqualTL);
4929 }
4930
4931 if (Result.isNull())
4932 return QualType();
4933
4934 Result = getDerived().RebuildQualifiedType(Result, T);
4935
4936 if (Result.isNull())
4937 return QualType();
4938
4939 // RebuildQualifiedType might have updated the type, but not in a way
4940 // that invalidates the TypeLoc. (There's no location information for
4941 // qualifiers.)
4942 TLB.TypeWasModifiedSafely(Result);
4943
4944 return Result;
4945}
4946
4947template <typename Derived>
4948QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4949 QualifiedTypeLoc TL) {
4950
4951 SourceLocation Loc = TL.getBeginLoc();
4952 Qualifiers Quals = TL.getType().getLocalQualifiers();
4953
4954 if ((T.getAddressSpace() != LangAS::Default &&
4955 Quals.getAddressSpace() != LangAS::Default) &&
4956 T.getAddressSpace() != Quals.getAddressSpace()) {
4957 SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4958 << TL.getType() << T;
4959 return QualType();
4960 }
4961
4962 // C++ [dcl.fct]p7:
4963 // [When] adding cv-qualifications on top of the function type [...] the
4964 // cv-qualifiers are ignored.
4965 if (T->isFunctionType()) {
4966 T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4967 Quals.getAddressSpace());
4968 return T;
4969 }
4970
4971 // C++ [dcl.ref]p1:
4972 // when the cv-qualifiers are introduced through the use of a typedef-name
4973 // or decltype-specifier [...] the cv-qualifiers are ignored.
4974 // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4975 // applied to a reference type.
4976 if (T->isReferenceType()) {
4977 // The only qualifier that applies to a reference type is restrict.
4978 if (!Quals.hasRestrict())
4979 return T;
4980 Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4981 }
4982
4983 // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4984 // resulting type.
4985 if (Quals.hasObjCLifetime()) {
4986 if (!T->isObjCLifetimeType() && !T->isDependentType())
4987 Quals.removeObjCLifetime();
4988 else if (T.getObjCLifetime()) {
4989 // Objective-C ARC:
4990 // A lifetime qualifier applied to a substituted template parameter
4991 // overrides the lifetime qualifier from the template argument.
4992 const AutoType *AutoTy;
4993 if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4994 // 'auto' types behave the same way as template parameters.
4995 QualType Deduced = AutoTy->getDeducedType();
4996 Qualifiers Qs = Deduced.getQualifiers();
4997 Qs.removeObjCLifetime();
4998 Deduced =
4999 SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
5000 T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
5001 AutoTy->isDependentType(),
5002 /*isPack=*/false,
5003 AutoTy->getTypeConstraintConcept(),
5004 AutoTy->getTypeConstraintArguments());
5005 } else {
5006 // Otherwise, complain about the addition of a qualifier to an
5007 // already-qualified type.
5008 // FIXME: Why is this check not in Sema::BuildQualifiedType?
5009 SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
5010 Quals.removeObjCLifetime();
5011 }
5012 }
5013 }
5014
5015 return SemaRef.BuildQualifiedType(T, Loc, Quals);
5016}
5017
5018template<typename Derived>
5019TypeLoc
5020TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
5021 QualType ObjectType,
5022 NamedDecl *UnqualLookup,
5023 CXXScopeSpec &SS) {
5024 if (getDerived().AlreadyTransformed(TL.getType()))
5025 return TL;
5026
5027 TypeSourceInfo *TSI =
5028 TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
5029 if (TSI)
5030 return TSI->getTypeLoc();
5031 return TypeLoc();
5032}
5033
5034template<typename Derived>
5035TypeSourceInfo *
5036TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
5037 QualType ObjectType,
5038 NamedDecl *UnqualLookup,
5039 CXXScopeSpec &SS) {
5040 if (getDerived().AlreadyTransformed(TSInfo->getType()))
5041 return TSInfo;
5042
5043 return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
5044 UnqualLookup, SS);
5045}
5046
5047template <typename Derived>
5048TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
5049 TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
5050 CXXScopeSpec &SS) {
5051 QualType T = TL.getType();
5052 assert(!getDerived().AlreadyTransformed(T))(static_cast <bool> (!getDerived().AlreadyTransformed(T
)) ? void (0) : __assert_fail ("!getDerived().AlreadyTransformed(T)"
, "clang/lib/Sema/TreeTransform.h", 5052, __extension__ __PRETTY_FUNCTION__
))
;
5053
5054 TypeLocBuilder TLB;
5055 QualType Result;
5056
5057 if (isa<TemplateSpecializationType>(T)) {
5058 TemplateSpecializationTypeLoc SpecTL =
5059 TL.castAs<TemplateSpecializationTypeLoc>();
5060
5061 TemplateName Template = getDerived().TransformTemplateName(
5062 SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
5063 ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
5064 if (Template.isNull())
5065 return nullptr;
5066
5067 Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
5068 Template);
5069 } else if (isa<DependentTemplateSpecializationType>(T)) {
5070 DependentTemplateSpecializationTypeLoc SpecTL =
5071 TL.castAs<DependentTemplateSpecializationTypeLoc>();
5072
5073 TemplateName Template
5074 = getDerived().RebuildTemplateName(SS,
5075 SpecTL.getTemplateKeywordLoc(),
5076 *SpecTL.getTypePtr()->getIdentifier(),
5077 SpecTL.getTemplateNameLoc(),
5078 ObjectType, UnqualLookup,
5079 /*AllowInjectedClassName*/true);
5080 if (Template.isNull())
5081 return nullptr;
5082
5083 Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
5084 SpecTL,
5085 Template,
5086 SS);
5087 } else {
5088 // Nothing special needs to be done for these.
5089 Result = getDerived().TransformType(TLB, TL);
5090 }
5091
5092 if (Result.isNull())
5093 return nullptr;
5094
5095 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
5096}
5097
5098template <class TyLoc> static inline
5099QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
5100 TyLoc NewT = TLB.push<TyLoc>(T.getType());
5101 NewT.setNameLoc(T.getNameLoc());
5102 return T.getType();
5103}
5104
5105template<typename Derived>
5106QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
5107 BuiltinTypeLoc T) {
5108 BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
5109 NewT.setBuiltinLoc(T.getBuiltinLoc());
5110 if (T.needsExtraLocalData())
5111 NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
5112 return T.getType();
5113}
5114
5115template<typename Derived>
5116QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
5117 ComplexTypeLoc T) {
5118 // FIXME: recurse?
5119 return TransformTypeSpecType(TLB, T);
5120}
5121
5122template <typename Derived>
5123QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
5124 AdjustedTypeLoc TL) {
5125 // Adjustments applied during transformation are handled elsewhere.
5126 return getDerived().TransformType(TLB, TL.getOriginalLoc());
5127}
5128
5129template<typename Derived>
5130QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
5131 DecayedTypeLoc TL) {
5132 QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
5133 if (OriginalType.isNull())
5134 return QualType();
5135
5136 QualType Result = TL.getType();
5137 if (getDerived().AlwaysRebuild() ||
5138 OriginalType != TL.getOriginalLoc().getType())
5139 Result = SemaRef.Context.getDecayedType(OriginalType);
5140 TLB.push<DecayedTypeLoc>(Result);
5141 // Nothing to set for DecayedTypeLoc.
5142 return Result;
5143}
5144
5145template<typename Derived>
5146QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
5147 PointerTypeLoc TL) {
5148 QualType PointeeType
5149 = getDerived().TransformType(TLB, TL.getPointeeLoc());
5150 if (PointeeType.isNull())
5151 return QualType();
5152
5153 QualType Result = TL.getType();
5154 if (PointeeType->getAs<ObjCObjectType>()) {
5155 // A dependent pointer type 'T *' has is being transformed such
5156 // that an Objective-C class type is being replaced for 'T'. The
5157 // resulting pointer type is an ObjCObjectPointerType, not a
5158 // PointerType.
5159 Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
5160
5161 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
5162 NewT.setStarLoc(TL.getStarLoc());
5163 return Result;
5164 }
5165
5166 if (getDerived().AlwaysRebuild() ||
5167 PointeeType != TL.getPointeeLoc().getType()) {
5168 Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
5169 if (Result.isNull())
5170 return QualType();
5171 }
5172
5173 // Objective-C ARC can add lifetime qualifiers to the type that we're
5174 // pointing to.
5175 TLB.TypeWasModifiedSafely(Result->getPointeeType());
5176
5177 PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
5178 NewT.setSigilLoc(TL.getSigilLoc());
5179 return Result;
5180}
5181
5182template<typename Derived>
5183QualType
5184TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
5185 BlockPointerTypeLoc TL) {
5186 QualType PointeeType
5187 = getDerived().TransformType(TLB, TL.getPointeeLoc());
5188 if (PointeeType.isNull())
5189 return QualType();
5190
5191 QualType Result = TL.getType();
5192 if (getDerived().AlwaysRebuild() ||
5193 PointeeType != TL.getPointeeLoc().getType()) {
5194 Result = getDerived().RebuildBlockPointerType(PointeeType,
5195 TL.getSigilLoc());
5196 if (Result.isNull())
5197 return QualType();
5198 }
5199
5200 BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
5201 NewT.setSigilLoc(TL.getSigilLoc());
5202 return Result;
5203}
5204
5205/// Transforms a reference type. Note that somewhat paradoxically we
5206/// don't care whether the type itself is an l-value type or an r-value
5207/// type; we only care if the type was *written* as an l-value type
5208/// or an r-value type.
5209template<typename Derived>
5210QualType
5211TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
5212 ReferenceTypeLoc TL) {
5213 const ReferenceType *T = TL.getTypePtr();
5214
5215 // Note that this works with the pointee-as-written.
5216 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5217 if (PointeeType.isNull())
5218 return QualType();
5219
5220 QualType Result = TL.getType();
5221 if (getDerived().AlwaysRebuild() ||
5222 PointeeType != T->getPointeeTypeAsWritten()) {
5223 Result = getDerived().RebuildReferenceType(PointeeType,
5224 T->isSpelledAsLValue(),
5225 TL.getSigilLoc());
5226 if (Result.isNull())
5227 return QualType();
5228 }
5229
5230 // Objective-C ARC can add lifetime qualifiers to the type that we're
5231 // referring to.
5232 TLB.TypeWasModifiedSafely(
5233 Result->castAs<ReferenceType>()->getPointeeTypeAsWritten());
5234
5235 // r-value references can be rebuilt as l-value references.
5236 ReferenceTypeLoc NewTL;
5237 if (isa<LValueReferenceType>(Result))
5238 NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
5239 else
5240 NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
5241 NewTL.setSigilLoc(TL.getSigilLoc());
5242
5243 return Result;
5244}
5245
5246template<typename Derived>
5247QualType
5248TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
5249 LValueReferenceTypeLoc TL) {
5250 return TransformReferenceType(TLB, TL);
5251}
5252
5253template<typename Derived>
5254QualType
5255TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
5256 RValueReferenceTypeLoc TL) {
5257 return TransformReferenceType(TLB, TL);
5258}
5259
5260template<typename Derived>
5261QualType
5262TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
5263 MemberPointerTypeLoc TL) {
5264 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5265 if (PointeeType.isNull())
5266 return QualType();
5267
5268 TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
5269 TypeSourceInfo *NewClsTInfo = nullptr;
5270 if (OldClsTInfo) {
5271 NewClsTInfo = getDerived().TransformType(OldClsTInfo);
5272 if (!NewClsTInfo)
5273 return QualType();
5274 }
5275
5276 const MemberPointerType *T = TL.getTypePtr();
5277 QualType OldClsType = QualType(T->getClass(), 0);
5278 QualType NewClsType;
5279 if (NewClsTInfo)
5280 NewClsType = NewClsTInfo->getType();
5281 else {
5282 NewClsType = getDerived().TransformType(OldClsType);
5283 if (NewClsType.isNull())
5284 return QualType();
5285 }
5286
5287 QualType Result = TL.getType();
5288 if (getDerived().AlwaysRebuild() ||
5289 PointeeType != T->getPointeeType() ||
5290 NewClsType != OldClsType) {
5291 Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
5292 TL.getStarLoc());
5293 if (Result.isNull())
5294 return QualType();
5295 }
5296
5297 // If we had to adjust the pointee type when building a member pointer, make
5298 // sure to push TypeLoc info for it.
5299 const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
5300 if (MPT && PointeeType != MPT->getPointeeType()) {
5301 assert(isa<AdjustedType>(MPT->getPointeeType()))(static_cast <bool> (isa<AdjustedType>(MPT->getPointeeType
())) ? void (0) : __assert_fail ("isa<AdjustedType>(MPT->getPointeeType())"
, "clang/lib/Sema/TreeTransform.h", 5301, __extension__ __PRETTY_FUNCTION__
))
;
5302 TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
5303 }
5304
5305 MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
5306 NewTL.setSigilLoc(TL.getSigilLoc());
5307 NewTL.setClassTInfo(NewClsTInfo);
5308
5309 return Result;
5310}
5311
5312template<typename Derived>
5313QualType
5314TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
5315 ConstantArrayTypeLoc TL) {
5316 const ConstantArrayType *T = TL.getTypePtr();
5317 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5318 if (ElementType.isNull())
5319 return QualType();
5320
5321 // Prefer the expression from the TypeLoc; the other may have been uniqued.
5322 Expr *OldSize = TL.getSizeExpr();
5323 if (!OldSize)
5324 OldSize = const_cast<Expr*>(T->getSizeExpr());
5325 Expr *NewSize = nullptr;
5326 if (OldSize) {
5327 EnterExpressionEvaluationContext Unevaluated(
5328 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5329 NewSize = getDerived().TransformExpr(OldSize).template getAs<Expr>();
5330 NewSize = SemaRef.ActOnConstantExpression(NewSize).get();
5331 }
5332
5333 QualType Result = TL.getType();
5334 if (getDerived().AlwaysRebuild() ||
5335 ElementType != T->getElementType() ||
5336 (T->getSizeExpr() && NewSize != OldSize)) {
5337 Result = getDerived().RebuildConstantArrayType(ElementType,
5338 T->getSizeModifier(),
5339 T->getSize(), NewSize,
5340 T->getIndexTypeCVRQualifiers(),
5341 TL.getBracketsRange());
5342 if (Result.isNull())
5343 return QualType();
5344 }
5345
5346 // We might have either a ConstantArrayType or a VariableArrayType now:
5347 // a ConstantArrayType is allowed to have an element type which is a
5348 // VariableArrayType if the type is dependent. Fortunately, all array
5349 // types have the same location layout.
5350 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5351 NewTL.setLBracketLoc(TL.getLBracketLoc());
5352 NewTL.setRBracketLoc(TL.getRBracketLoc());
5353 NewTL.setSizeExpr(NewSize);
5354
5355 return Result;
5356}
5357
5358template<typename Derived>
5359QualType TreeTransform<Derived>::TransformIncompleteArrayType(
5360 TypeLocBuilder &TLB,
5361 IncompleteArrayTypeLoc TL) {
5362 const IncompleteArrayType *T = TL.getTypePtr();
5363 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5364 if (ElementType.isNull())
5365 return QualType();
5366
5367 QualType Result = TL.getType();
5368 if (getDerived().AlwaysRebuild() ||
5369 ElementType != T->getElementType()) {
5370 Result = getDerived().RebuildIncompleteArrayType(ElementType,
5371 T->getSizeModifier(),
5372 T->getIndexTypeCVRQualifiers(),
5373 TL.getBracketsRange());
5374 if (Result.isNull())
5375 return QualType();
5376 }
5377
5378 IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
5379 NewTL.setLBracketLoc(TL.getLBracketLoc());
5380 NewTL.setRBracketLoc(TL.getRBracketLoc());
5381 NewTL.setSizeExpr(nullptr);
5382
5383 return Result;
5384}
5385
5386template<typename Derived>
5387QualType
5388TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
5389 VariableArrayTypeLoc TL) {
5390 const VariableArrayType *T = TL.getTypePtr();
5391 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5392 if (ElementType.isNull())
5393 return QualType();
5394
5395 ExprResult SizeResult;
5396 {
5397 EnterExpressionEvaluationContext Context(
5398 SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
5399 SizeResult = getDerived().TransformExpr(T->getSizeExpr());
5400 }
5401 if (SizeResult.isInvalid())
5402 return QualType();
5403 SizeResult =
5404 SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
5405 if (SizeResult.isInvalid())
5406 return QualType();
5407
5408 Expr *Size = SizeResult.get();
5409
5410 QualType Result = TL.getType();
5411 if (getDerived().AlwaysRebuild() ||
5412 ElementType != T->getElementType() ||
5413 Size != T->getSizeExpr()) {
5414 Result = getDerived().RebuildVariableArrayType(ElementType,
5415 T->getSizeModifier(),
5416 Size,
5417 T->getIndexTypeCVRQualifiers(),
5418 TL.getBracketsRange());
5419 if (Result.isNull())
5420 return QualType();
5421 }
5422
5423 // We might have constant size array now, but fortunately it has the same
5424 // location layout.
5425 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5426 NewTL.setLBracketLoc(TL.getLBracketLoc());
5427 NewTL.setRBracketLoc(TL.getRBracketLoc());
5428 NewTL.setSizeExpr(Size);
5429
5430 return Result;
5431}
5432
5433template<typename Derived>
5434QualType
5435TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
5436 DependentSizedArrayTypeLoc TL) {
5437 const DependentSizedArrayType *T = TL.getTypePtr();
5438 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5439 if (ElementType.isNull())
5440 return QualType();
5441
5442 // Array bounds are constant expressions.
5443 EnterExpressionEvaluationContext Unevaluated(
5444 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5445
5446 // Prefer the expression from the TypeLoc; the other may have been uniqued.
5447 Expr *origSize = TL.getSizeExpr();
5448 if (!origSize) origSize = T->getSizeExpr();
5449
5450 ExprResult sizeResult
5451 = getDerived().TransformExpr(origSize);
5452 sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
5453 if (sizeResult.isInvalid())
5454 return QualType();
5455
5456 Expr *size = sizeResult.get();
5457
5458 QualType Result = TL.getType();
5459 if (getDerived().AlwaysRebuild() ||
5460 ElementType != T->getElementType() ||
5461 size != origSize) {
5462 Result = getDerived().RebuildDependentSizedArrayType(ElementType,
5463 T->getSizeModifier(),
5464 size,
5465 T->getIndexTypeCVRQualifiers(),
5466 TL.getBracketsRange());
5467 if (Result.isNull())
5468 return QualType();
5469 }
5470
5471 // We might have any sort of array type now, but fortunately they
5472 // all have the same location layout.
5473 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5474 NewTL.setLBracketLoc(TL.getLBracketLoc());
5475 NewTL.setRBracketLoc(TL.getRBracketLoc());
5476 NewTL.setSizeExpr(size);
5477
5478 return Result;
5479}
5480
5481template <typename Derived>
5482QualType TreeTransform<Derived>::TransformDependentVectorType(
5483 TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
5484 const DependentVectorType *T = TL.getTypePtr();
5485 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5486 if (ElementType.isNull())
5487 return QualType();
5488
5489 EnterExpressionEvaluationContext Unevaluated(
5490 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5491
5492 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5493 Size = SemaRef.ActOnConstantExpression(Size);
5494 if (Size.isInvalid())
5495 return QualType();
5496
5497 QualType Result = TL.getType();
5498 if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5499 Size.get() != T->getSizeExpr()) {
5500 Result = getDerived().RebuildDependentVectorType(
5501 ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
5502 if (Result.isNull())
5503 return QualType();
5504 }
5505
5506 // Result might be dependent or not.
5507 if (isa<DependentVectorType>(Result)) {
5508 DependentVectorTypeLoc NewTL =
5509 TLB.push<DependentVectorTypeLoc>(Result);
5510 NewTL.setNameLoc(TL.getNameLoc());
5511 } else {
5512 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5513 NewTL.setNameLoc(TL.getNameLoc());
5514 }
5515
5516 return Result;
5517}
5518
5519template<typename Derived>
5520QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
5521 TypeLocBuilder &TLB,
5522 DependentSizedExtVectorTypeLoc TL) {
5523 const DependentSizedExtVectorType *T = TL.getTypePtr();
5524
5525 // FIXME: ext vector locs should be nested
5526 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5527 if (ElementType.isNull())
5528 return QualType();
5529
5530 // Vector sizes are constant expressions.
5531 EnterExpressionEvaluationContext Unevaluated(
5532 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5533
5534 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5535 Size = SemaRef.ActOnConstantExpression(Size);
5536 if (Size.isInvalid())
5537 return QualType();
5538
5539 QualType Result = TL.getType();
5540 if (getDerived().AlwaysRebuild() ||
5541 ElementType != T->getElementType() ||
5542 Size.get() != T->getSizeExpr()) {
5543 Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
5544 Size.get(),
5545 T->getAttributeLoc());
5546 if (Result.isNull())
5547 return QualType();
5548 }
5549
5550 // Result might be dependent or not.
5551 if (isa<DependentSizedExtVectorType>(Result)) {
5552 DependentSizedExtVectorTypeLoc NewTL
5553 = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
5554 NewTL.setNameLoc(TL.getNameLoc());
5555 } else {
5556 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5557 NewTL.setNameLoc(TL.getNameLoc());
5558 }
5559
5560 return Result;
5561}
5562
5563template <typename Derived>
5564QualType
5565TreeTransform<Derived>::TransformConstantMatrixType(TypeLocBuilder &TLB,
5566 ConstantMatrixTypeLoc TL) {
5567 const ConstantMatrixType *T = TL.getTypePtr();
5568 QualType ElementType = getDerived().TransformType(T->getElementType());
5569 if (ElementType.isNull())
5570 return QualType();
5571
5572 QualType Result = TL.getType();
5573 if (getDerived().AlwaysRebuild() || ElementType != T->getElementType()) {
5574 Result = getDerived().RebuildConstantMatrixType(
5575 ElementType, T->getNumRows(), T->getNumColumns());
5576 if (Result.isNull())
5577 return QualType();
5578 }
5579
5580 ConstantMatrixTypeLoc NewTL = TLB.push<ConstantMatrixTypeLoc>(Result);
5581 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5582 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5583 NewTL.setAttrRowOperand(TL.getAttrRowOperand());
5584 NewTL.setAttrColumnOperand(TL.getAttrColumnOperand());
5585
5586 return Result;
5587}
5588
5589template <typename Derived>
5590QualType TreeTransform<Derived>::TransformDependentSizedMatrixType(
5591 TypeLocBuilder &TLB, DependentSizedMatrixTypeLoc TL) {
5592 const DependentSizedMatrixType *T = TL.getTypePtr();
5593
5594 QualType ElementType = getDerived().TransformType(T->getElementType());
5595 if (ElementType.isNull()) {
5596 return QualType();
5597 }
5598
5599 // Matrix dimensions are constant expressions.
5600 EnterExpressionEvaluationContext Unevaluated(
5601 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5602
5603 Expr *origRows = TL.getAttrRowOperand();
5604 if (!origRows)
5605 origRows = T->getRowExpr();
5606 Expr *origColumns = TL.getAttrColumnOperand();
5607 if (!origColumns)
5608 origColumns = T->getColumnExpr();
5609
5610 ExprResult rowResult = getDerived().TransformExpr(origRows);
5611 rowResult = SemaRef.ActOnConstantExpression(rowResult);
5612 if (rowResult.isInvalid())
5613 return QualType();
5614
5615 ExprResult columnResult = getDerived().TransformExpr(origColumns);
5616 columnResult = SemaRef.ActOnConstantExpression(columnResult);
5617 if (columnResult.isInvalid())
5618 return QualType();
5619
5620 Expr *rows = rowResult.get();
5621 Expr *columns = columnResult.get();
5622
5623 QualType Result = TL.getType();
5624 if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5625 rows != origRows || columns != origColumns) {
5626 Result = getDerived().RebuildDependentSizedMatrixType(
5627 ElementType, rows, columns, T->getAttributeLoc());
5628
5629 if (Result.isNull())
5630 return QualType();
5631 }
5632
5633 // We might have any sort of matrix type now, but fortunately they
5634 // all have the same location layout.
5635 MatrixTypeLoc NewTL = TLB.push<MatrixTypeLoc>(Result);
5636 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5637 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5638 NewTL.setAttrRowOperand(rows);
5639 NewTL.setAttrColumnOperand(columns);
5640 return Result;
5641}
5642
5643template <typename Derived>
5644QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
5645 TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
5646 const DependentAddressSpaceType *T = TL.getTypePtr();
5647
5648 QualType pointeeType = getDerived().TransformType(T->getPointeeType());
5649
5650 if (pointeeType.isNull())
5651 return QualType();
5652
5653 // Address spaces are constant expressions.
5654 EnterExpressionEvaluationContext Unevaluated(
5655 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5656
5657 ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
5658 AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
5659 if (AddrSpace.isInvalid())
5660 return QualType();
5661
5662 QualType Result = TL.getType();
5663 if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
5664 AddrSpace.get() != T->getAddrSpaceExpr()) {
5665 Result = getDerived().RebuildDependentAddressSpaceType(
5666 pointeeType, AddrSpace.get(), T->getAttributeLoc());
5667 if (Result.isNull())
5668 return QualType();
5669 }
5670
5671 // Result might be dependent or not.
5672 if (isa<DependentAddressSpaceType>(Result)) {
5673 DependentAddressSpaceTypeLoc NewTL =
5674 TLB.push<DependentAddressSpaceTypeLoc>(Result);
5675
5676 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5677 NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5678 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5679
5680 } else {
5681 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5682 Result, getDerived().getBaseLocation());
5683 TransformType(TLB, DI->getTypeLoc());
5684 }
5685
5686 return Result;
5687}
5688
5689template <typename Derived>
5690QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5691 VectorTypeLoc TL) {
5692 const VectorType *T = TL.getTypePtr();
5693 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5694 if (ElementType.isNull())
5695 return QualType();
5696
5697 QualType Result = TL.getType();
5698 if (getDerived().AlwaysRebuild() ||
5699 ElementType != T->getElementType()) {
5700 Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5701 T->getVectorKind());
5702 if (Result.isNull())
5703 return QualType();
5704 }
5705
5706 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5707 NewTL.setNameLoc(TL.getNameLoc());
5708
5709 return Result;
5710}
5711
5712template<typename Derived>
5713QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5714 ExtVectorTypeLoc TL) {
5715 const VectorType *T = TL.getTypePtr();
5716 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5717 if (ElementType.isNull())
5718 return QualType();
5719
5720 QualType Result = TL.getType();
5721 if (getDerived().AlwaysRebuild() ||
5722 ElementType != T->getElementType()) {
5723 Result = getDerived().RebuildExtVectorType(ElementType,
5724 T->getNumElements(),
5725 /*FIXME*/ SourceLocation());
5726 if (Result.isNull())
5727 return QualType();
5728 }
5729
5730 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5731 NewTL.setNameLoc(TL.getNameLoc());
5732
5733 return Result;
5734}
5735
5736template <typename Derived>
5737ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5738 ParmVarDecl *OldParm, int indexAdjustment,
5739 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
5740 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5741 TypeSourceInfo *NewDI = nullptr;
5742
5743 if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5744 // If we're substituting into a pack expansion type and we know the
5745 // length we want to expand to, just substitute for the pattern.
5746 TypeLoc OldTL = OldDI->getTypeLoc();
5747 PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5748
5749 TypeLocBuilder TLB;
5750 TypeLoc NewTL = OldDI->getTypeLoc();
5751 TLB.reserve(NewTL.getFullDataSize());
5752
5753 QualType Result = getDerived().TransformType(TLB,
5754 OldExpansionTL.getPatternLoc());
5755 if (Result.isNull())
5756 return nullptr;
5757
5758 Result = RebuildPackExpansionType(Result,
5759 OldExpansionTL.getPatternLoc().getSourceRange(),
5760 OldExpansionTL.getEllipsisLoc(),
5761 NumExpansions);
5762 if (Result.isNull())
5763 return nullptr;
5764
5765 PackExpansionTypeLoc NewExpansionTL
5766 = TLB.push<PackExpansionTypeLoc>(Result);
5767 NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5768 NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5769 } else
5770 NewDI = getDerived().TransformType(OldDI);
5771 if (!NewDI)
5772 return nullptr;
5773
5774 if (NewDI == OldDI && indexAdjustment == 0)
5775 return OldParm;
5776
5777 ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5778 OldParm->getDeclContext(),
5779 OldParm->getInnerLocStart(),
5780 OldParm->getLocation(),
5781 OldParm->getIdentifier(),
5782 NewDI->getType(),
5783 NewDI,
5784 OldParm->getStorageClass(),
5785 /* DefArg */ nullptr);
5786 newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5787 OldParm->getFunctionScopeIndex() + indexAdjustment);
5788 transformedLocalDecl(OldParm, {newParm});
5789 return newParm;
5790}
5791
5792template <typename Derived>
5793bool TreeTransform<Derived>::TransformFunctionTypeParams(
5794 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5795 const QualType *ParamTypes,
5796 const FunctionProtoType::ExtParameterInfo *ParamInfos,
5797 SmallVectorImpl<QualType> &OutParamTypes,
5798 SmallVectorImpl<ParmVarDecl *> *PVars,
5799 Sema::ExtParameterInfoBuilder &PInfos,
5800 unsigned *LastParamTransformed) {
5801 int indexAdjustment = 0;
5802
5803 unsigned NumParams = Params.size();
5804 for (unsigned i = 0; i != NumParams; ++i) {
5805 if (LastParamTransformed)
5806 *LastParamTransformed = i;
5807 if (ParmVarDecl *OldParm = Params[i]) {
5808 assert(OldParm->getFunctionScopeIndex() == i)(static_cast <bool> (OldParm->getFunctionScopeIndex(
) == i) ? void (0) : __assert_fail ("OldParm->getFunctionScopeIndex() == i"
, "clang/lib/Sema/TreeTransform.h", 5808, __extension__ __PRETTY_FUNCTION__
))
;
5809
5810 std::optional<unsigned> NumExpansions;
5811 ParmVarDecl *NewParm = nullptr;
5812 if (OldParm->isParameterPack()) {
5813 // We have a function parameter pack that may need to be expanded.
5814 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5815
5816 // Find the parameter packs that could be expanded.
5817 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5818 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5819 TypeLoc Pattern = ExpansionTL.getPatternLoc();
5820 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5821
5822 // Determine whether we should expand the parameter packs.
5823 bool ShouldExpand = false;
5824 bool RetainExpansion = false;
5825 std::optional<unsigned> OrigNumExpansions;
5826 if (Unexpanded.size() > 0) {
5827 OrigNumExpansions = ExpansionTL.getTypePtr()->getNumExpansions();
5828 NumExpansions = OrigNumExpansions;
5829 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5830 Pattern.getSourceRange(),
5831 Unexpanded,
5832 ShouldExpand,
5833 RetainExpansion,
5834 NumExpansions)) {
5835 return true;
5836 }
5837 } else {
5838#ifndef NDEBUG
5839 const AutoType *AT =
5840 Pattern.getType().getTypePtr()->getContainedAutoType();
5841 assert((AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) &&(static_cast <bool> ((AT && (!AT->isDeduced(
) || AT->getDeducedType().isNull())) && "Could not find parameter packs or undeduced auto type!"
) ? void (0) : __assert_fail ("(AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) && \"Could not find parameter packs or undeduced auto type!\""
, "clang/lib/Sema/TreeTransform.h", 5842, __extension__ __PRETTY_FUNCTION__
))
5842 "Could not find parameter packs or undeduced auto type!")(static_cast <bool> ((AT && (!AT->isDeduced(
) || AT->getDeducedType().isNull())) && "Could not find parameter packs or undeduced auto type!"
) ? void (0) : __assert_fail ("(AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) && \"Could not find parameter packs or undeduced auto type!\""
, "clang/lib/Sema/TreeTransform.h", 5842, __extension__ __PRETTY_FUNCTION__
))
;
5843#endif
5844 }
5845
5846 if (ShouldExpand) {
5847 // Expand the function parameter pack into multiple, separate
5848 // parameters.
5849 getDerived().ExpandingFunctionParameterPack(OldParm);
5850 for (unsigned I = 0; I != *NumExpansions; ++I) {
5851 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5852 ParmVarDecl *NewParm
5853 = getDerived().TransformFunctionTypeParam(OldParm,
5854 indexAdjustment++,
5855 OrigNumExpansions,
5856 /*ExpectParameterPack=*/false);
5857 if (!NewParm)
5858 return true;
5859
5860 if (ParamInfos)
5861 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5862 OutParamTypes.push_back(NewParm->getType());
5863 if (PVars)
5864 PVars->push_back(NewParm);
5865 }
5866
5867 // If we're supposed to retain a pack expansion, do so by temporarily
5868 // forgetting the partially-substituted parameter pack.
5869 if (RetainExpansion) {
5870 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5871 ParmVarDecl *NewParm
5872 = getDerived().TransformFunctionTypeParam(OldParm,
5873 indexAdjustment++,
5874 OrigNumExpansions,
5875 /*ExpectParameterPack=*/false);
5876 if (!NewParm)
5877 return true;
5878
5879 if (ParamInfos)
5880 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5881 OutParamTypes.push_back(NewParm->getType());
5882 if (PVars)
5883 PVars->push_back(NewParm);
5884 }
5885
5886 // The next parameter should have the same adjustment as the
5887 // last thing we pushed, but we post-incremented indexAdjustment
5888 // on every push. Also, if we push nothing, the adjustment should
5889 // go down by one.
5890 indexAdjustment--;
5891
5892 // We're done with the pack expansion.
5893 continue;
5894 }
5895
5896 // We'll substitute the parameter now without expanding the pack
5897 // expansion.
5898 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5899 NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5900 indexAdjustment,
5901 NumExpansions,
5902 /*ExpectParameterPack=*/true);
5903 assert(NewParm->isParameterPack() &&(static_cast <bool> (NewParm->isParameterPack() &&
"Parameter pack no longer a parameter pack after " "transformation."
) ? void (0) : __assert_fail ("NewParm->isParameterPack() && \"Parameter pack no longer a parameter pack after \" \"transformation.\""
, "clang/lib/Sema/TreeTransform.h", 5905, __extension__ __PRETTY_FUNCTION__
))
5904 "Parameter pack no longer a parameter pack after "(static_cast <bool> (NewParm->isParameterPack() &&
"Parameter pack no longer a parameter pack after " "transformation."
) ? void (0) : __assert_fail ("NewParm->isParameterPack() && \"Parameter pack no longer a parameter pack after \" \"transformation.\""
, "clang/lib/Sema/TreeTransform.h", 5905, __extension__ __PRETTY_FUNCTION__
))
5905 "transformation.")(static_cast <bool> (NewParm->isParameterPack() &&
"Parameter pack no longer a parameter pack after " "transformation."
) ? void (0) : __assert_fail ("NewParm->isParameterPack() && \"Parameter pack no longer a parameter pack after \" \"transformation.\""
, "clang/lib/Sema/TreeTransform.h", 5905, __extension__ __PRETTY_FUNCTION__
))
;
5906 } else {
5907 NewParm = getDerived().TransformFunctionTypeParam(
5908 OldParm, indexAdjustment, std::nullopt,
5909 /*ExpectParameterPack=*/false);
5910 }
5911
5912 if (!NewParm)
5913 return true;
5914
5915 if (ParamInfos)
5916 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5917 OutParamTypes.push_back(NewParm->getType());
5918 if (PVars)
5919 PVars->push_back(NewParm);
5920 continue;
5921 }
5922
5923 // Deal with the possibility that we don't have a parameter
5924 // declaration for this parameter.
5925 assert(ParamTypes)(static_cast <bool> (ParamTypes) ? void (0) : __assert_fail
("ParamTypes", "clang/lib/Sema/TreeTransform.h", 5925, __extension__
__PRETTY_FUNCTION__))
;
5926 QualType OldType = ParamTypes[i];
5927 bool IsPackExpansion = false;
5928 std::optional<unsigned> NumExpansions;
5929 QualType NewType;
5930 if (const PackExpansionType *Expansion
5931 = dyn_cast<PackExpansionType>(OldType)) {
5932 // We have a function parameter pack that may need to be expanded.
5933 QualType Pattern = Expansion->getPattern();
5934 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5935 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5936
5937 // Determine whether we should expand the parameter packs.
5938 bool ShouldExpand = false;
5939 bool RetainExpansion = false;
5940 if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5941 Unexpanded,
5942 ShouldExpand,
5943 RetainExpansion,
5944 NumExpansions)) {
5945 return true;
5946 }
5947
5948 if (ShouldExpand) {
5949 // Expand the function parameter pack into multiple, separate
5950 // parameters.
5951 for (unsigned I = 0; I != *NumExpansions; ++I) {
5952 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5953 QualType NewType = getDerived().TransformType(Pattern);
5954 if (NewType.isNull())
5955 return true;
5956
5957 if (NewType->containsUnexpandedParameterPack()) {
5958 NewType = getSema().getASTContext().getPackExpansionType(
5959 NewType, std::nullopt);
5960
5961 if (NewType.isNull())
5962 return true;
5963 }
5964
5965 if (ParamInfos)
5966 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5967 OutParamTypes.push_back(NewType);
5968 if (PVars)
5969 PVars->push_back(nullptr);
5970 }
5971
5972 // We're done with the pack expansion.
5973 continue;
5974 }
5975
5976 // If we're supposed to retain a pack expansion, do so by temporarily
5977 // forgetting the partially-substituted parameter pack.
5978 if (RetainExpansion) {
5979 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5980 QualType NewType = getDerived().TransformType(Pattern);
5981 if (NewType.isNull())
5982 return true;
5983
5984 if (ParamInfos)
5985 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5986 OutParamTypes.push_back(NewType);
5987 if (PVars)
5988 PVars->push_back(nullptr);
5989 }
5990
5991 // We'll substitute the parameter now without expanding the pack
5992 // expansion.
5993 OldType = Expansion->getPattern();
5994 IsPackExpansion = true;
5995 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5996 NewType = getDerived().TransformType(OldType);
5997 } else {
5998 NewType = getDerived().TransformType(OldType);
5999 }
6000
6001 if (NewType.isNull())
6002 return true;
6003
6004 if (IsPackExpansion)
6005 NewType = getSema().Context.getPackExpansionType(NewType,
6006 NumExpansions);
6007
6008 if (ParamInfos)
6009 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
6010 OutParamTypes.push_back(NewType);
6011 if (PVars)
6012 PVars->push_back(nullptr);
6013 }
6014
6015#ifndef NDEBUG
6016 if (PVars) {
6017 for (unsigned i = 0, e = PVars->size(); i != e; ++i)
6018 if (ParmVarDecl *parm = (*PVars)[i])
6019 assert(parm->getFunctionScopeIndex() == i)(static_cast <bool> (parm->getFunctionScopeIndex() ==
i) ? void (0) : __assert_fail ("parm->getFunctionScopeIndex() == i"
, "clang/lib/Sema/TreeTransform.h", 6019, __extension__ __PRETTY_FUNCTION__
))
;
6020 }
6021#endif
6022
6023 return false;
6024}
6025
6026template<typename Derived>
6027QualType
6028TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
6029 FunctionProtoTypeLoc TL) {
6030 SmallVector<QualType, 4> ExceptionStorage;
6031 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
6032 return getDerived().TransformFunctionProtoType(
6033 TLB, TL, nullptr, Qualifiers(),
6034 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
6035 return This->getDerived().TransformExceptionSpec(
6036 TL.getBeginLoc(), ESI, ExceptionStorage, Changed);
6037 });
6038}
6039
6040template<typename Derived> template<typename Fn>
6041QualType TreeTransform<Derived>::TransformFunctionProtoType(
6042 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
6043 Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
6044
6045 // Transform the parameters and return type.
6046 //
6047 // We are required to instantiate the params and return type in source order.
6048 // When the function has a trailing return type, we instantiate the
6049 // parameters before the return type, since the return type can then refer
6050 // to the parameters themselves (via decltype, sizeof, etc.).
6051 //
6052 SmallVector<QualType, 4> ParamTypes;
6053 SmallVector<ParmVarDecl*, 4> ParamDecls;
6054 Sema::ExtParameterInfoBuilder ExtParamInfos;
6055 const FunctionProtoType *T = TL.getTypePtr();
6056
6057 QualType ResultType;
6058
6059 if (T->hasTrailingReturn()) {
6060 if (getDerived().TransformFunctionTypeParams(
6061 TL.getBeginLoc(), TL.getParams(),
6062 TL.getTypePtr()->param_type_begin(),
6063 T->getExtParameterInfosOrNull(),
6064 ParamTypes, &ParamDecls, ExtParamInfos))
6065 return QualType();
6066
6067 {
6068 // C++11 [expr.prim.general]p3:
6069 // If a declaration declares a member function or member function
6070 // template of a class X, the expression this is a prvalue of type
6071 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6072 // and the end of the function-definition, member-declarator, or
6073 // declarator.
6074 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
6075
6076 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6077 if (ResultType.isNull())
6078 return QualType();
6079 }
6080 }
6081 else {
6082 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6083 if (ResultType.isNull())
6084 return QualType();
6085
6086 if (getDerived().TransformFunctionTypeParams(
6087 TL.getBeginLoc(), TL.getParams(),
6088 TL.getTypePtr()->param_type_begin(),
6089 T->getExtParameterInfosOrNull(),
6090 ParamTypes, &ParamDecls, ExtParamInfos))
6091 return QualType();
6092 }
6093
6094 FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
6095
6096 bool EPIChanged = false;
6097 if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
6098 return QualType();
6099
6100 // Handle extended parameter information.
6101 if (auto NewExtParamInfos =
6102 ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
6103 if (!EPI.ExtParameterInfos ||
6104 llvm::ArrayRef(EPI.ExtParameterInfos, TL.getNumParams()) !=
6105 llvm::ArrayRef(NewExtParamInfos, ParamTypes.size())) {
6106 EPIChanged = true;
6107 }
6108 EPI.ExtParameterInfos = NewExtParamInfos;
6109 } else if (EPI.ExtParameterInfos) {
6110 EPIChanged = true;
6111 EPI.ExtParameterInfos = nullptr;
6112 }
6113
6114 QualType Result = TL.getType();
6115 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
6116 T->getParamTypes() != llvm::ArrayRef(ParamTypes) || EPIChanged) {
6117 Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
6118 if (Result.isNull())
6119 return QualType();
6120 }
6121
6122 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
6123 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6124 NewTL.setLParenLoc(TL.getLParenLoc());
6125 NewTL.setRParenLoc(TL.getRParenLoc());
6126 NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
6127 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6128 for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
6129 NewTL.setParam(i, ParamDecls[i]);
6130
6131 return Result;
6132}
6133
6134template<typename Derived>
6135bool TreeTransform<Derived>::TransformExceptionSpec(
6136 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
6137 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
6138 assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated)(static_cast <bool> (ESI.Type != EST_Uninstantiated &&
ESI.Type != EST_Unevaluated) ? void (0) : __assert_fail ("ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated"
, "clang/lib/Sema/TreeTransform.h", 6138, __extension__ __PRETTY_FUNCTION__
))
;
6139
6140 // Instantiate a dynamic noexcept expression, if any.
6141 if (isComputedNoexcept(ESI.Type)) {
6142 EnterExpressionEvaluationContext Unevaluated(
6143 getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
6144 ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
6145 if (NoexceptExpr.isInvalid())
6146 return true;
6147
6148 ExceptionSpecificationType EST = ESI.Type;
6149 NoexceptExpr =
6150 getSema().ActOnNoexceptSpec(NoexceptExpr.get(), EST);
6151 if (NoexceptExpr.isInvalid())
6152 return true;
6153
6154 if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
6155 Changed = true;
6156 ESI.NoexceptExpr = NoexceptExpr.get();
6157 ESI.Type = EST;
6158 }
6159
6160 if (ESI.Type != EST_Dynamic)
6161 return false;
6162
6163 // Instantiate a dynamic exception specification's type.
6164 for (QualType T : ESI.Exceptions) {
6165 if (const PackExpansionType *PackExpansion =
6166 T->getAs<PackExpansionType>()) {
6167 Changed = true;
6168
6169 // We have a pack expansion. Instantiate it.
6170 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6171 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6172 Unexpanded);
6173 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 6173, __extension__ __PRETTY_FUNCTION__
))
;
6174
6175 // Determine whether the set of unexpanded parameter packs can and
6176 // should
6177 // be expanded.
6178 bool Expand = false;
6179 bool RetainExpansion = false;
6180 std::optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6181 // FIXME: Track the location of the ellipsis (and track source location
6182 // information for the types in the exception specification in general).
6183 if (getDerived().TryExpandParameterPacks(
6184 Loc, SourceRange(), Unexpanded, Expand,
6185 RetainExpansion, NumExpansions))
6186 return true;
6187
6188 if (!Expand) {
6189 // We can't expand this pack expansion into separate arguments yet;
6190 // just substitute into the pattern and create a new pack expansion
6191 // type.
6192 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6193 QualType U = getDerived().TransformType(PackExpansion->getPattern());
6194 if (U.isNull())
6195 return true;
6196
6197 U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
6198 Exceptions.push_back(U);
6199 continue;
6200 }
6201
6202 // Substitute into the pack expansion pattern for each slice of the
6203 // pack.
6204 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6205 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6206
6207 QualType U = getDerived().TransformType(PackExpansion->getPattern());
6208 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6209 return true;
6210
6211 Exceptions.push_back(U);
6212 }
6213 } else {
6214 QualType U = getDerived().TransformType(T);
6215 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6216 return true;
6217 if (T != U)
6218 Changed = true;
6219
6220 Exceptions.push_back(U);
6221 }
6222 }
6223
6224 ESI.Exceptions = Exceptions;
6225 if (ESI.Exceptions.empty())
6226 ESI.Type = EST_DynamicNone;
6227 return false;
6228}
6229
6230template<typename Derived>
6231QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
6232 TypeLocBuilder &TLB,
6233 FunctionNoProtoTypeLoc TL) {
6234 const FunctionNoProtoType *T = TL.getTypePtr();
6235 QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6236 if (ResultType.isNull())
6237 return QualType();
6238
6239 QualType Result = TL.getType();
6240 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
6241 Result = getDerived().RebuildFunctionNoProtoType(ResultType);
6242
6243 FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
6244 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6245 NewTL.setLParenLoc(TL.getLParenLoc());
6246 NewTL.setRParenLoc(TL.getRParenLoc());
6247 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6248
6249 return Result;
6250}
6251
6252template <typename Derived>
6253QualType TreeTransform<Derived>::TransformUnresolvedUsingType(
6254 TypeLocBuilder &TLB, UnresolvedUsingTypeLoc TL) {
6255 const UnresolvedUsingType *T = TL.getTypePtr();
6256 Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
6257 if (!D)
6258 return QualType();
6259
6260 QualType Result = TL.getType();
6261 if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
6262 Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
6263 if (Result.isNull())
6264 return QualType();
6265 }
6266
6267 // We might get an arbitrary type spec type back. We should at
6268 // least always get a type spec type, though.
6269 TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
6270 NewTL.setNameLoc(TL.getNameLoc());
6271
6272 return Result;
6273}
6274
6275template <typename Derived>
6276QualType TreeTransform<Derived>::TransformUsingType(TypeLocBuilder &TLB,
6277 UsingTypeLoc TL) {
6278 const UsingType *T = TL.getTypePtr();
6279
6280 auto *Found = cast_or_null<UsingShadowDecl>(getDerived().TransformDecl(
6281 TL.getLocalSourceRange().getBegin(), T->getFoundDecl()));
6282 if (!Found)
6283 return QualType();
6284
6285 QualType Underlying = getDerived().TransformType(T->desugar());
6286 if (Underlying.isNull())
6287 return QualType();
6288
6289 QualType Result = TL.getType();
6290 if (getDerived().AlwaysRebuild() || Found != T->getFoundDecl() ||
6291 Underlying != T->getUnderlyingType()) {
6292 Result = getDerived().RebuildUsingType(Found, Underlying);
6293 if (Result.isNull())
6294 return QualType();
6295 }
6296
6297 TLB.pushTypeSpec(Result).setNameLoc(TL.getNameLoc());
6298 return Result;
6299}
6300
6301template<typename Derived>
6302QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
6303 TypedefTypeLoc TL) {
6304 const TypedefType *T = TL.getTypePtr();
6305 TypedefNameDecl *Typedef
6306 = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6307 T->getDecl()));
6308 if (!Typedef)
6309 return QualType();
6310
6311 QualType Result = TL.getType();
6312 if (getDerived().AlwaysRebuild() ||
6313 Typedef != T->getDecl()) {
6314 Result = getDerived().RebuildTypedefType(Typedef);
6315 if (Result.isNull())
6316 return QualType();
6317 }
6318
6319 TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
6320 NewTL.setNameLoc(TL.getNameLoc());
6321
6322 return Result;
6323}
6324
6325template<typename Derived>
6326QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
6327 TypeOfExprTypeLoc TL) {
6328 // typeof expressions are not potentially evaluated contexts
6329 EnterExpressionEvaluationContext Unevaluated(
6330 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
6331 Sema::ReuseLambdaContextDecl);
6332
6333 ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
6334 if (E.isInvalid())
6335 return QualType();
6336
6337 E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
6338 if (E.isInvalid())
6339 return QualType();
6340
6341 QualType Result = TL.getType();
6342 TypeOfKind Kind = Result->getAs<TypeOfExprType>()->getKind();
6343 if (getDerived().AlwaysRebuild() || E.get() != TL.getUnderlyingExpr()) {
6344 Result =
6345 getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc(), Kind);
6346 if (Result.isNull())
6347 return QualType();
6348 }
6349
6350 TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
6351 NewTL.setTypeofLoc(TL.getTypeofLoc());
6352 NewTL.setLParenLoc(TL.getLParenLoc());
6353 NewTL.setRParenLoc(TL.getRParenLoc());
6354
6355 return Result;
6356}
6357
6358template<typename Derived>
6359QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
6360 TypeOfTypeLoc TL) {
6361 TypeSourceInfo* Old_Under_TI = TL.getUnmodifiedTInfo();
6362 TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
6363 if (!New_Under_TI)
6364 return QualType();
6365
6366 QualType Result = TL.getType();
6367 TypeOfKind Kind = Result->getAs<TypeOfType>()->getKind();
6368 if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
6369 Result = getDerived().RebuildTypeOfType(New_Under_TI->getType(), Kind);
6370 if (Result.isNull())
6371 return QualType();
6372 }
6373
6374 TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
6375 NewTL.setTypeofLoc(TL.getTypeofLoc());
6376 NewTL.setLParenLoc(TL.getLParenLoc());
6377 NewTL.setRParenLoc(TL.getRParenLoc());
6378 NewTL.setUnmodifiedTInfo(New_Under_TI);
6379
6380 return Result;
6381}
6382
6383template<typename Derived>
6384QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
6385 DecltypeTypeLoc TL) {
6386 const DecltypeType *T = TL.getTypePtr();
6387
6388 // decltype expressions are not potentially evaluated contexts
6389 EnterExpressionEvaluationContext Unevaluated(
6390 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
6391 Sema::ExpressionEvaluationContextRecord::EK_Decltype);
6392
6393 ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
6394 if (E.isInvalid())
6395 return QualType();
6396
6397 E = getSema().ActOnDecltypeExpression(E.get());
6398 if (E.isInvalid())
6399 return QualType();
6400
6401 QualType Result = TL.getType();
6402 if (getDerived().AlwaysRebuild() ||
6403 E.get() != T->getUnderlyingExpr()) {
6404 Result = getDerived().RebuildDecltypeType(E.get(), TL.getDecltypeLoc());
6405 if (Result.isNull())
6406 return QualType();
6407 }
6408 else E.get();
6409
6410 DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
6411 NewTL.setDecltypeLoc(TL.getDecltypeLoc());
6412 NewTL.setRParenLoc(TL.getRParenLoc());
6413 return Result;
6414}
6415
6416template<typename Derived>
6417QualType TreeTransform<Derived>::TransformUnaryTransformType(
6418 TypeLocBuilder &TLB,
6419 UnaryTransformTypeLoc TL) {
6420 QualType Result = TL.getType();
6421 if (Result->isDependentType()) {
6422 const UnaryTransformType *T = TL.getTypePtr();
6423 QualType NewBase =
6424 getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
6425 Result = getDerived().RebuildUnaryTransformType(NewBase,
6426 T->getUTTKind(),
6427 TL.getKWLoc());
6428 if (Result.isNull())
6429 return QualType();
6430 }
6431
6432 UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
6433 NewTL.setKWLoc(TL.getKWLoc());
6434 NewTL.setParensRange(TL.getParensRange());
6435 NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
6436 return Result;
6437}
6438
6439template<typename Derived>
6440QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
6441 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
6442 const DeducedTemplateSpecializationType *T = TL.getTypePtr();
6443
6444 CXXScopeSpec SS;
6445 TemplateName TemplateName = getDerived().TransformTemplateName(
6446 SS, T->getTemplateName(), TL.getTemplateNameLoc());
6447 if (TemplateName.isNull())
6448 return QualType();
6449
6450 QualType OldDeduced = T->getDeducedType();
6451 QualType NewDeduced;
6452 if (!OldDeduced.isNull()) {
6453 NewDeduced = getDerived().TransformType(OldDeduced);
6454 if (NewDeduced.isNull())
6455 return QualType();
6456 }
6457
6458 QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
6459 TemplateName, NewDeduced);
6460 if (Result.isNull())
6461 return QualType();
6462
6463 DeducedTemplateSpecializationTypeLoc NewTL =
6464 TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
6465 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6466
6467 return Result;
6468}
6469
6470template<typename Derived>
6471QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
6472 RecordTypeLoc TL) {
6473 const RecordType *T = TL.getTypePtr();
6474 RecordDecl *Record
6475 = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6476 T->getDecl()));
6477 if (!Record)
6478 return QualType();
6479
6480 QualType Result = TL.getType();
6481 if (getDerived().AlwaysRebuild() ||
6482 Record != T->getDecl()) {
6483 Result = getDerived().RebuildRecordType(Record);
6484 if (Result.isNull())
6485 return QualType();
6486 }
6487
6488 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
6489 NewTL.setNameLoc(TL.getNameLoc());
6490
6491 return Result;
6492}
6493
6494template<typename Derived>
6495QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
6496 EnumTypeLoc TL) {
6497 const EnumType *T = TL.getTypePtr();
6498 EnumDecl *Enum
6499 = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6500 T->getDecl()));
6501 if (!Enum)
6502 return QualType();
6503
6504 QualType Result = TL.getType();
6505 if (getDerived().AlwaysRebuild() ||
6506 Enum != T->getDecl()) {
6507 Result = getDerived().RebuildEnumType(Enum);
6508 if (Result.isNull())
6509 return QualType();
6510 }
6511
6512 EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
6513 NewTL.setNameLoc(TL.getNameLoc());
6514
6515 return Result;
6516}
6517
6518template<typename Derived>
6519QualType TreeTransform<Derived>::TransformInjectedClassNameType(
6520 TypeLocBuilder &TLB,
6521 InjectedClassNameTypeLoc TL) {
6522 Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
6523 TL.getTypePtr()->getDecl());
6524 if (!D) return QualType();
6525
6526 QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
6527 TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
6528 return T;
6529}
6530
6531template<typename Derived>
6532QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6533 TypeLocBuilder &TLB,
6534 TemplateTypeParmTypeLoc TL) {
6535 return getDerived().TransformTemplateTypeParmType(
6536 TLB, TL,
6537 /*SuppressObjCLifetime=*/false);
6538}
6539
6540template <typename Derived>
6541QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6542 TypeLocBuilder &TLB, TemplateTypeParmTypeLoc TL, bool) {
6543 return TransformTypeSpecType(TLB, TL);
6544}
6545
6546template<typename Derived>
6547QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
6548 TypeLocBuilder &TLB,
6549 SubstTemplateTypeParmTypeLoc TL) {
6550 const SubstTemplateTypeParmType *T = TL.getTypePtr();
6551
6552 Decl *NewReplaced =
6553 getDerived().TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
6554
6555 // Substitute into the replacement type, which itself might involve something
6556 // that needs to be transformed. This only tends to occur with default
6557 // template arguments of template template parameters.
6558 TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
6559 QualType Replacement = getDerived().TransformType(T->getReplacementType());
6560 if (Replacement.isNull())
6561 return QualType();
6562
6563 QualType Result = SemaRef.Context.getSubstTemplateTypeParmType(
6564 Replacement, NewReplaced, T->getIndex(), T->getPackIndex());
6565
6566 // Propagate type-source information.
6567 SubstTemplateTypeParmTypeLoc NewTL
6568 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
6569 NewTL.setNameLoc(TL.getNameLoc());
6570 return Result;
6571
6572}
6573
6574template<typename Derived>
6575QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6576 TypeLocBuilder &TLB,
6577 SubstTemplateTypeParmPackTypeLoc TL) {
6578 return getDerived().TransformSubstTemplateTypeParmPackType(
6579 TLB, TL, /*SuppressObjCLifetime=*/false);
6580}
6581
6582template <typename Derived>
6583QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6584 TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL, bool) {
6585 return TransformTypeSpecType(TLB, TL);
6586}
6587
6588template<typename Derived>
6589QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6590 TypeLocBuilder &TLB,
6591 TemplateSpecializationTypeLoc TL) {
6592 const TemplateSpecializationType *T = TL.getTypePtr();
6593
6594 // The nested-name-specifier never matters in a TemplateSpecializationType,
6595 // because we can't have a dependent nested-name-specifier anyway.
6596 CXXScopeSpec SS;
6597 TemplateName Template
6598 = getDerived().TransformTemplateName(SS, T->getTemplateName(),
6599 TL.getTemplateNameLoc());
6600 if (Template.isNull())
6601 return QualType();
6602
6603 return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
6604}
6605
6606template<typename Derived>
6607QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
6608 AtomicTypeLoc TL) {
6609 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6610 if (ValueType.isNull())
6611 return QualType();
6612
6613 QualType Result = TL.getType();
6614 if (getDerived().AlwaysRebuild() ||
6615 ValueType != TL.getValueLoc().getType()) {
6616 Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
6617 if (Result.isNull())
6618 return QualType();
6619 }
6620
6621 AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
6622 NewTL.setKWLoc(TL.getKWLoc());
6623 NewTL.setLParenLoc(TL.getLParenLoc());
6624 NewTL.setRParenLoc(TL.getRParenLoc());
6625
6626 return Result;
6627}
6628
6629template <typename Derived>
6630QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
6631 PipeTypeLoc TL) {
6632 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6633 if (ValueType.isNull())
6634 return QualType();
6635
6636 QualType Result = TL.getType();
6637 if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
6638 const PipeType *PT = Result->castAs<PipeType>();
6639 bool isReadPipe = PT->isReadOnly();
6640 Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
6641 if (Result.isNull())
6642 return QualType();
6643 }
6644
6645 PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
6646 NewTL.setKWLoc(TL.getKWLoc());
6647
6648 return Result;
6649}
6650
6651template <typename Derived>
6652QualType TreeTransform<Derived>::TransformBitIntType(TypeLocBuilder &TLB,
6653 BitIntTypeLoc TL) {
6654 const BitIntType *EIT = TL.getTypePtr();
6655 QualType Result = TL.getType();
6656
6657 if (getDerived().AlwaysRebuild()) {
6658 Result = getDerived().RebuildBitIntType(EIT->isUnsigned(),
6659 EIT->getNumBits(), TL.getNameLoc());
6660 if (Result.isNull())
6661 return QualType();
6662 }
6663
6664 BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6665 NewTL.setNameLoc(TL.getNameLoc());
6666 return Result;
6667}
6668
6669template <typename Derived>
6670QualType TreeTransform<Derived>::TransformDependentBitIntType(
6671 TypeLocBuilder &TLB, DependentBitIntTypeLoc TL) {
6672 const DependentBitIntType *EIT = TL.getTypePtr();
6673
6674 EnterExpressionEvaluationContext Unevaluated(
6675 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6676 ExprResult BitsExpr = getDerived().TransformExpr(EIT->getNumBitsExpr());
6677 BitsExpr = SemaRef.ActOnConstantExpression(BitsExpr);
6678
6679 if (BitsExpr.isInvalid())
6680 return QualType();
6681
6682 QualType Result = TL.getType();
6683
6684 if (getDerived().AlwaysRebuild() || BitsExpr.get() != EIT->getNumBitsExpr()) {
6685 Result = getDerived().RebuildDependentBitIntType(
6686 EIT->isUnsigned(), BitsExpr.get(), TL.getNameLoc());
6687
6688 if (Result.isNull())
6689 return QualType();
6690 }
6691
6692 if (isa<DependentBitIntType>(Result)) {
6693 DependentBitIntTypeLoc NewTL = TLB.push<DependentBitIntTypeLoc>(Result);
6694 NewTL.setNameLoc(TL.getNameLoc());
6695 } else {
6696 BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6697 NewTL.setNameLoc(TL.getNameLoc());
6698 }
6699 return Result;
6700}
6701
6702 /// Simple iterator that traverses the template arguments in a
6703 /// container that provides a \c getArgLoc() member function.
6704 ///
6705 /// This iterator is intended to be used with the iterator form of
6706 /// \c TreeTransform<Derived>::TransformTemplateArguments().
6707 template<typename ArgLocContainer>
6708 class TemplateArgumentLocContainerIterator {
6709 ArgLocContainer *Container;
6710 unsigned Index;
6711
6712 public:
6713 typedef TemplateArgumentLoc value_type;
6714 typedef TemplateArgumentLoc reference;
6715 typedef int difference_type;
6716 typedef std::input_iterator_tag iterator_category;
6717
6718 class pointer {
6719 TemplateArgumentLoc Arg;
6720
6721 public:
6722 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
6723
6724 const TemplateArgumentLoc *operator->() const {
6725 return &Arg;
6726 }
6727 };
6728
6729
6730 TemplateArgumentLocContainerIterator() {}
6731
6732 TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
6733 unsigned Index)
6734 : Container(&Container), Index(Index) { }
6735
6736 TemplateArgumentLocContainerIterator &operator++() {
6737 ++Index;
6738 return *this;
6739 }
6740
6741 TemplateArgumentLocContainerIterator operator++(int) {
6742 TemplateArgumentLocContainerIterator Old(*this);
6743 ++(*this);
6744 return Old;
6745 }
6746
6747 TemplateArgumentLoc operator*() const {
6748 return Container->getArgLoc(Index);
6749 }
6750
6751 pointer operator->() const {
6752 return pointer(Container->getArgLoc(Index));
6753 }
6754
6755 friend bool operator==(const TemplateArgumentLocContainerIterator &X,
6756 const TemplateArgumentLocContainerIterator &Y) {
6757 return X.Container == Y.Container && X.Index == Y.Index;
6758 }
6759
6760 friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6761 const TemplateArgumentLocContainerIterator &Y) {
6762 return !(X == Y);
6763 }
6764 };
6765
6766template<typename Derived>
6767QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
6768 AutoTypeLoc TL) {
6769 const AutoType *T = TL.getTypePtr();
6770 QualType OldDeduced = T->getDeducedType();
6771 QualType NewDeduced;
6772 if (!OldDeduced.isNull()) {
6773 NewDeduced = getDerived().TransformType(OldDeduced);
6774 if (NewDeduced.isNull())
6775 return QualType();
6776 }
6777
6778 ConceptDecl *NewCD = nullptr;
6779 TemplateArgumentListInfo NewTemplateArgs;
6780 NestedNameSpecifierLoc NewNestedNameSpec;
6781 if (T->isConstrained()) {
6782 NewCD = cast_or_null<ConceptDecl>(getDerived().TransformDecl(
6783 TL.getConceptNameLoc(), T->getTypeConstraintConcept()));
6784
6785 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6786 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6787 typedef TemplateArgumentLocContainerIterator<AutoTypeLoc> ArgIterator;
6788 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6789 ArgIterator(TL,
6790 TL.getNumArgs()),
6791 NewTemplateArgs))
6792 return QualType();
6793
6794 if (TL.getNestedNameSpecifierLoc()) {
6795 NewNestedNameSpec
6796 = getDerived().TransformNestedNameSpecifierLoc(
6797 TL.getNestedNameSpecifierLoc());
6798 if (!NewNestedNameSpec)
6799 return QualType();
6800 }
6801 }
6802
6803 QualType Result = TL.getType();
6804 if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
6805 T->isDependentType() || T->isConstrained()) {
6806 // FIXME: Maybe don't rebuild if all template arguments are the same.
6807 llvm::SmallVector<TemplateArgument, 4> NewArgList;
6808 NewArgList.reserve(NewTemplateArgs.size());
6809 for (const auto &ArgLoc : NewTemplateArgs.arguments())
6810 NewArgList.push_back(ArgLoc.getArgument());
6811 Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword(), NewCD,
6812 NewArgList);
6813 if (Result.isNull())
6814 return QualType();
6815 }
6816
6817 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
6818 NewTL.setNameLoc(TL.getNameLoc());
6819 NewTL.setNestedNameSpecifierLoc(NewNestedNameSpec);
6820 NewTL.setTemplateKWLoc(TL.getTemplateKWLoc());
6821 NewTL.setConceptNameLoc(TL.getConceptNameLoc());
6822 NewTL.setFoundDecl(TL.getFoundDecl());
6823 NewTL.setLAngleLoc(TL.getLAngleLoc());
6824 NewTL.setRAngleLoc(TL.getRAngleLoc());
6825 NewTL.setRParenLoc(TL.getRParenLoc());
6826 for (unsigned I = 0; I < NewTL.getNumArgs(); ++I)
6827 NewTL.setArgLocInfo(I, NewTemplateArgs.arguments()[I].getLocInfo());
6828
6829 return Result;
6830}
6831
6832template <typename Derived>
6833QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6834 TypeLocBuilder &TLB,
6835 TemplateSpecializationTypeLoc TL,
6836 TemplateName Template) {
6837 TemplateArgumentListInfo NewTemplateArgs;
6838 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6839 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6840 typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6841 ArgIterator;
6842 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6843 ArgIterator(TL, TL.getNumArgs()),
6844 NewTemplateArgs))
6845 return QualType();
6846
6847 // FIXME: maybe don't rebuild if all the template arguments are the same.
6848
6849 QualType Result =
6850 getDerived().RebuildTemplateSpecializationType(Template,
6851 TL.getTemplateNameLoc(),
6852 NewTemplateArgs);
6853
6854 if (!Result.isNull()) {
6855 // Specializations of template template parameters are represented as
6856 // TemplateSpecializationTypes, and substitution of type alias templates
6857 // within a dependent context can transform them into
6858 // DependentTemplateSpecializationTypes.
6859 if (isa<DependentTemplateSpecializationType>(Result)) {
6860 DependentTemplateSpecializationTypeLoc NewTL
6861 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6862 NewTL.setElaboratedKeywordLoc(SourceLocation());
6863 NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6864 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6865 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6866 NewTL.setLAngleLoc(TL.getLAngleLoc());
6867 NewTL.setRAngleLoc(TL.getRAngleLoc());
6868 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6869 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6870 return Result;
6871 }
6872
6873 TemplateSpecializationTypeLoc NewTL
6874 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6875 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6876 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6877 NewTL.setLAngleLoc(TL.getLAngleLoc());
6878 NewTL.setRAngleLoc(TL.getRAngleLoc());
6879 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6880 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6881 }
6882
6883 return Result;
6884}
6885
6886template <typename Derived>
6887QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6888 TypeLocBuilder &TLB,
6889 DependentTemplateSpecializationTypeLoc TL,
6890 TemplateName Template,
6891 CXXScopeSpec &SS) {
6892 TemplateArgumentListInfo NewTemplateArgs;
6893 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6894 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6895 typedef TemplateArgumentLocContainerIterator<
6896 DependentTemplateSpecializationTypeLoc> ArgIterator;
6897 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6898 ArgIterator(TL, TL.getNumArgs()),
6899 NewTemplateArgs))
6900 return QualType();
6901
6902 // FIXME: maybe don't rebuild if all the template arguments are the same.
6903
6904 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6905 QualType Result = getSema().Context.getDependentTemplateSpecializationType(
6906 TL.getTypePtr()->getKeyword(), DTN->getQualifier(),
6907 DTN->getIdentifier(), NewTemplateArgs.arguments());
6908
6909 DependentTemplateSpecializationTypeLoc NewTL
6910 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6911 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6912 NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6913 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6914 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6915 NewTL.setLAngleLoc(TL.getLAngleLoc());
6916 NewTL.setRAngleLoc(TL.getRAngleLoc());
6917 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6918 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6919 return Result;
6920 }
6921
6922 QualType Result
6923 = getDerived().RebuildTemplateSpecializationType(Template,
6924 TL.getTemplateNameLoc(),
6925 NewTemplateArgs);
6926
6927 if (!Result.isNull()) {
6928 /// FIXME: Wrap this in an elaborated-type-specifier?
6929 TemplateSpecializationTypeLoc NewTL
6930 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6931 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6932 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6933 NewTL.setLAngleLoc(TL.getLAngleLoc());
6934 NewTL.setRAngleLoc(TL.getRAngleLoc());
6935 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6936 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6937 }
6938
6939 return Result;
6940}
6941
6942template<typename Derived>
6943QualType
6944TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6945 ElaboratedTypeLoc TL) {
6946 const ElaboratedType *T = TL.getTypePtr();
6947
6948 NestedNameSpecifierLoc QualifierLoc;
6949 // NOTE: the qualifier in an ElaboratedType is optional.
6950 if (TL.getQualifierLoc()) {
6951 QualifierLoc
6952 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6953 if (!QualifierLoc)
6954 return QualType();
6955 }
6956
6957 QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6958 if (NamedT.isNull())
6959 return QualType();
6960
6961 // C++0x [dcl.type.elab]p2:
6962 // If the identifier resolves to a typedef-name or the simple-template-id
6963 // resolves to an alias template specialization, the
6964 // elaborated-type-specifier is ill-formed.
6965 if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6966 if (const TemplateSpecializationType *TST =
6967 NamedT->getAs<TemplateSpecializationType>()) {
6968 TemplateName Template = TST->getTemplateName();
6969 if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6970 Template.getAsTemplateDecl())) {
6971 SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6972 diag::err_tag_reference_non_tag)
6973 << TAT << Sema::NTK_TypeAliasTemplate
6974 << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6975 SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6976 }
6977 }
6978 }
6979
6980 QualType Result = TL.getType();
6981 if (getDerived().AlwaysRebuild() ||
6982 QualifierLoc != TL.getQualifierLoc() ||
6983 NamedT != T->getNamedType()) {
6984 Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6985 T->getKeyword(),
6986 QualifierLoc, NamedT);
6987 if (Result.isNull())
6988 return QualType();
6989 }
6990
6991 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6992 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6993 NewTL.setQualifierLoc(QualifierLoc);
6994 return Result;
6995}
6996
6997template<typename Derived>
6998QualType TreeTransform<Derived>::TransformAttributedType(
6999 TypeLocBuilder &TLB,
7000 AttributedTypeLoc TL) {
7001 const AttributedType *oldType = TL.getTypePtr();
7002 QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
7003 if (modifiedType.isNull())
7004 return QualType();
7005
7006 // oldAttr can be null if we started with a QualType rather than a TypeLoc.
7007 const Attr *oldAttr = TL.getAttr();
7008 const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
7009 if (oldAttr && !newAttr)
7010 return QualType();
7011
7012 QualType result = TL.getType();
7013
7014 // FIXME: dependent operand expressions?
7015 if (getDerived().AlwaysRebuild() ||
7016 modifiedType != oldType->getModifiedType()) {
7017 // TODO: this is really lame; we should really be rebuilding the
7018 // equivalent type from first principles.
7019 QualType equivalentType
7020 = getDerived().TransformType(oldType->getEquivalentType());
7021 if (equivalentType.isNull())
7022 return QualType();
7023
7024 // Check whether we can add nullability; it is only represented as
7025 // type sugar, and therefore cannot be diagnosed in any other way.
7026 if (auto nullability = oldType->getImmediateNullability()) {
7027 if (!modifiedType->canHaveNullability()) {
7028 SemaRef.Diag((TL.getAttr() ? TL.getAttr()->getLocation()
7029 : TL.getModifiedLoc().getBeginLoc()),
7030 diag::err_nullability_nonpointer)
7031 << DiagNullabilityKind(*nullability, false) << modifiedType;
7032 return QualType();
7033 }
7034 }
7035
7036 result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
7037 modifiedType,
7038 equivalentType);
7039 }
7040
7041 AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
7042 newTL.setAttr(newAttr);
7043 return result;
7044}
7045
7046template <typename Derived>
7047QualType TreeTransform<Derived>::TransformBTFTagAttributedType(
7048 TypeLocBuilder &TLB, BTFTagAttributedTypeLoc TL) {
7049 // The BTFTagAttributedType is available for C only.
7050 llvm_unreachable("Unexpected TreeTransform for BTFTagAttributedType")::llvm::llvm_unreachable_internal("Unexpected TreeTransform for BTFTagAttributedType"
, "clang/lib/Sema/TreeTransform.h", 7050)
;
7051}
7052
7053template<typename Derived>
7054QualType
7055TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
7056 ParenTypeLoc TL) {
7057 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
7058 if (Inner.isNull())
7059 return QualType();
7060
7061 QualType Result = TL.getType();
7062 if (getDerived().AlwaysRebuild() ||
7063 Inner != TL.getInnerLoc().getType()) {
7064 Result = getDerived().RebuildParenType(Inner);
7065 if (Result.isNull())
7066 return QualType();
7067 }
7068
7069 ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
7070 NewTL.setLParenLoc(TL.getLParenLoc());
7071 NewTL.setRParenLoc(TL.getRParenLoc());
7072 return Result;
7073}
7074
7075template <typename Derived>
7076QualType
7077TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
7078 MacroQualifiedTypeLoc TL) {
7079 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
7080 if (Inner.isNull())
7081 return QualType();
7082
7083 QualType Result = TL.getType();
7084 if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
7085 Result =
7086 getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
7087 if (Result.isNull())
7088 return QualType();
7089 }
7090
7091 MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
7092 NewTL.setExpansionLoc(TL.getExpansionLoc());
7093 return Result;
7094}
7095
7096template<typename Derived>
7097QualType TreeTransform<Derived>::TransformDependentNameType(
7098 TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
7099 return TransformDependentNameType(TLB, TL, false);
7100}
7101
7102template<typename Derived>
7103QualType TreeTransform<Derived>::TransformDependentNameType(
7104 TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
7105 const DependentNameType *T = TL.getTypePtr();
7106
7107 NestedNameSpecifierLoc QualifierLoc
7108 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
7109 if (!QualifierLoc)
7110 return QualType();
7111
7112 QualType Result
7113 = getDerived().RebuildDependentNameType(T->getKeyword(),
7114 TL.getElaboratedKeywordLoc(),
7115 QualifierLoc,
7116 T->getIdentifier(),
7117 TL.getNameLoc(),
7118 DeducedTSTContext);
7119 if (Result.isNull())
7120 return QualType();
7121
7122 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
7123 QualType NamedT = ElabT->getNamedType();
7124 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
7125
7126 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7127 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7128 NewTL.setQualifierLoc(QualifierLoc);
7129 } else {
7130 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
7131 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7132 NewTL.setQualifierLoc(QualifierLoc);
7133 NewTL.setNameLoc(TL.getNameLoc());
7134 }
7135 return Result;
7136}
7137
7138template<typename Derived>
7139QualType TreeTransform<Derived>::
7140 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
7141 DependentTemplateSpecializationTypeLoc TL) {
7142 NestedNameSpecifierLoc QualifierLoc;
7143 if (TL.getQualifierLoc()) {
7144 QualifierLoc
7145 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
7146 if (!QualifierLoc)
7147 return QualType();
7148 }
7149
7150 return getDerived()
7151 .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
7152}
7153
7154template<typename Derived>
7155QualType TreeTransform<Derived>::
7156TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
7157 DependentTemplateSpecializationTypeLoc TL,
7158 NestedNameSpecifierLoc QualifierLoc) {
7159 const DependentTemplateSpecializationType *T = TL.getTypePtr();
7160
7161 TemplateArgumentListInfo NewTemplateArgs;
7162 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
7163 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
7164
7165 typedef TemplateArgumentLocContainerIterator<
7166 DependentTemplateSpecializationTypeLoc> ArgIterator;
7167 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
7168 ArgIterator(TL, TL.getNumArgs()),
7169 NewTemplateArgs))
7170 return QualType();
7171
7172 QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
7173 T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
7174 T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
7175 /*AllowInjectedClassName*/ false);
7176 if (Result.isNull())
7177 return QualType();
7178
7179 if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
7180 QualType NamedT = ElabT->getNamedType();
7181
7182 // Copy information relevant to the template specialization.
7183 TemplateSpecializationTypeLoc NamedTL
7184 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
7185 NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7186 NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7187 NamedTL.setLAngleLoc(TL.getLAngleLoc());
7188 NamedTL.setRAngleLoc(TL.getRAngleLoc());
7189 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7190 NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7191
7192 // Copy information relevant to the elaborated type.
7193 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7194 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7195 NewTL.setQualifierLoc(QualifierLoc);
7196 } else if (isa<DependentTemplateSpecializationType>(Result)) {
7197 DependentTemplateSpecializationTypeLoc SpecTL
7198 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
7199 SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7200 SpecTL.setQualifierLoc(QualifierLoc);
7201 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7202 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7203 SpecTL.setLAngleLoc(TL.getLAngleLoc());
7204 SpecTL.setRAngleLoc(TL.getRAngleLoc());
7205 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7206 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7207 } else {
7208 TemplateSpecializationTypeLoc SpecTL
7209 = TLB.push<TemplateSpecializationTypeLoc>(Result);
7210 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7211 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7212 SpecTL.setLAngleLoc(TL.getLAngleLoc());
7213 SpecTL.setRAngleLoc(TL.getRAngleLoc());
7214 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7215 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7216 }
7217 return Result;
7218}
7219
7220template<typename Derived>
7221QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
7222 PackExpansionTypeLoc TL) {
7223 QualType Pattern
7224 = getDerived().TransformType(TLB, TL.getPatternLoc());
7225 if (Pattern.isNull())
7226 return QualType();
7227
7228 QualType Result = TL.getType();
7229 if (getDerived().AlwaysRebuild() ||
7230 Pattern != TL.getPatternLoc().getType()) {
7231 Result = getDerived().RebuildPackExpansionType(Pattern,
7232 TL.getPatternLoc().getSourceRange(),
7233 TL.getEllipsisLoc(),
7234 TL.getTypePtr()->getNumExpansions());
7235 if (Result.isNull())
7236 return QualType();
7237 }
7238
7239 PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
7240 NewT.setEllipsisLoc(TL.getEllipsisLoc());
7241 return Result;
7242}
7243
7244template<typename Derived>
7245QualType
7246TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
7247 ObjCInterfaceTypeLoc TL) {
7248 // ObjCInterfaceType is never dependent.
7249 TLB.pushFullCopy(TL);
7250 return TL.getType();
7251}
7252
7253template<typename Derived>
7254QualType
7255TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
7256 ObjCTypeParamTypeLoc TL) {
7257 const ObjCTypeParamType *T = TL.getTypePtr();
7258 ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
7259 getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
7260 if (!OTP)
7261 return QualType();
7262
7263 QualType Result = TL.getType();
7264 if (getDerived().AlwaysRebuild() ||
7265 OTP != T->getDecl()) {
7266 Result = getDerived().RebuildObjCTypeParamType(
7267 OTP, TL.getProtocolLAngleLoc(),
7268 llvm::ArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7269 TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7270 if (Result.isNull())
7271 return QualType();
7272 }
7273
7274 ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
7275 if (TL.getNumProtocols()) {
7276 NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7277 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7278 NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
7279 NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7280 }
7281 return Result;
7282}
7283
7284template<typename Derived>
7285QualType
7286TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
7287 ObjCObjectTypeLoc TL) {
7288 // Transform base type.
7289 QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
7290 if (BaseType.isNull())
7291 return QualType();
7292
7293 bool AnyChanged = BaseType != TL.getBaseLoc().getType();
7294
7295 // Transform type arguments.
7296 SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
7297 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
7298 TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
7299 TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
7300 QualType TypeArg = TypeArgInfo->getType();
7301 if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
7302 AnyChanged = true;
7303
7304 // We have a pack expansion. Instantiate it.
7305 const auto *PackExpansion = PackExpansionLoc.getType()
7306 ->castAs<PackExpansionType>();
7307 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
7308 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
7309 Unexpanded);
7310 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 7310, __extension__ __PRETTY_FUNCTION__
))
;
7311
7312 // Determine whether the set of unexpanded parameter packs can
7313 // and should be expanded.
7314 TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
7315 bool Expand = false;
7316 bool RetainExpansion = false;
7317 std::optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
7318 if (getDerived().TryExpandParameterPacks(
7319 PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
7320 Unexpanded, Expand, RetainExpansion, NumExpansions))
7321 return QualType();
7322
7323 if (!Expand) {
7324 // We can't expand this pack expansion into separate arguments yet;
7325 // just substitute into the pattern and create a new pack expansion
7326 // type.
7327 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
7328
7329 TypeLocBuilder TypeArgBuilder;
7330 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7331 QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
7332 PatternLoc);
7333 if (NewPatternType.isNull())
7334 return QualType();
7335
7336 QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
7337 NewPatternType, NumExpansions);
7338 auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
7339 NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
7340 NewTypeArgInfos.push_back(
7341 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
7342 continue;
7343 }
7344
7345 // Substitute into the pack expansion pattern for each slice of the
7346 // pack.
7347 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
7348 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
7349
7350 TypeLocBuilder TypeArgBuilder;
7351 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7352
7353 QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
7354 PatternLoc);
7355 if (NewTypeArg.isNull())
7356 return QualType();
7357
7358 NewTypeArgInfos.push_back(
7359 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7360 }
7361
7362 continue;
7363 }
7364
7365 TypeLocBuilder TypeArgBuilder;
7366 TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
7367 QualType NewTypeArg =
7368 getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
7369 if (NewTypeArg.isNull())
7370 return QualType();
7371
7372 // If nothing changed, just keep the old TypeSourceInfo.
7373 if (NewTypeArg == TypeArg) {
7374 NewTypeArgInfos.push_back(TypeArgInfo);
7375 continue;
7376 }
7377
7378 NewTypeArgInfos.push_back(
7379 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7380 AnyChanged = true;
7381 }
7382
7383 QualType Result = TL.getType();
7384 if (getDerived().AlwaysRebuild() || AnyChanged) {
7385 // Rebuild the type.
7386 Result = getDerived().RebuildObjCObjectType(
7387 BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
7388 TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
7389 llvm::ArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7390 TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7391
7392 if (Result.isNull())
7393 return QualType();
7394 }
7395
7396 ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
7397 NewT.setHasBaseTypeAsWritten(true);
7398 NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
7399 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
7400 NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
7401 NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
7402 NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7403 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7404 NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
7405 NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7406 return Result;
7407}
7408
7409template<typename Derived>
7410QualType
7411TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
7412 ObjCObjectPointerTypeLoc TL) {
7413 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
7414 if (PointeeType.isNull())
7415 return QualType();
7416
7417 QualType Result = TL.getType();
7418 if (getDerived().AlwaysRebuild() ||
7419 PointeeType != TL.getPointeeLoc().getType()) {
7420 Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
7421 TL.getStarLoc());
7422 if (Result.isNull())
7423 return QualType();
7424 }
7425
7426 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
7427 NewT.setStarLoc(TL.getStarLoc());
7428 return Result;
7429}
7430
7431//===----------------------------------------------------------------------===//
7432// Statement transformation
7433//===----------------------------------------------------------------------===//
7434template<typename Derived>
7435StmtResult
7436TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
7437 return S;
7438}
7439
7440template<typename Derived>
7441StmtResult
7442TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
7443 return getDerived().TransformCompoundStmt(S, false);
7444}
7445
7446template<typename Derived>
7447StmtResult
7448TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
7449 bool IsStmtExpr) {
7450 Sema::CompoundScopeRAII CompoundScope(getSema());
7451
7452 const Stmt *ExprResult = S->getStmtExprResult();
7453 bool SubStmtInvalid = false;
7454 bool SubStmtChanged = false;
7455 SmallVector<Stmt*, 8> Statements;
7456 for (auto *B : S->body()) {
7457 StmtResult Result = getDerived().TransformStmt(
7458 B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
7459
7460 if (Result.isInvalid()) {
7461 // Immediately fail if this was a DeclStmt, since it's very
7462 // likely that this will cause problems for future statements.
7463 if (isa<DeclStmt>(B))
7464 return StmtError();
7465
7466 // Otherwise, just keep processing substatements and fail later.
7467 SubStmtInvalid = true;
7468 continue;
7469 }
7470
7471 SubStmtChanged = SubStmtChanged || Result.get() != B;
7472 Statements.push_back(Result.getAs<Stmt>());
7473 }
7474
7475 if (SubStmtInvalid)
7476 return StmtError();
7477
7478 if (!getDerived().AlwaysRebuild() &&
7479 !SubStmtChanged)
7480 return S;
7481
7482 return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
7483 Statements,
7484 S->getRBracLoc(),
7485 IsStmtExpr);
7486}
7487
7488template<typename Derived>
7489StmtResult
7490TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
7491 ExprResult LHS, RHS;
7492 {
7493 EnterExpressionEvaluationContext Unevaluated(
7494 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7495
7496 // Transform the left-hand case value.
7497 LHS = getDerived().TransformExpr(S->getLHS());
7498 LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
7499 if (LHS.isInvalid())
7500 return StmtError();
7501
7502 // Transform the right-hand case value (for the GNU case-range extension).
7503 RHS = getDerived().TransformExpr(S->getRHS());
7504 RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
7505 if (RHS.isInvalid())
7506 return StmtError();
7507 }
7508
7509 // Build the case statement.
7510 // Case statements are always rebuilt so that they will attached to their
7511 // transformed switch statement.
7512 StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
7513 LHS.get(),
7514 S->getEllipsisLoc(),
7515 RHS.get(),
7516 S->getColonLoc());
7517 if (Case.isInvalid())
7518 return StmtError();
7519
7520 // Transform the statement following the case
7521 StmtResult SubStmt =
7522 getDerived().TransformStmt(S->getSubStmt());
7523 if (SubStmt.isInvalid())
7524 return StmtError();
7525
7526 // Attach the body to the case statement
7527 return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
7528}
7529
7530template <typename Derived>
7531StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
7532 // Transform the statement following the default case
7533 StmtResult SubStmt =
7534 getDerived().TransformStmt(S->getSubStmt());
7535 if (SubStmt.isInvalid())
7536 return StmtError();
7537
7538 // Default statements are always rebuilt
7539 return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
7540 SubStmt.get());
7541}
7542
7543template<typename Derived>
7544StmtResult
7545TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
7546 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7547 if (SubStmt.isInvalid())
7548 return StmtError();
7549
7550 Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
7551 S->getDecl());
7552 if (!LD)
7553 return StmtError();
7554
7555 // If we're transforming "in-place" (we're not creating new local
7556 // declarations), assume we're replacing the old label statement
7557 // and clear out the reference to it.
7558 if (LD == S->getDecl())
7559 S->getDecl()->setStmt(nullptr);
7560
7561 // FIXME: Pass the real colon location in.
7562 return getDerived().RebuildLabelStmt(S->getIdentLoc(),
7563 cast<LabelDecl>(LD), SourceLocation(),
7564 SubStmt.get());
7565}
7566
7567template <typename Derived>
7568const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
7569 if (!R)
7570 return R;
7571
7572 switch (R->getKind()) {
7573// Transform attributes by calling TransformXXXAttr.
7574#define ATTR(X) \
7575 case attr::X: \
7576 return getDerived().Transform##X##Attr(cast<X##Attr>(R));
7577#include "clang/Basic/AttrList.inc"
7578 }
7579 return R;
7580}
7581
7582template <typename Derived>
7583const Attr *TreeTransform<Derived>::TransformStmtAttr(const Stmt *OrigS,
7584 const Stmt *InstS,
7585 const Attr *R) {
7586 if (!R)
7587 return R;
7588
7589 switch (R->getKind()) {
7590// Transform attributes by calling TransformStmtXXXAttr.
7591#define ATTR(X) \
7592 case attr::X: \
7593 return getDerived().TransformStmt##X##Attr(OrigS, InstS, cast<X##Attr>(R));
7594#include "clang/Basic/AttrList.inc"
7595 }
7596 return TransformAttr(R);
7597}
7598
7599template <typename Derived>
7600StmtResult
7601TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
7602 StmtDiscardKind SDK) {
7603 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7604 if (SubStmt.isInvalid())
7605 return StmtError();
7606
7607 bool AttrsChanged = false;
7608 SmallVector<const Attr *, 1> Attrs;
7609
7610 // Visit attributes and keep track if any are transformed.
7611 for (const auto *I : S->getAttrs()) {
7612 const Attr *R =
7613 getDerived().TransformStmtAttr(S->getSubStmt(), SubStmt.get(), I);
7614 AttrsChanged |= (I != R);
7615 if (R)
7616 Attrs.push_back(R);
7617 }
7618
7619 if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
7620 return S;
7621
7622 // If transforming the attributes failed for all of the attributes in the
7623 // statement, don't make an AttributedStmt without attributes.
7624 if (Attrs.empty())
7625 return SubStmt;
7626
7627 return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
7628 SubStmt.get());
7629}
7630
7631template<typename Derived>
7632StmtResult
7633TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
7634 // Transform the initialization statement
7635 StmtResult Init = getDerived().TransformStmt(S->getInit());
7636 if (Init.isInvalid())
7637 return StmtError();
7638
7639 Sema::ConditionResult Cond;
7640 if (!S->isConsteval()) {
7641 // Transform the condition
7642 Cond = getDerived().TransformCondition(
7643 S->getIfLoc(), S->getConditionVariable(), S->getCond(),
7644 S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
7645 : Sema::ConditionKind::Boolean);
7646 if (Cond.isInvalid())
7647 return StmtError();
7648 }
7649
7650 // If this is a constexpr if, determine which arm we should instantiate.
7651 std::optional<bool> ConstexprConditionValue;
7652 if (S->isConstexpr())
7653 ConstexprConditionValue = Cond.getKnownValue();
7654
7655 // Transform the "then" branch.
7656 StmtResult Then;
7657 if (!ConstexprConditionValue || *ConstexprConditionValue) {
7658 Then = getDerived().TransformStmt(S->getThen());
7659 if (Then.isInvalid())
7660 return StmtError();
7661 } else {
7662 Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
7663 }
7664
7665 // Transform the "else" branch.
7666 StmtResult Else;
7667 if (!ConstexprConditionValue || !*ConstexprConditionValue) {
7668 Else = getDerived().TransformStmt(S->getElse());
7669 if (Else.isInvalid())
7670 return StmtError();
7671 }
7672
7673 if (!getDerived().AlwaysRebuild() &&
7674 Init.get() == S->getInit() &&
7675 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7676 Then.get() == S->getThen() &&
7677 Else.get() == S->getElse())
7678 return S;
7679
7680 return getDerived().RebuildIfStmt(
7681 S->getIfLoc(), S->getStatementKind(), S->getLParenLoc(), Cond,
7682 S->getRParenLoc(), Init.get(), Then.get(), S->getElseLoc(), Else.get());
7683}
7684
7685template<typename Derived>
7686StmtResult
7687TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
7688 // Transform the initialization statement
7689 StmtResult Init = getDerived().TransformStmt(S->getInit());
7690 if (Init.isInvalid())
7691 return StmtError();
7692
7693 // Transform the condition.
7694 Sema::ConditionResult Cond = getDerived().TransformCondition(
7695 S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
7696 Sema::ConditionKind::Switch);
7697 if (Cond.isInvalid())
7698 return StmtError();
7699
7700 // Rebuild the switch statement.
7701 StmtResult Switch =
7702 getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), S->getLParenLoc(),
7703 Init.get(), Cond, S->getRParenLoc());
7704 if (Switch.isInvalid())
7705 return StmtError();
7706
7707 // Transform the body of the switch statement.
7708 StmtResult Body = getDerived().TransformStmt(S->getBody());
7709 if (Body.isInvalid())
7710 return StmtError();
7711
7712 // Complete the switch statement.
7713 return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
7714 Body.get());
7715}
7716
7717template<typename Derived>
7718StmtResult
7719TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
7720 // Transform the condition
7721 Sema::ConditionResult Cond = getDerived().TransformCondition(
7722 S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
7723 Sema::ConditionKind::Boolean);
7724 if (Cond.isInvalid())
7725 return StmtError();
7726
7727 // Transform the body
7728 StmtResult Body = getDerived().TransformStmt(S->getBody());
7729 if (Body.isInvalid())
7730 return StmtError();
7731
7732 if (!getDerived().AlwaysRebuild() &&
7733 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7734 Body.get() == S->getBody())
7735 return Owned(S);
7736
7737 return getDerived().RebuildWhileStmt(S->getWhileLoc(), S->getLParenLoc(),
7738 Cond, S->getRParenLoc(), Body.get());
7739}
7740
7741template<typename Derived>
7742StmtResult
7743TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
7744 // Transform the body
7745 StmtResult Body = getDerived().TransformStmt(S->getBody());
7746 if (Body.isInvalid())
7747 return StmtError();
7748
7749 // Transform the condition
7750 ExprResult Cond = getDerived().TransformExpr(S->getCond());
7751 if (Cond.isInvalid())
7752 return StmtError();
7753
7754 if (!getDerived().AlwaysRebuild() &&
7755 Cond.get() == S->getCond() &&
7756 Body.get() == S->getBody())
7757 return S;
7758
7759 return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
7760 /*FIXME:*/S->getWhileLoc(), Cond.get(),
7761 S->getRParenLoc());
7762}
7763
7764template<typename Derived>
7765StmtResult
7766TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
7767 if (getSema().getLangOpts().OpenMP)
7768 getSema().startOpenMPLoop();
7769
7770 // Transform the initialization statement
7771 StmtResult Init = getDerived().TransformStmt(S->getInit());
7772 if (Init.isInvalid())
7773 return StmtError();
7774
7775 // In OpenMP loop region loop control variable must be captured and be
7776 // private. Perform analysis of first part (if any).
7777 if (getSema().getLangOpts().OpenMP && Init.isUsable())
7778 getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
7779
7780 // Transform the condition
7781 Sema::ConditionResult Cond = getDerived().TransformCondition(
7782 S->getForLoc(), S->getConditionVariable(), S->getCond(),
7783 Sema::ConditionKind::Boolean);
7784 if (Cond.isInvalid())
7785 return StmtError();
7786
7787 // Transform the increment
7788 ExprResult Inc = getDerived().TransformExpr(S->getInc());
7789 if (Inc.isInvalid())
7790 return StmtError();
7791
7792 Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
7793 if (S->getInc() && !FullInc.get())
7794 return StmtError();
7795
7796 // Transform the body
7797 StmtResult Body = getDerived().TransformStmt(S->getBody());
7798 if (Body.isInvalid())
7799 return StmtError();
7800
7801 if (!getDerived().AlwaysRebuild() &&
7802 Init.get() == S->getInit() &&
7803 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7804 Inc.get() == S->getInc() &&
7805 Body.get() == S->getBody())
7806 return S;
7807
7808 return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
7809 Init.get(), Cond, FullInc,
7810 S->getRParenLoc(), Body.get());
7811}
7812
7813template<typename Derived>
7814StmtResult
7815TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
7816 Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
7817 S->getLabel());
7818 if (!LD)
7819 return StmtError();
7820
7821 // Goto statements must always be rebuilt, to resolve the label.
7822 return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
7823 cast<LabelDecl>(LD));
7824}
7825
7826template<typename Derived>
7827StmtResult
7828TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
7829 ExprResult Target = getDerived().TransformExpr(S->getTarget());
7830 if (Target.isInvalid())
7831 return StmtError();
7832 Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
7833
7834 if (!getDerived().AlwaysRebuild() &&
7835 Target.get() == S->getTarget())
7836 return S;
7837
7838 return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
7839 Target.get());
7840}
7841
7842template<typename Derived>
7843StmtResult
7844TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
7845 return S;
7846}
7847
7848template<typename Derived>
7849StmtResult
7850TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
7851 return S;
7852}
7853
7854template<typename Derived>
7855StmtResult
7856TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7857 ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7858 /*NotCopyInit*/false);
7859 if (Result.isInvalid())
7860 return StmtError();
7861
7862 // FIXME: We always rebuild the return statement because there is no way
7863 // to tell whether the return type of the function has changed.
7864 return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7865}
7866
7867template<typename Derived>
7868StmtResult
7869TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7870 bool DeclChanged = false;
7871 SmallVector<Decl *, 4> Decls;
7872 for (auto *D : S->decls()) {
7873 Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7874 if (!Transformed)
7875 return StmtError();
7876
7877 if (Transformed != D)
7878 DeclChanged = true;
7879
7880 Decls.push_back(Transformed);
7881 }
7882
7883 if (!getDerived().AlwaysRebuild() && !DeclChanged)
7884 return S;
7885
7886 return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7887}
7888
7889template<typename Derived>
7890StmtResult
7891TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7892
7893 SmallVector<Expr*, 8> Constraints;
7894 SmallVector<Expr*, 8> Exprs;
7895 SmallVector<IdentifierInfo *, 4> Names;
7896
7897 ExprResult AsmString;
7898 SmallVector<Expr*, 8> Clobbers;
7899
7900 bool ExprsChanged = false;
7901
7902 // Go through the outputs.
7903 for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7904 Names.push_back(S->getOutputIdentifier(I));
7905
7906 // No need to transform the constraint literal.
7907 Constraints.push_back(S->getOutputConstraintLiteral(I));
7908
7909 // Transform the output expr.
7910 Expr *OutputExpr = S->getOutputExpr(I);
7911 ExprResult Result = getDerived().TransformExpr(OutputExpr);
7912 if (Result.isInvalid())
7913 return StmtError();
7914
7915 ExprsChanged |= Result.get() != OutputExpr;
7916
7917 Exprs.push_back(Result.get());
7918 }
7919
7920 // Go through the inputs.
7921 for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7922 Names.push_back(S->getInputIdentifier(I));
7923
7924 // No need to transform the constraint literal.
7925 Constraints.push_back(S->getInputConstraintLiteral(I));
7926
7927 // Transform the input expr.
7928 Expr *InputExpr = S->getInputExpr(I);
7929 ExprResult Result = getDerived().TransformExpr(InputExpr);
7930 if (Result.isInvalid())
7931 return StmtError();
7932
7933 ExprsChanged |= Result.get() != InputExpr;
7934
7935 Exprs.push_back(Result.get());
7936 }
7937
7938 // Go through the Labels.
7939 for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7940 Names.push_back(S->getLabelIdentifier(I));
7941
7942 ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7943 if (Result.isInvalid())
7944 return StmtError();
7945 ExprsChanged |= Result.get() != S->getLabelExpr(I);
7946 Exprs.push_back(Result.get());
7947 }
7948 if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7949 return S;
7950
7951 // Go through the clobbers.
7952 for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7953 Clobbers.push_back(S->getClobberStringLiteral(I));
7954
7955 // No need to transform the asm string literal.
7956 AsmString = S->getAsmString();
7957 return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7958 S->isVolatile(), S->getNumOutputs(),
7959 S->getNumInputs(), Names.data(),
7960 Constraints, Exprs, AsmString.get(),
7961 Clobbers, S->getNumLabels(),
7962 S->getRParenLoc());
7963}
7964
7965template<typename Derived>
7966StmtResult
7967TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
7968 ArrayRef<Token> AsmToks = llvm::ArrayRef(S->getAsmToks(), S->getNumAsmToks());
7969
7970 bool HadError = false, HadChange = false;
7971
7972 ArrayRef<Expr*> SrcExprs = S->getAllExprs();
7973 SmallVector<Expr*, 8> TransformedExprs;
7974 TransformedExprs.reserve(SrcExprs.size());
7975 for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
7976 ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
7977 if (!Result.isUsable()) {
7978 HadError = true;
7979 } else {
7980 HadChange |= (Result.get() != SrcExprs[i]);
7981 TransformedExprs.push_back(Result.get());
7982 }
7983 }
7984
7985 if (HadError) return StmtError();
7986 if (!HadChange && !getDerived().AlwaysRebuild())
7987 return Owned(S);
7988
7989 return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7990 AsmToks, S->getAsmString(),
7991 S->getNumOutputs(), S->getNumInputs(),
7992 S->getAllConstraints(), S->getClobbers(),
7993 TransformedExprs, S->getEndLoc());
7994}
7995
7996// C++ Coroutines
7997template<typename Derived>
7998StmtResult
7999TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
8000 auto *ScopeInfo = SemaRef.getCurFunction();
8001 auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
8002 assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&(static_cast <bool> (FD && ScopeInfo &&
!ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends
&& ScopeInfo->CoroutineSuspends.first == nullptr &&
ScopeInfo->CoroutineSuspends.second == nullptr &&
"expected clean scope info") ? void (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "clang/lib/Sema/TreeTransform.h", 8006, __extension__ __PRETTY_FUNCTION__
))
8003 ScopeInfo->NeedsCoroutineSuspends &&(static_cast <bool> (FD && ScopeInfo &&
!ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends
&& ScopeInfo->CoroutineSuspends.first == nullptr &&
ScopeInfo->CoroutineSuspends.second == nullptr &&
"expected clean scope info") ? void (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "clang/lib/Sema/TreeTransform.h", 8006, __extension__ __PRETTY_FUNCTION__
))
8004 ScopeInfo->CoroutineSuspends.first == nullptr &&(static_cast <bool> (FD && ScopeInfo &&
!ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends
&& ScopeInfo->CoroutineSuspends.first == nullptr &&
ScopeInfo->CoroutineSuspends.second == nullptr &&
"expected clean scope info") ? void (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "clang/lib/Sema/TreeTransform.h", 8006, __extension__ __PRETTY_FUNCTION__
))
8005 ScopeInfo->CoroutineSuspends.second == nullptr &&(static_cast <bool> (FD && ScopeInfo &&
!ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends
&& ScopeInfo->CoroutineSuspends.first == nullptr &&
ScopeInfo->CoroutineSuspends.second == nullptr &&
"expected clean scope info") ? void (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "clang/lib/Sema/TreeTransform.h", 8006, __extension__ __PRETTY_FUNCTION__
))
8006 "expected clean scope info")(static_cast <bool> (FD && ScopeInfo &&
!ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends
&& ScopeInfo->CoroutineSuspends.first == nullptr &&
ScopeInfo->CoroutineSuspends.second == nullptr &&
"expected clean scope info") ? void (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "clang/lib/Sema/TreeTransform.h", 8006, __extension__ __PRETTY_FUNCTION__
))
;
8007
8008 // Set that we have (possibly-invalid) suspend points before we do anything
8009 // that may fail.
8010 ScopeInfo->setNeedsCoroutineSuspends(false);
8011
8012 // We re-build the coroutine promise object (and the coroutine parameters its
8013 // type and constructor depend on) based on the types used in our current
8014 // function. We must do so, and set it on the current FunctionScopeInfo,
8015 // before attempting to transform the other parts of the coroutine body
8016 // statement, such as the implicit suspend statements (because those
8017 // statements reference the FunctionScopeInfo::CoroutinePromise).
8018 if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
8019 return StmtError();
8020 auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
8021 if (!Promise)
8022 return StmtError();
8023 getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
8024 ScopeInfo->CoroutinePromise = Promise;
8025
8026 // Transform the implicit coroutine statements constructed using dependent
8027 // types during the previous parse: initial and final suspensions, the return
8028 // object, and others. We also transform the coroutine function's body.
8029 StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
8030 if (InitSuspend.isInvalid())
8031 return StmtError();
8032 StmtResult FinalSuspend =
8033 getDerived().TransformStmt(S->getFinalSuspendStmt());
8034 if (FinalSuspend.isInvalid() ||
8035 !SemaRef.checkFinalSuspendNoThrow(FinalSuspend.get()))
8036 return StmtError();
8037 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
8038 assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()))(static_cast <bool> (isa<Expr>(InitSuspend.get())
&& isa<Expr>(FinalSuspend.get())) ? void (0) :
__assert_fail ("isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get())"
, "clang/lib/Sema/TreeTransform.h", 8038, __extension__ __PRETTY_FUNCTION__
))
;
8039
8040 StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
8041 if (BodyRes.isInvalid())
8042 return StmtError();
8043
8044 CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
8045 if (Builder.isInvalid())
8046 return StmtError();
8047
8048 Expr *ReturnObject = S->getReturnValueInit();
8049 assert(ReturnObject && "the return object is expected to be valid")(static_cast <bool> (ReturnObject && "the return object is expected to be valid"
) ? void (0) : __assert_fail ("ReturnObject && \"the return object is expected to be valid\""
, "clang/lib/Sema/TreeTransform.h", 8049, __extension__ __PRETTY_FUNCTION__
))
;
8050 ExprResult Res = getDerived().TransformInitializer(ReturnObject,
8051 /*NoCopyInit*/ false);
8052 if (Res.isInvalid())
8053 return StmtError();
8054 Builder.ReturnValue = Res.get();
8055
8056 // If during the previous parse the coroutine still had a dependent promise
8057 // statement, we may need to build some implicit coroutine statements
8058 // (such as exception and fallthrough handlers) for the first time.
8059 if (S->hasDependentPromiseType()) {
8060 // We can only build these statements, however, if the current promise type
8061 // is not dependent.
8062 if (!Promise->getType()->isDependentType()) {
8063 assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&(static_cast <bool> (!S->getFallthroughHandler() &&
!S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure
() && !S->getDeallocate() && "these nodes should not have been built yet"
) ? void (0) : __assert_fail ("!S->getFallthroughHandler() && !S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() && \"these nodes should not have been built yet\""
, "clang/lib/Sema/TreeTransform.h", 8065, __extension__ __PRETTY_FUNCTION__
))
8064 !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&(static_cast <bool> (!S->getFallthroughHandler() &&
!S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure
() && !S->getDeallocate() && "these nodes should not have been built yet"
) ? void (0) : __assert_fail ("!S->getFallthroughHandler() && !S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() && \"these nodes should not have been built yet\""
, "clang/lib/Sema/TreeTransform.h", 8065, __extension__ __PRETTY_FUNCTION__
))
8065 "these nodes should not have been built yet")(static_cast <bool> (!S->getFallthroughHandler() &&
!S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure
() && !S->getDeallocate() && "these nodes should not have been built yet"
) ? void (0) : __assert_fail ("!S->getFallthroughHandler() && !S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() && \"these nodes should not have been built yet\""
, "clang/lib/Sema/TreeTransform.h", 8065, __extension__ __PRETTY_FUNCTION__
))
;
8066 if (!Builder.buildDependentStatements())
8067 return StmtError();
8068 }
8069 } else {
8070 if (auto *OnFallthrough = S->getFallthroughHandler()) {
8071 StmtResult Res = getDerived().TransformStmt(OnFallthrough);
8072 if (Res.isInvalid())
8073 return StmtError();
8074 Builder.OnFallthrough = Res.get();
8075 }
8076
8077 if (auto *OnException = S->getExceptionHandler()) {
8078 StmtResult Res = getDerived().TransformStmt(OnException);
8079 if (Res.isInvalid())
8080 return StmtError();
8081 Builder.OnException = Res.get();
8082 }
8083
8084 if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
8085 StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
8086 if (Res.isInvalid())
8087 return StmtError();
8088 Builder.ReturnStmtOnAllocFailure = Res.get();
8089 }
8090
8091 // Transform any additional statements we may have already built
8092 assert(S->getAllocate() && S->getDeallocate() &&(static_cast <bool> (S->getAllocate() && S->
getDeallocate() && "allocation and deallocation calls must already be built"
) ? void (0) : __assert_fail ("S->getAllocate() && S->getDeallocate() && \"allocation and deallocation calls must already be built\""
, "clang/lib/Sema/TreeTransform.h", 8093, __extension__ __PRETTY_FUNCTION__
))
8093 "allocation and deallocation calls must already be built")(static_cast <bool> (S->getAllocate() && S->
getDeallocate() && "allocation and deallocation calls must already be built"
) ? void (0) : __assert_fail ("S->getAllocate() && S->getDeallocate() && \"allocation and deallocation calls must already be built\""
, "clang/lib/Sema/TreeTransform.h", 8093, __extension__ __PRETTY_FUNCTION__
))
;
8094 ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
8095 if (AllocRes.isInvalid())
8096 return StmtError();
8097 Builder.Allocate = AllocRes.get();
8098
8099 ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
8100 if (DeallocRes.isInvalid())
8101 return StmtError();
8102 Builder.Deallocate = DeallocRes.get();
8103
8104 if (auto *ResultDecl = S->getResultDecl()) {
8105 StmtResult Res = getDerived().TransformStmt(ResultDecl);
8106 if (Res.isInvalid())
8107 return StmtError();
8108 Builder.ResultDecl = Res.get();
8109 }
8110
8111 if (auto *ReturnStmt = S->getReturnStmt()) {
8112 StmtResult Res = getDerived().TransformStmt(ReturnStmt);
8113 if (Res.isInvalid())
8114 return StmtError();
8115 Builder.ReturnStmt = Res.get();
8116 }
8117 }
8118
8119 return getDerived().RebuildCoroutineBodyStmt(Builder);
8120}
8121
8122template<typename Derived>
8123StmtResult
8124TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
8125 ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
8126 /*NotCopyInit*/false);
8127 if (Result.isInvalid())
8128 return StmtError();
8129
8130 // Always rebuild; we don't know if this needs to be injected into a new
8131 // context or if the promise type has changed.
8132 return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
8133 S->isImplicit());
8134}
8135
8136template <typename Derived>
8137ExprResult TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
8138 ExprResult Operand = getDerived().TransformInitializer(E->getOperand(),
8139 /*NotCopyInit*/ false);
8140 if (Operand.isInvalid())
8141 return ExprError();
8142
8143 // Rebuild the common-expr from the operand rather than transforming it
8144 // separately.
8145
8146 // FIXME: getCurScope() should not be used during template instantiation.
8147 // We should pick up the set of unqualified lookup results for operator
8148 // co_await during the initial parse.
8149 ExprResult Lookup = getSema().BuildOperatorCoawaitLookupExpr(
8150 getSema().getCurScope(), E->getKeywordLoc());
8151
8152 // Always rebuild; we don't know if this needs to be injected into a new
8153 // context or if the promise type has changed.
8154 return getDerived().RebuildCoawaitExpr(
8155 E->getKeywordLoc(), Operand.get(),
8156 cast<UnresolvedLookupExpr>(Lookup.get()), E->isImplicit());
8157}
8158
8159template <typename Derived>
8160ExprResult
8161TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
8162 ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
8163 /*NotCopyInit*/ false);
8164 if (OperandResult.isInvalid())
8165 return ExprError();
8166
8167 ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
8168 E->getOperatorCoawaitLookup());
8169
8170 if (LookupResult.isInvalid())
8171 return ExprError();
8172
8173 // Always rebuild; we don't know if this needs to be injected into a new
8174 // context or if the promise type has changed.
8175 return getDerived().RebuildDependentCoawaitExpr(
8176 E->getKeywordLoc(), OperandResult.get(),
8177 cast<UnresolvedLookupExpr>(LookupResult.get()));
8178}
8179
8180template<typename Derived>
8181ExprResult
8182TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
8183 ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
8184 /*NotCopyInit*/false);
8185 if (Result.isInvalid())
8186 return ExprError();
8187
8188 // Always rebuild; we don't know if this needs to be injected into a new
8189 // context or if the promise type has changed.
8190 return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
8191}
8192
8193// Objective-C Statements.
8194
8195template<typename Derived>
8196StmtResult
8197TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
8198 // Transform the body of the @try.
8199 StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
8200 if (TryBody.isInvalid())
8201 return StmtError();
8202
8203 // Transform the @catch statements (if present).
8204 bool AnyCatchChanged = false;
8205 SmallVector<Stmt*, 8> CatchStmts;
8206 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
8207 StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
8208 if (Catch.isInvalid())
8209 return StmtError();
8210 if (Catch.get() != S->getCatchStmt(I))
8211 AnyCatchChanged = true;
8212 CatchStmts.push_back(Catch.get());
8213 }
8214
8215 // Transform the @finally statement (if present).
8216 StmtResult Finally;
8217 if (S->getFinallyStmt()) {
8218 Finally = getDerived().TransformStmt(S->getFinallyStmt());
8219 if (Finally.isInvalid())
8220 return StmtError();
8221 }
8222
8223 // If nothing changed, just retain this statement.
8224 if (!getDerived().AlwaysRebuild() &&
8225 TryBody.get() == S->getTryBody() &&
8226 !AnyCatchChanged &&
8227 Finally.get() == S->getFinallyStmt())
8228 return S;
8229
8230 // Build a new statement.
8231 return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
8232 CatchStmts, Finally.get());
8233}
8234
8235template<typename Derived>
8236StmtResult
8237TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
8238 // Transform the @catch parameter, if there is one.
8239 VarDecl *Var = nullptr;
8240 if (VarDecl *FromVar = S->getCatchParamDecl()) {
8241 TypeSourceInfo *TSInfo = nullptr;
8242 if (FromVar->getTypeSourceInfo()) {
8243 TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
8244 if (!TSInfo)
8245 return StmtError();
8246 }
8247
8248 QualType T;
8249 if (TSInfo)
8250 T = TSInfo->getType();
8251 else {
8252 T = getDerived().TransformType(FromVar->getType());
8253 if (T.isNull())
8254 return StmtError();
8255 }
8256
8257 Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
8258 if (!Var)
8259 return StmtError();
8260 }
8261
8262 StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
8263 if (Body.isInvalid())
8264 return StmtError();
8265
8266 return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
8267 S->getRParenLoc(),
8268 Var, Body.get());
8269}
8270
8271template<typename Derived>
8272StmtResult
8273TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
8274 // Transform the body.
8275 StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
8276 if (Body.isInvalid())
8277 return StmtError();
8278
8279 // If nothing changed, just retain this statement.
8280 if (!getDerived().AlwaysRebuild() &&
8281 Body.get() == S->getFinallyBody())
8282 return S;
8283
8284 // Build a new statement.
8285 return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
8286 Body.get());
8287}
8288
8289template<typename Derived>
8290StmtResult
8291TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
8292 ExprResult Operand;
8293 if (S->getThrowExpr()) {
8294 Operand = getDerived().TransformExpr(S->getThrowExpr());
8295 if (Operand.isInvalid())
8296 return StmtError();
8297 }
8298
8299 if (!getDerived().AlwaysRebuild() &&
8300 Operand.get() == S->getThrowExpr())
8301 return S;
8302
8303 return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
8304}
8305
8306template<typename Derived>
8307StmtResult
8308TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
8309 ObjCAtSynchronizedStmt *S) {
8310 // Transform the object we are locking.
8311 ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
8312 if (Object.isInvalid())
8313 return StmtError();
8314 Object =
8315 getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
8316 Object.get());
8317 if (Object.isInvalid())
8318 return StmtError();
8319
8320 // Transform the body.
8321 StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
8322 if (Body.isInvalid())
8323 return StmtError();
8324
8325 // If nothing change, just retain the current statement.
8326 if (!getDerived().AlwaysRebuild() &&
8327 Object.get() == S->getSynchExpr() &&
8328 Body.get() == S->getSynchBody())
8329 return S;
8330
8331 // Build a new statement.
8332 return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
8333 Object.get(), Body.get());
8334}
8335
8336template<typename Derived>
8337StmtResult
8338TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
8339 ObjCAutoreleasePoolStmt *S) {
8340 // Transform the body.
8341 StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
8342 if (Body.isInvalid())
8343 return StmtError();
8344
8345 // If nothing changed, just retain this statement.
8346 if (!getDerived().AlwaysRebuild() &&
8347 Body.get() == S->getSubStmt())
8348 return S;
8349
8350 // Build a new statement.
8351 return getDerived().RebuildObjCAutoreleasePoolStmt(
8352 S->getAtLoc(), Body.get());
8353}
8354
8355template<typename Derived>
8356StmtResult
8357TreeTransform<Derived>::TransformObjCForCollectionStmt(
8358 ObjCForCollectionStmt *S) {
8359 // Transform the element statement.
8360 StmtResult Element =
8361 getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
8362 if (Element.isInvalid())
8363 return StmtError();
8364
8365 // Transform the collection expression.
8366 ExprResult Collection = getDerived().TransformExpr(S->getCollection());
8367 if (Collection.isInvalid())
8368 return StmtError();
8369
8370 // Transform the body.
8371 StmtResult Body = getDerived().TransformStmt(S->getBody());
8372 if (Body.isInvalid())
8373 return StmtError();
8374
8375 // If nothing changed, just retain this statement.
8376 if (!getDerived().AlwaysRebuild() &&
8377 Element.get() == S->getElement() &&
8378 Collection.get() == S->getCollection() &&
8379 Body.get() == S->getBody())
8380 return S;
8381
8382 // Build a new statement.
8383 return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
8384 Element.get(),
8385 Collection.get(),
8386 S->getRParenLoc(),
8387 Body.get());
8388}
8389
8390template <typename Derived>
8391StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
8392 // Transform the exception declaration, if any.
8393 VarDecl *Var = nullptr;
8394 if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
8395 TypeSourceInfo *T =
8396 getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
8397 if (!T)
8398 return StmtError();
8399
8400 Var = getDerived().RebuildExceptionDecl(
8401 ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
8402 ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
8403 if (!Var || Var->isInvalidDecl())
8404 return StmtError();
8405 }
8406
8407 // Transform the actual exception handler.
8408 StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
8409 if (Handler.isInvalid())
8410 return StmtError();
8411
8412 if (!getDerived().AlwaysRebuild() && !Var &&
8413 Handler.get() == S->getHandlerBlock())
8414 return S;
8415
8416 return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
8417}
8418
8419template <typename Derived>
8420StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
8421 // Transform the try block itself.
8422 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8423 if (TryBlock.isInvalid())
8424 return StmtError();
8425
8426 // Transform the handlers.
8427 bool HandlerChanged = false;
8428 SmallVector<Stmt *, 8> Handlers;
8429 for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
8430 StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
8431 if (Handler.isInvalid())
8432 return StmtError();
8433
8434 HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
8435 Handlers.push_back(Handler.getAs<Stmt>());
8436 }
8437
8438 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8439 !HandlerChanged)
8440 return S;
8441
8442 return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
8443 Handlers);
8444}
8445
8446template<typename Derived>
8447StmtResult
8448TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
8449 StmtResult Init =
8450 S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
8451 if (Init.isInvalid())
8452 return StmtError();
8453
8454 StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
8455 if (Range.isInvalid())
8456 return StmtError();
8457
8458 StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
8459 if (Begin.isInvalid())
8460 return StmtError();
8461 StmtResult End = getDerived().TransformStmt(S->getEndStmt());
8462 if (End.isInvalid())
8463 return StmtError();
8464
8465 ExprResult Cond = getDerived().TransformExpr(S->getCond());
8466 if (Cond.isInvalid())
8467 return StmtError();
8468 if (Cond.get())
8469 Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
8470 if (Cond.isInvalid())
8471 return StmtError();
8472 if (Cond.get())
8473 Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
8474
8475 ExprResult Inc = getDerived().TransformExpr(S->getInc());
8476 if (Inc.isInvalid())
8477 return StmtError();
8478 if (Inc.get())
8479 Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
8480
8481 StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
8482 if (LoopVar.isInvalid())
8483 return StmtError();
8484
8485 StmtResult NewStmt = S;
8486 if (getDerived().AlwaysRebuild() ||
8487 Init.get() != S->getInit() ||
8488 Range.get() != S->getRangeStmt() ||
8489 Begin.get() != S->getBeginStmt() ||
8490 End.get() != S->getEndStmt() ||
8491 Cond.get() != S->getCond() ||
8492 Inc.get() != S->getInc() ||
8493 LoopVar.get() != S->getLoopVarStmt()) {
8494 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8495 S->getCoawaitLoc(), Init.get(),
8496 S->getColonLoc(), Range.get(),
8497 Begin.get(), End.get(),
8498 Cond.get(),
8499 Inc.get(), LoopVar.get(),
8500 S->getRParenLoc());
8501 if (NewStmt.isInvalid() && LoopVar.get() != S->getLoopVarStmt()) {
8502 // Might not have attached any initializer to the loop variable.
8503 getSema().ActOnInitializerError(
8504 cast<DeclStmt>(LoopVar.get())->getSingleDecl());
8505 return StmtError();
8506 }
8507 }
8508
8509 StmtResult Body = getDerived().TransformStmt(S->getBody());
8510 if (Body.isInvalid())
8511 return StmtError();
8512
8513 // Body has changed but we didn't rebuild the for-range statement. Rebuild
8514 // it now so we have a new statement to attach the body to.
8515 if (Body.get() != S->getBody() && NewStmt.get() == S) {
8516 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8517 S->getCoawaitLoc(), Init.get(),
8518 S->getColonLoc(), Range.get(),
8519 Begin.get(), End.get(),
8520 Cond.get(),
8521 Inc.get(), LoopVar.get(),
8522 S->getRParenLoc());
8523 if (NewStmt.isInvalid())
8524 return StmtError();
8525 }
8526
8527 if (NewStmt.get() == S)
8528 return S;
8529
8530 return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
8531}
8532
8533template<typename Derived>
8534StmtResult
8535TreeTransform<Derived>::TransformMSDependentExistsStmt(
8536 MSDependentExistsStmt *S) {
8537 // Transform the nested-name-specifier, if any.
8538 NestedNameSpecifierLoc QualifierLoc;
8539 if (S->getQualifierLoc()) {
8540 QualifierLoc
8541 = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
8542 if (!QualifierLoc)
8543 return StmtError();
8544 }
8545
8546 // Transform the declaration name.
8547 DeclarationNameInfo NameInfo = S->getNameInfo();
8548 if (NameInfo.getName()) {
8549 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8550 if (!NameInfo.getName())
8551 return StmtError();
8552 }
8553
8554 // Check whether anything changed.
8555 if (!getDerived().AlwaysRebuild() &&
8556 QualifierLoc == S->getQualifierLoc() &&
8557 NameInfo.getName() == S->getNameInfo().getName())
8558 return S;
8559
8560 // Determine whether this name exists, if we can.
8561 CXXScopeSpec SS;
8562 SS.Adopt(QualifierLoc);
8563 bool Dependent = false;
8564 switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
8565 case Sema::IER_Exists:
8566 if (S->isIfExists())
8567 break;
8568
8569 return new (getSema().Context) NullStmt(S->getKeywordLoc());
8570
8571 case Sema::IER_DoesNotExist:
8572 if (S->isIfNotExists())
8573 break;
8574
8575 return new (getSema().Context) NullStmt(S->getKeywordLoc());
8576
8577 case Sema::IER_Dependent:
8578 Dependent = true;
8579 break;
8580
8581 case Sema::IER_Error:
8582 return StmtError();
8583 }
8584
8585 // We need to continue with the instantiation, so do so now.
8586 StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
8587 if (SubStmt.isInvalid())
8588 return StmtError();
8589
8590 // If we have resolved the name, just transform to the substatement.
8591 if (!Dependent)
8592 return SubStmt;
8593
8594 // The name is still dependent, so build a dependent expression again.
8595 return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
8596 S->isIfExists(),
8597 QualifierLoc,
8598 NameInfo,
8599 SubStmt.get());
8600}
8601
8602template<typename Derived>
8603ExprResult
8604TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
8605 NestedNameSpecifierLoc QualifierLoc;
8606 if (E->getQualifierLoc()) {
8607 QualifierLoc
8608 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8609 if (!QualifierLoc)
8610 return ExprError();
8611 }
8612
8613 MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
8614 getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
8615 if (!PD)
8616 return ExprError();
8617
8618 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
8619 if (Base.isInvalid())
8620 return ExprError();
8621
8622 return new (SemaRef.getASTContext())
8623 MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
8624 SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
8625 QualifierLoc, E->getMemberLoc());
8626}
8627
8628template <typename Derived>
8629ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
8630 MSPropertySubscriptExpr *E) {
8631 auto BaseRes = getDerived().TransformExpr(E->getBase());
8632 if (BaseRes.isInvalid())
8633 return ExprError();
8634 auto IdxRes = getDerived().TransformExpr(E->getIdx());
8635 if (IdxRes.isInvalid())
8636 return ExprError();
8637
8638 if (!getDerived().AlwaysRebuild() &&
8639 BaseRes.get() == E->getBase() &&
8640 IdxRes.get() == E->getIdx())
8641 return E;
8642
8643 return getDerived().RebuildArraySubscriptExpr(
8644 BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
8645}
8646
8647template <typename Derived>
8648StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
8649 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8650 if (TryBlock.isInvalid())
8651 return StmtError();
8652
8653 StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
8654 if (Handler.isInvalid())
8655 return StmtError();
8656
8657 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8658 Handler.get() == S->getHandler())
8659 return S;
8660
8661 return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
8662 TryBlock.get(), Handler.get());
8663}
8664
8665template <typename Derived>
8666StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
8667 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8668 if (Block.isInvalid())
8669 return StmtError();
8670
8671 return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
8672}
8673
8674template <typename Derived>
8675StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
8676 ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
8677 if (FilterExpr.isInvalid())
8678 return StmtError();
8679
8680 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8681 if (Block.isInvalid())
8682 return StmtError();
8683
8684 return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
8685 Block.get());
8686}
8687
8688template <typename Derived>
8689StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
8690 if (isa<SEHFinallyStmt>(Handler))
8691 return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
8692 else
8693 return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
8694}
8695
8696template<typename Derived>
8697StmtResult
8698TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
8699 return S;
8700}
8701
8702//===----------------------------------------------------------------------===//
8703// OpenMP directive transformation
8704//===----------------------------------------------------------------------===//
8705
8706template <typename Derived>
8707StmtResult
8708TreeTransform<Derived>::TransformOMPCanonicalLoop(OMPCanonicalLoop *L) {
8709 // OMPCanonicalLoops are eliminated during transformation, since they will be
8710 // recomputed by semantic analysis of the associated OMPLoopBasedDirective
8711 // after transformation.
8712 return getDerived().TransformStmt(L->getLoopStmt());
8713}
8714
8715template <typename Derived>
8716StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
8717 OMPExecutableDirective *D) {
8718
8719 // Transform the clauses
8720 llvm::SmallVector<OMPClause *, 16> TClauses;
8721 ArrayRef<OMPClause *> Clauses = D->clauses();
8722 TClauses.reserve(Clauses.size());
8723 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
8724 I != E; ++I) {
8725 if (*I) {
8726 getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
8727 OMPClause *Clause = getDerived().TransformOMPClause(*I);
8728 getDerived().getSema().EndOpenMPClause();
8729 if (Clause)
8730 TClauses.push_back(Clause);
8731 } else {
8732 TClauses.push_back(nullptr);
8733 }
8734 }
8735 StmtResult AssociatedStmt;
8736 if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
8737 getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
8738 /*CurScope=*/nullptr);
8739 StmtResult Body;
8740 {
8741 Sema::CompoundScopeRAII CompoundScope(getSema());
8742 Stmt *CS;
8743 if (D->getDirectiveKind() == OMPD_atomic ||
8744 D->getDirectiveKind() == OMPD_critical ||
8745 D->getDirectiveKind() == OMPD_section ||
8746 D->getDirectiveKind() == OMPD_master)
8747 CS = D->getAssociatedStmt();
8748 else
8749 CS = D->getRawStmt();
8750 Body = getDerived().TransformStmt(CS);
8751 if (Body.isUsable() && isOpenMPLoopDirective(D->getDirectiveKind()) &&
8752 getSema().getLangOpts().OpenMPIRBuilder)
8753 Body = getDerived().RebuildOMPCanonicalLoop(Body.get());
8754 }
8755 AssociatedStmt =
8756 getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
8757 if (AssociatedStmt.isInvalid()) {
8758 return StmtError();
8759 }
8760 }
8761 if (TClauses.size() != Clauses.size()) {
8762 return StmtError();
8763 }
8764
8765 // Transform directive name for 'omp critical' directive.
8766 DeclarationNameInfo DirName;
8767 if (D->getDirectiveKind() == OMPD_critical) {
8768 DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
8769 DirName = getDerived().TransformDeclarationNameInfo(DirName);
8770 }
8771 OpenMPDirectiveKind CancelRegion = OMPD_unknown;
8772 if (D->getDirectiveKind() == OMPD_cancellation_point) {
8773 CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
8774 } else if (D->getDirectiveKind() == OMPD_cancel) {
8775 CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
8776 }
8777
8778 return getDerived().RebuildOMPExecutableDirective(
8779 D->getDirectiveKind(), DirName, CancelRegion, TClauses,
8780 AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
8781}
8782
8783template <typename Derived>
8784StmtResult
8785TreeTransform<Derived>::TransformOMPMetaDirective(OMPMetaDirective *D) {
8786 // TODO: Fix This
8787 SemaRef.Diag(D->getBeginLoc(), diag::err_omp_instantiation_not_supported)
8788 << getOpenMPDirectiveName(D->getDirectiveKind());
8789 return StmtError();
8790}
8791
8792template <typename Derived>
8793StmtResult
8794TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
8795 DeclarationNameInfo DirName;
8796 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
8797 D->getBeginLoc());
8798 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8799 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8800 return Res;
8801}
8802
8803template <typename Derived>
8804StmtResult
8805TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
8806 DeclarationNameInfo DirName;
8807 getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
8808 D->getBeginLoc());
8809 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8810 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8811 return Res;
8812}
8813
8814template <typename Derived>
8815StmtResult
8816TreeTransform<Derived>::TransformOMPTileDirective(OMPTileDirective *D) {
8817 DeclarationNameInfo DirName;
8818 getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8819 nullptr, D->getBeginLoc());
8820 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8821 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8822 return Res;
8823}
8824
8825template <typename Derived>
8826StmtResult
8827TreeTransform<Derived>::TransformOMPUnrollDirective(OMPUnrollDirective *D) {
8828 DeclarationNameInfo DirName;
8829 getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8830 nullptr, D->getBeginLoc());
8831 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8832 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8833 return Res;
8834}
8835
8836template <typename Derived>
8837StmtResult
8838TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
8839 DeclarationNameInfo DirName;
8840 getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
8841 D->getBeginLoc());
8842 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8843 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8844 return Res;
8845}
8846
8847template <typename Derived>
8848StmtResult
8849TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
8850 DeclarationNameInfo DirName;
8851 getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
8852 D->getBeginLoc());
8853 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8854 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8855 return Res;
8856}
8857
8858template <typename Derived>
8859StmtResult
8860TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
8861 DeclarationNameInfo DirName;
8862 getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
8863 D->getBeginLoc());
8864 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8865 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8866 return Res;
8867}
8868
8869template <typename Derived>
8870StmtResult
8871TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
8872 DeclarationNameInfo DirName;
8873 getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
8874 D->getBeginLoc());
8875 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8876 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8877 return Res;
8878}
8879
8880template <typename Derived>
8881StmtResult
8882TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
8883 DeclarationNameInfo DirName;
8884 getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
8885 D->getBeginLoc());
8886 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8887 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8888 return Res;
8889}
8890
8891template <typename Derived>
8892StmtResult
8893TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
8894 DeclarationNameInfo DirName;
8895 getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
8896 D->getBeginLoc());
8897 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8898 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8899 return Res;
8900}
8901
8902template <typename Derived>
8903StmtResult
8904TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
8905 getDerived().getSema().StartOpenMPDSABlock(
8906 OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
8907 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8908 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8909 return Res;
8910}
8911
8912template <typename Derived>
8913StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
8914 OMPParallelForDirective *D) {
8915 DeclarationNameInfo DirName;
8916 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
8917 nullptr, D->getBeginLoc());
8918 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8919 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8920 return Res;
8921}
8922
8923template <typename Derived>
8924StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8925 OMPParallelForSimdDirective *D) {
8926 DeclarationNameInfo DirName;
8927 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8928 nullptr, D->getBeginLoc());
8929 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8930 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8931 return Res;
8932}
8933
8934template <typename Derived>
8935StmtResult TreeTransform<Derived>::TransformOMPParallelMasterDirective(
8936 OMPParallelMasterDirective *D) {
8937 DeclarationNameInfo DirName;
8938 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_master, DirName,
8939 nullptr, D->getBeginLoc());
8940 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8941 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8942 return Res;
8943}
8944
8945template <typename Derived>
8946StmtResult TreeTransform<Derived>::TransformOMPParallelMaskedDirective(
8947 OMPParallelMaskedDirective *D) {
8948 DeclarationNameInfo DirName;
8949 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_masked, DirName,
8950 nullptr, D->getBeginLoc());
8951 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8952 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8953 return Res;
8954}
8955
8956template <typename Derived>
8957StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8958 OMPParallelSectionsDirective *D) {
8959 DeclarationNameInfo DirName;
8960 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8961 nullptr, D->getBeginLoc());
8962 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8963 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8964 return Res;
8965}
8966
8967template <typename Derived>
8968StmtResult
8969TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8970 DeclarationNameInfo DirName;
8971 getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
8972 D->getBeginLoc());
8973 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8974 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8975 return Res;
8976}
8977
8978template <typename Derived>
8979StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8980 OMPTaskyieldDirective *D) {
8981 DeclarationNameInfo DirName;
8982 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
8983 D->getBeginLoc());
8984 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8985 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8986 return Res;
8987}
8988
8989template <typename Derived>
8990StmtResult
8991TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8992 DeclarationNameInfo DirName;
8993 getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8994 D->getBeginLoc());
8995 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8996 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8997 return Res;
8998}
8999
9000template <typename Derived>
9001StmtResult
9002TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
9003 DeclarationNameInfo DirName;
9004 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
9005 D->getBeginLoc());
9006 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9007 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9008 return Res;
9009}
9010
9011template <typename Derived>
9012StmtResult
9013TreeTransform<Derived>::TransformOMPErrorDirective(OMPErrorDirective *D) {
9014 DeclarationNameInfo DirName;
9015 getDerived().getSema().StartOpenMPDSABlock(OMPD_error, DirName, nullptr,
9016 D->getBeginLoc());
9017 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9018 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9019 return Res;
9020}
9021
9022template <typename Derived>
9023StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
9024 OMPTaskgroupDirective *D) {
9025 DeclarationNameInfo DirName;
9026 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
9027 D->getBeginLoc());
9028 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9029 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9030 return Res;
9031}
9032
9033template <typename Derived>
9034StmtResult
9035TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
9036 DeclarationNameInfo DirName;
9037 getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
9038 D->getBeginLoc());
9039 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9040 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9041 return Res;
9042}
9043
9044template <typename Derived>
9045StmtResult
9046TreeTransform<Derived>::TransformOMPDepobjDirective(OMPDepobjDirective *D) {
9047 DeclarationNameInfo DirName;
9048 getDerived().getSema().StartOpenMPDSABlock(OMPD_depobj, DirName, nullptr,
9049 D->getBeginLoc());
9050 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9051 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9052 return Res;
9053}
9054
9055template <typename Derived>
9056StmtResult
9057TreeTransform<Derived>::TransformOMPScanDirective(OMPScanDirective *D) {
9058 DeclarationNameInfo DirName;
9059 getDerived().getSema().StartOpenMPDSABlock(OMPD_scan, DirName, nullptr,
9060 D->getBeginLoc());
9061 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9062 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9063 return Res;
9064}
9065
9066template <typename Derived>
9067StmtResult
9068TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
9069 DeclarationNameInfo DirName;
9070 getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
9071 D->getBeginLoc());
9072 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9073 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9074 return Res;
9075}
9076
9077template <typename Derived>
9078StmtResult
9079TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
9080 DeclarationNameInfo DirName;
9081 getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
9082 D->getBeginLoc());
9083 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9084 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9085 return Res;
9086}
9087
9088template <typename Derived>
9089StmtResult
9090TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
9091 DeclarationNameInfo DirName;
9092 getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
9093 D->getBeginLoc());
9094 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9095 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9096 return Res;
9097}
9098
9099template <typename Derived>
9100StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
9101 OMPTargetDataDirective *D) {
9102 DeclarationNameInfo DirName;
9103 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
9104 D->getBeginLoc());
9105 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9106 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9107 return Res;
9108}
9109
9110template <typename Derived>
9111StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
9112 OMPTargetEnterDataDirective *D) {
9113 DeclarationNameInfo DirName;
9114 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
9115 nullptr, D->getBeginLoc());
9116 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9117 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9118 return Res;
9119}
9120
9121template <typename Derived>
9122StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
9123 OMPTargetExitDataDirective *D) {
9124 DeclarationNameInfo DirName;
9125 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
9126 nullptr, D->getBeginLoc());
9127 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9128 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9129 return Res;
9130}
9131
9132template <typename Derived>
9133StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
9134 OMPTargetParallelDirective *D) {
9135 DeclarationNameInfo DirName;
9136 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
9137 nullptr, D->getBeginLoc());
9138 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9139 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9140 return Res;
9141}
9142
9143template <typename Derived>
9144StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
9145 OMPTargetParallelForDirective *D) {
9146 DeclarationNameInfo DirName;
9147 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
9148 nullptr, D->getBeginLoc());
9149 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9150 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9151 return Res;
9152}
9153
9154template <typename Derived>
9155StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
9156 OMPTargetUpdateDirective *D) {
9157 DeclarationNameInfo DirName;
9158 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
9159 nullptr, D->getBeginLoc());
9160 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9161 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9162 return Res;
9163}
9164
9165template <typename Derived>
9166StmtResult
9167TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
9168 DeclarationNameInfo DirName;
9169 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
9170 D->getBeginLoc());
9171 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9172 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9173 return Res;
9174}
9175
9176template <typename Derived>
9177StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
9178 OMPCancellationPointDirective *D) {
9179 DeclarationNameInfo DirName;
9180 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
9181 nullptr, D->getBeginLoc());
9182 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9183 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9184 return Res;
9185}
9186
9187template <typename Derived>
9188StmtResult
9189TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
9190 DeclarationNameInfo DirName;
9191 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
9192 D->getBeginLoc());
9193 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9194 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9195 return Res;
9196}
9197
9198template <typename Derived>
9199StmtResult
9200TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
9201 DeclarationNameInfo DirName;
9202 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
9203 D->getBeginLoc());
9204 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9205 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9206 return Res;
9207}
9208
9209template <typename Derived>
9210StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
9211 OMPTaskLoopSimdDirective *D) {
9212 DeclarationNameInfo DirName;
9213 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
9214 nullptr, D->getBeginLoc());
9215 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9216 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9217 return Res;
9218}
9219
9220template <typename Derived>
9221StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopDirective(
9222 OMPMasterTaskLoopDirective *D) {
9223 DeclarationNameInfo DirName;
9224 getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, DirName,
9225 nullptr, D->getBeginLoc());
9226 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9227 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9228 return Res;
9229}
9230
9231template <typename Derived>
9232StmtResult TreeTransform<Derived>::TransformOMPMaskedTaskLoopDirective(
9233 OMPMaskedTaskLoopDirective *D) {
9234 DeclarationNameInfo DirName;
9235 getDerived().getSema().StartOpenMPDSABlock(OMPD_masked_taskloop, DirName,
9236 nullptr, D->getBeginLoc());
9237 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9238 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9239 return Res;
9240}
9241
9242template <typename Derived>
9243StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopSimdDirective(
9244 OMPMasterTaskLoopSimdDirective *D) {
9245 DeclarationNameInfo DirName;
9246 getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
9247 nullptr, D->getBeginLoc());
9248 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9249 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9250 return Res;
9251}
9252
9253template <typename Derived>
9254StmtResult TreeTransform<Derived>::TransformOMPMaskedTaskLoopSimdDirective(
9255 OMPMaskedTaskLoopSimdDirective *D) {
9256 DeclarationNameInfo DirName;
9257 getDerived().getSema().StartOpenMPDSABlock(OMPD_masked_taskloop_simd, DirName,
9258 nullptr, D->getBeginLoc());
9259 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9260 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9261 return Res;
9262}
9263
9264template <typename Derived>
9265StmtResult TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
9266 OMPParallelMasterTaskLoopDirective *D) {
9267 DeclarationNameInfo DirName;
9268 getDerived().getSema().StartOpenMPDSABlock(
9269 OMPD_parallel_master_taskloop, DirName, nullptr, D->getBeginLoc());
9270 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9271 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9272 return Res;
9273}
9274
9275template <typename Derived>
9276StmtResult TreeTransform<Derived>::TransformOMPParallelMaskedTaskLoopDirective(
9277 OMPParallelMaskedTaskLoopDirective *D) {
9278 DeclarationNameInfo DirName;
9279 getDerived().getSema().StartOpenMPDSABlock(
9280 OMPD_parallel_masked_taskloop, DirName, nullptr, D->getBeginLoc());
9281 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9282 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9283 return Res;
9284}
9285
9286template <typename Derived>
9287StmtResult
9288TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopSimdDirective(
9289 OMPParallelMasterTaskLoopSimdDirective *D) {
9290 DeclarationNameInfo DirName;
9291 getDerived().getSema().StartOpenMPDSABlock(
9292 OMPD_parallel_master_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9293 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9294 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9295 return Res;
9296}
9297
9298template <typename Derived>
9299StmtResult
9300TreeTransform<Derived>::TransformOMPParallelMaskedTaskLoopSimdDirective(
9301 OMPParallelMaskedTaskLoopSimdDirective *D) {
9302 DeclarationNameInfo DirName;
9303 getDerived().getSema().StartOpenMPDSABlock(
9304 OMPD_parallel_masked_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9305 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9306 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9307 return Res;
9308}
9309
9310template <typename Derived>
9311StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
9312 OMPDistributeDirective *D) {
9313 DeclarationNameInfo DirName;
9314 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
9315 D->getBeginLoc());
9316 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9317 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9318 return Res;
9319}
9320
9321template <typename Derived>
9322StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
9323 OMPDistributeParallelForDirective *D) {
9324 DeclarationNameInfo DirName;
9325 getDerived().getSema().StartOpenMPDSABlock(
9326 OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9327 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9328 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9329 return Res;
9330}
9331
9332template <typename Derived>
9333StmtResult
9334TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
9335 OMPDistributeParallelForSimdDirective *D) {
9336 DeclarationNameInfo DirName;
9337 getDerived().getSema().StartOpenMPDSABlock(
9338 OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9339 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9340 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9341 return Res;
9342}
9343
9344template <typename Derived>
9345StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
9346 OMPDistributeSimdDirective *D) {
9347 DeclarationNameInfo DirName;
9348 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
9349 nullptr, D->getBeginLoc());
9350 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9351 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9352 return Res;
9353}
9354
9355template <typename Derived>
9356StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
9357 OMPTargetParallelForSimdDirective *D) {
9358 DeclarationNameInfo DirName;
9359 getDerived().getSema().StartOpenMPDSABlock(
9360 OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9361 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9362 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9363 return Res;
9364}
9365
9366template <typename Derived>
9367StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
9368 OMPTargetSimdDirective *D) {
9369 DeclarationNameInfo DirName;
9370 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
9371 D->getBeginLoc());
9372 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9373 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9374 return Res;
9375}
9376
9377template <typename Derived>
9378StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
9379 OMPTeamsDistributeDirective *D) {
9380 DeclarationNameInfo DirName;
9381 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
9382 nullptr, D->getBeginLoc());
9383 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9384 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9385 return Res;
9386}
9387
9388template <typename Derived>
9389StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
9390 OMPTeamsDistributeSimdDirective *D) {
9391 DeclarationNameInfo DirName;
9392 getDerived().getSema().StartOpenMPDSABlock(
9393 OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9394 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9395 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9396 return Res;
9397}
9398
9399template <typename Derived>
9400StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
9401 OMPTeamsDistributeParallelForSimdDirective *D) {
9402 DeclarationNameInfo DirName;
9403 getDerived().getSema().StartOpenMPDSABlock(
9404 OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
9405 D->getBeginLoc());
9406 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9407 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9408 return Res;
9409}
9410
9411template <typename Derived>
9412StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
9413 OMPTeamsDistributeParallelForDirective *D) {
9414 DeclarationNameInfo DirName;
9415 getDerived().getSema().StartOpenMPDSABlock(
9416 OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9417 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9418 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9419 return Res;
9420}
9421
9422template <typename Derived>
9423StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
9424 OMPTargetTeamsDirective *D) {
9425 DeclarationNameInfo DirName;
9426 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
9427 nullptr, D->getBeginLoc());
9428 auto Res = getDerived().TransformOMPExecutableDirective(D);
9429 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9430 return Res;
9431}
9432
9433template <typename Derived>
9434StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
9435 OMPTargetTeamsDistributeDirective *D) {
9436 DeclarationNameInfo DirName;
9437 getDerived().getSema().StartOpenMPDSABlock(
9438 OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
9439 auto Res = getDerived().TransformOMPExecutableDirective(D);
9440 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9441 return Res;
9442}
9443
9444template <typename Derived>
9445StmtResult
9446TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
9447 OMPTargetTeamsDistributeParallelForDirective *D) {
9448 DeclarationNameInfo DirName;
9449 getDerived().getSema().StartOpenMPDSABlock(
9450 OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
9451 D->getBeginLoc());
9452 auto Res = getDerived().TransformOMPExecutableDirective(D);
9453 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9454 return Res;
9455}
9456
9457template <typename Derived>
9458StmtResult TreeTransform<Derived>::
9459 TransformOMPTargetTeamsDistributeParallelForSimdDirective(
9460 OMPTargetTeamsDistributeParallelForSimdDirective *D) {
9461 DeclarationNameInfo DirName;
9462 getDerived().getSema().StartOpenMPDSABlock(
9463 OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
9464 D->getBeginLoc());
9465 auto Res = getDerived().TransformOMPExecutableDirective(D);
9466 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9467 return Res;
9468}
9469
9470template <typename Derived>
9471StmtResult
9472TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
9473 OMPTargetTeamsDistributeSimdDirective *D) {
9474 DeclarationNameInfo DirName;
9475 getDerived().getSema().StartOpenMPDSABlock(
9476 OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9477 auto Res = getDerived().TransformOMPExecutableDirective(D);
9478 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9479 return Res;
9480}
9481
9482template <typename Derived>
9483StmtResult
9484TreeTransform<Derived>::TransformOMPInteropDirective(OMPInteropDirective *D) {
9485 DeclarationNameInfo DirName;
9486 getDerived().getSema().StartOpenMPDSABlock(OMPD_interop, DirName, nullptr,
9487 D->getBeginLoc());
9488 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9489 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9490 return Res;
9491}
9492
9493template <typename Derived>
9494StmtResult
9495TreeTransform<Derived>::TransformOMPDispatchDirective(OMPDispatchDirective *D) {
9496 DeclarationNameInfo DirName;
9497 getDerived().getSema().StartOpenMPDSABlock(OMPD_dispatch, DirName, nullptr,
9498 D->getBeginLoc());
9499 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9500 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9501 return Res;
9502}
9503
9504template <typename Derived>
9505StmtResult
9506TreeTransform<Derived>::TransformOMPMaskedDirective(OMPMaskedDirective *D) {
9507 DeclarationNameInfo DirName;
9508 getDerived().getSema().StartOpenMPDSABlock(OMPD_masked, DirName, nullptr,
9509 D->getBeginLoc());
9510 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9511 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9512 return Res;
9513}
9514
9515template <typename Derived>
9516StmtResult TreeTransform<Derived>::TransformOMPGenericLoopDirective(
9517 OMPGenericLoopDirective *D) {
9518 DeclarationNameInfo DirName;
9519 getDerived().getSema().StartOpenMPDSABlock(OMPD_loop, DirName, nullptr,
9520 D->getBeginLoc());
9521 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9522 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9523 return Res;
9524}
9525
9526template <typename Derived>
9527StmtResult TreeTransform<Derived>::TransformOMPTeamsGenericLoopDirective(
9528 OMPTeamsGenericLoopDirective *D) {
9529 DeclarationNameInfo DirName;
9530 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_loop, DirName, nullptr,
9531 D->getBeginLoc());
9532 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9533 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9534 return Res;
9535}
9536
9537template <typename Derived>
9538StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsGenericLoopDirective(
9539 OMPTargetTeamsGenericLoopDirective *D) {
9540 DeclarationNameInfo DirName;
9541 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams_loop, DirName,
9542 nullptr, D->getBeginLoc());
9543 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9544 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9545 return Res;
9546}
9547
9548template <typename Derived>
9549StmtResult TreeTransform<Derived>::TransformOMPParallelGenericLoopDirective(
9550 OMPParallelGenericLoopDirective *D) {
9551 DeclarationNameInfo DirName;
9552 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_loop, DirName,
9553 nullptr, D->getBeginLoc());
9554 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9555 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9556 return Res;
9557}
9558
9559template <typename Derived>
9560StmtResult
9561TreeTransform<Derived>::TransformOMPTargetParallelGenericLoopDirective(
9562 OMPTargetParallelGenericLoopDirective *D) {
9563 DeclarationNameInfo DirName;
9564 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_loop, DirName,
9565 nullptr, D->getBeginLoc());
9566 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9567 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9568 return Res;
9569}
9570
9571//===----------------------------------------------------------------------===//
9572// OpenMP clause transformation
9573//===----------------------------------------------------------------------===//
9574template <typename Derived>
9575OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
9576 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9577 if (Cond.isInvalid())
9578 return nullptr;
9579 return getDerived().RebuildOMPIfClause(
9580 C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
9581 C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
9582}
9583
9584template <typename Derived>
9585OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
9586 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9587 if (Cond.isInvalid())
9588 return nullptr;
9589 return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
9590 C->getLParenLoc(), C->getEndLoc());
9591}
9592
9593template <typename Derived>
9594OMPClause *
9595TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
9596 ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
9597 if (NumThreads.isInvalid())
9598 return nullptr;
9599 return getDerived().RebuildOMPNumThreadsClause(
9600 NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9601}
9602
9603template <typename Derived>
9604OMPClause *
9605TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
9606 ExprResult E = getDerived().TransformExpr(C->getSafelen());
9607 if (E.isInvalid())
9608 return nullptr;
9609 return getDerived().RebuildOMPSafelenClause(
9610 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9611}
9612
9613template <typename Derived>
9614OMPClause *
9615TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
9616 ExprResult E = getDerived().TransformExpr(C->getAllocator());
9617 if (E.isInvalid())
9618 return nullptr;
9619 return getDerived().RebuildOMPAllocatorClause(
9620 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9621}
9622
9623template <typename Derived>
9624OMPClause *
9625TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
9626 ExprResult E = getDerived().TransformExpr(C->getSimdlen());
9627 if (E.isInvalid())
9628 return nullptr;
9629 return getDerived().RebuildOMPSimdlenClause(
9630 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9631}
9632
9633template <typename Derived>
9634OMPClause *TreeTransform<Derived>::TransformOMPSizesClause(OMPSizesClause *C) {
9635 SmallVector<Expr *, 4> TransformedSizes;
9636 TransformedSizes.reserve(C->getNumSizes());
9637 bool Changed = false;
9638 for (Expr *E : C->getSizesRefs()) {
9639 if (!E) {
9640 TransformedSizes.push_back(nullptr);
9641 continue;
9642 }
9643
9644 ExprResult T = getDerived().TransformExpr(E);
9645 if (T.isInvalid())
9646 return nullptr;
9647 if (E != T.get())
9648 Changed = true;
9649 TransformedSizes.push_back(T.get());
9650 }
9651
9652 if (!Changed && !getDerived().AlwaysRebuild())
9653 return C;
9654 return RebuildOMPSizesClause(TransformedSizes, C->getBeginLoc(),
9655 C->getLParenLoc(), C->getEndLoc());
9656}
9657
9658template <typename Derived>
9659OMPClause *TreeTransform<Derived>::TransformOMPFullClause(OMPFullClause *C) {
9660 if (!getDerived().AlwaysRebuild())
9661 return C;
9662 return RebuildOMPFullClause(C->getBeginLoc(), C->getEndLoc());
9663}
9664
9665template <typename Derived>
9666OMPClause *
9667TreeTransform<Derived>::TransformOMPPartialClause(OMPPartialClause *C) {
9668 ExprResult T = getDerived().TransformExpr(C->getFactor());
9669 if (T.isInvalid())
9670 return nullptr;
9671 Expr *Factor = T.get();
9672 bool Changed = Factor != C->getFactor();
9673
9674 if (!Changed && !getDerived().AlwaysRebuild())
9675 return C;
9676 return RebuildOMPPartialClause(Factor, C->getBeginLoc(), C->getLParenLoc(),
9677 C->getEndLoc());
9678}
9679
9680template <typename Derived>
9681OMPClause *
9682TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
9683 ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
9684 if (E.isInvalid())
9685 return nullptr;
9686 return getDerived().RebuildOMPCollapseClause(
9687 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9688}
9689
9690template <typename Derived>
9691OMPClause *
9692TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
9693 return getDerived().RebuildOMPDefaultClause(
9694 C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
9695 C->getLParenLoc(), C->getEndLoc());
9696}
9697
9698template <typename Derived>
9699OMPClause *
9700TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
9701 return getDerived().RebuildOMPProcBindClause(
9702 C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
9703 C->getLParenLoc(), C->getEndLoc());
9704}
9705
9706template <typename Derived>
9707OMPClause *
9708TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
9709 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9710 if (E.isInvalid())
9711 return nullptr;
9712 return getDerived().RebuildOMPScheduleClause(
9713 C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
9714 C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9715 C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
9716 C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9717}
9718
9719template <typename Derived>
9720OMPClause *
9721TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
9722 ExprResult E;
9723 if (auto *Num = C->getNumForLoops()) {
9724 E = getDerived().TransformExpr(Num);
9725 if (E.isInvalid())
9726 return nullptr;
9727 }
9728 return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
9729 C->getLParenLoc(), E.get());
9730}
9731
9732template <typename Derived>
9733OMPClause *
9734TreeTransform<Derived>::TransformOMPDetachClause(OMPDetachClause *C) {
9735 ExprResult E;
9736 if (Expr *Evt = C->getEventHandler()) {
9737 E = getDerived().TransformExpr(Evt);
9738 if (E.isInvalid())
9739 return nullptr;
9740 }
9741 return getDerived().RebuildOMPDetachClause(E.get(), C->getBeginLoc(),
9742 C->getLParenLoc(), C->getEndLoc());
9743}
9744
9745template <typename Derived>
9746OMPClause *
9747TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
9748 // No need to rebuild this clause, no template-dependent parameters.
9749 return C;
9750}
9751
9752template <typename Derived>
9753OMPClause *
9754TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
9755 // No need to rebuild this clause, no template-dependent parameters.
9756 return C;
9757}
9758
9759template <typename Derived>
9760OMPClause *
9761TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
9762 // No need to rebuild this clause, no template-dependent parameters.
9763 return C;
9764}
9765
9766template <typename Derived>
9767OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
9768 // No need to rebuild this clause, no template-dependent parameters.
9769 return C;
9770}
9771
9772template <typename Derived>
9773OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
9774 // No need to rebuild this clause, no template-dependent parameters.
9775 return C;
9776}
9777
9778template <typename Derived>
9779OMPClause *
9780TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
9781 // No need to rebuild this clause, no template-dependent parameters.
9782 return C;
9783}
9784
9785template <typename Derived>
9786OMPClause *
9787TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
9788 // No need to rebuild this clause, no template-dependent parameters.
9789 return C;
9790}
9791
9792template <typename Derived>
9793OMPClause *
9794TreeTransform<Derived>::TransformOMPCompareClause(OMPCompareClause *C) {
9795 // No need to rebuild this clause, no template-dependent parameters.
9796 return C;
9797}
9798
9799template <typename Derived>
9800OMPClause *
9801TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
9802 // No need to rebuild this clause, no template-dependent parameters.
9803 return C;
9804}
9805
9806template <typename Derived>
9807OMPClause *
9808TreeTransform<Derived>::TransformOMPAcqRelClause(OMPAcqRelClause *C) {
9809 // No need to rebuild this clause, no template-dependent parameters.
9810 return C;
9811}
9812
9813template <typename Derived>
9814OMPClause *
9815TreeTransform<Derived>::TransformOMPAcquireClause(OMPAcquireClause *C) {
9816 // No need to rebuild this clause, no template-dependent parameters.
9817 return C;
9818}
9819
9820template <typename Derived>
9821OMPClause *
9822TreeTransform<Derived>::TransformOMPReleaseClause(OMPReleaseClause *C) {
9823 // No need to rebuild this clause, no template-dependent parameters.
9824 return C;
9825}
9826
9827template <typename Derived>
9828OMPClause *
9829TreeTransform<Derived>::TransformOMPRelaxedClause(OMPRelaxedClause *C) {
9830 // No need to rebuild this clause, no template-dependent parameters.
9831 return C;
9832}
9833
9834template <typename Derived>
9835OMPClause *
9836TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
9837 // No need to rebuild this clause, no template-dependent parameters.
9838 return C;
9839}
9840
9841template <typename Derived>
9842OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
9843 // No need to rebuild this clause, no template-dependent parameters.
9844 return C;
9845}
9846
9847template <typename Derived>
9848OMPClause *
9849TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
9850 // No need to rebuild this clause, no template-dependent parameters.
9851 return C;
9852}
9853
9854template <typename Derived>
9855OMPClause *TreeTransform<Derived>::TransformOMPInitClause(OMPInitClause *C) {
9856 ExprResult IVR = getDerived().TransformExpr(C->getInteropVar());
9857 if (IVR.isInvalid())
9858 return nullptr;
9859
9860 OMPInteropInfo InteropInfo(C->getIsTarget(), C->getIsTargetSync());
9861 InteropInfo.PreferTypes.reserve(C->varlist_size() - 1);
9862 for (Expr *E : llvm::drop_begin(C->varlists())) {
9863 ExprResult ER = getDerived().TransformExpr(cast<Expr>(E));
9864 if (ER.isInvalid())
9865 return nullptr;
9866 InteropInfo.PreferTypes.push_back(ER.get());
9867 }
9868 return getDerived().RebuildOMPInitClause(IVR.get(), InteropInfo,
9869 C->getBeginLoc(), C->getLParenLoc(),
9870 C->getVarLoc(), C->getEndLoc());
9871}
9872
9873template <typename Derived>
9874OMPClause *TreeTransform<Derived>::TransformOMPUseClause(OMPUseClause *C) {
9875 ExprResult ER = getDerived().TransformExpr(C->getInteropVar());
9876 if (ER.isInvalid())
9877 return nullptr;
9878 return getDerived().RebuildOMPUseClause(ER.get(), C->getBeginLoc(),
9879 C->getLParenLoc(), C->getVarLoc(),
9880 C->getEndLoc());
9881}
9882
9883template <typename Derived>
9884OMPClause *
9885TreeTransform<Derived>::TransformOMPDestroyClause(OMPDestroyClause *C) {
9886 ExprResult ER;
9887 if (Expr *IV = C->getInteropVar()) {
9888 ER = getDerived().TransformExpr(IV);
9889 if (ER.isInvalid())
9890 return nullptr;
9891 }
9892 return getDerived().RebuildOMPDestroyClause(ER.get(), C->getBeginLoc(),
9893 C->getLParenLoc(), C->getVarLoc(),
9894 C->getEndLoc());
9895}
9896
9897template <typename Derived>
9898OMPClause *
9899TreeTransform<Derived>::TransformOMPNovariantsClause(OMPNovariantsClause *C) {
9900 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9901 if (Cond.isInvalid())
9902 return nullptr;
9903 return getDerived().RebuildOMPNovariantsClause(
9904 Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9905}
9906
9907template <typename Derived>
9908OMPClause *
9909TreeTransform<Derived>::TransformOMPNocontextClause(OMPNocontextClause *C) {
9910 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9911 if (Cond.isInvalid())
9912 return nullptr;
9913 return getDerived().RebuildOMPNocontextClause(
9914 Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9915}
9916
9917template <typename Derived>
9918OMPClause *
9919TreeTransform<Derived>::TransformOMPFilterClause(OMPFilterClause *C) {
9920 ExprResult ThreadID = getDerived().TransformExpr(C->getThreadID());
9921 if (ThreadID.isInvalid())
9922 return nullptr;
9923 return getDerived().RebuildOMPFilterClause(ThreadID.get(), C->getBeginLoc(),
9924 C->getLParenLoc(), C->getEndLoc());
9925}
9926
9927template <typename Derived>
9928OMPClause *TreeTransform<Derived>::TransformOMPAlignClause(OMPAlignClause *C) {
9929 ExprResult E = getDerived().TransformExpr(C->getAlignment());
9930 if (E.isInvalid())
9931 return nullptr;
9932 return getDerived().RebuildOMPAlignClause(E.get(), C->getBeginLoc(),
9933 C->getLParenLoc(), C->getEndLoc());
9934}
9935
9936template <typename Derived>
9937OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
9938 OMPUnifiedAddressClause *C) {
9939 llvm_unreachable("unified_address clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("unified_address clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9939)
;
9940}
9941
9942template <typename Derived>
9943OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
9944 OMPUnifiedSharedMemoryClause *C) {
9945 llvm_unreachable(::llvm::llvm_unreachable_internal("unified_shared_memory clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9946)
9946 "unified_shared_memory clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("unified_shared_memory clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9946)
;
9947}
9948
9949template <typename Derived>
9950OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
9951 OMPReverseOffloadClause *C) {
9952 llvm_unreachable("reverse_offload clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("reverse_offload clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9952)
;
9953}
9954
9955template <typename Derived>
9956OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
9957 OMPDynamicAllocatorsClause *C) {
9958 llvm_unreachable(::llvm::llvm_unreachable_internal("dynamic_allocators clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9959)
9959 "dynamic_allocators clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("dynamic_allocators clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9959)
;
9960}
9961
9962template <typename Derived>
9963OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
9964 OMPAtomicDefaultMemOrderClause *C) {
9965 llvm_unreachable(::llvm::llvm_unreachable_internal("atomic_default_mem_order clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9966)
9966 "atomic_default_mem_order clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("atomic_default_mem_order clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9966)
;
9967}
9968
9969template <typename Derived>
9970OMPClause *TreeTransform<Derived>::TransformOMPAtClause(OMPAtClause *C) {
9971 return getDerived().RebuildOMPAtClause(C->getAtKind(), C->getAtKindKwLoc(),
9972 C->getBeginLoc(), C->getLParenLoc(),
9973 C->getEndLoc());
9974}
9975
9976template <typename Derived>
9977OMPClause *
9978TreeTransform<Derived>::TransformOMPSeverityClause(OMPSeverityClause *C) {
9979 return getDerived().RebuildOMPSeverityClause(
9980 C->getSeverityKind(), C->getSeverityKindKwLoc(), C->getBeginLoc(),
9981 C->getLParenLoc(), C->getEndLoc());
9982}
9983
9984template <typename Derived>
9985OMPClause *
9986TreeTransform<Derived>::TransformOMPMessageClause(OMPMessageClause *C) {
9987 ExprResult E = getDerived().TransformExpr(C->getMessageString());
9988 if (E.isInvalid())
9989 return nullptr;
9990 return getDerived().RebuildOMPMessageClause(
9991 C->getMessageString(), C->getBeginLoc(), C->getLParenLoc(),
9992 C->getEndLoc());
9993}
9994
9995template <typename Derived>
9996OMPClause *
9997TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
9998 llvm::SmallVector<Expr *, 16> Vars;
9999 Vars.reserve(C->varlist_size());
10000 for (auto *VE : C->varlists()) {
10001 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10002 if (EVar.isInvalid())
10003 return nullptr;
10004 Vars.push_back(EVar.get());
10005 }
10006 return getDerived().RebuildOMPPrivateClause(
10007 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10008}
10009
10010template <typename Derived>
10011OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
10012 OMPFirstprivateClause *C) {
10013 llvm::SmallVector<Expr *, 16> Vars;
10014 Vars.reserve(C->varlist_size());
10015 for (auto *VE : C->varlists()) {
10016 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10017 if (EVar.isInvalid())
10018 return nullptr;
10019 Vars.push_back(EVar.get());
10020 }
10021 return getDerived().RebuildOMPFirstprivateClause(
10022 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10023}
10024
10025template <typename Derived>
10026OMPClause *
10027TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
10028 llvm::SmallVector<Expr *, 16> Vars;
10029 Vars.reserve(C->varlist_size());
10030 for (auto *VE : C->varlists()) {
10031 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10032 if (EVar.isInvalid())
10033 return nullptr;
10034 Vars.push_back(EVar.get());
10035 }
10036 return getDerived().RebuildOMPLastprivateClause(
10037 Vars, C->getKind(), C->getKindLoc(), C->getColonLoc(), C->getBeginLoc(),
10038 C->getLParenLoc(), C->getEndLoc());
10039}
10040
10041template <typename Derived>
10042OMPClause *
10043TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
10044 llvm::SmallVector<Expr *, 16> Vars;
10045 Vars.reserve(C->varlist_size());
10046 for (auto *VE : C->varlists()) {
10047 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10048 if (EVar.isInvalid())
10049 return nullptr;
10050 Vars.push_back(EVar.get());
10051 }
10052 return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
10053 C->getLParenLoc(), C->getEndLoc());
10054}
10055
10056template <typename Derived>
10057OMPClause *
10058TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
10059 llvm::SmallVector<Expr *, 16> Vars;
10060 Vars.reserve(C->varlist_size());
10061 for (auto *VE : C->varlists()) {
10062 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10063 if (EVar.isInvalid())
10064 return nullptr;
10065 Vars.push_back(EVar.get());
10066 }
10067 CXXScopeSpec ReductionIdScopeSpec;
10068 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10069
10070 DeclarationNameInfo NameInfo = C->getNameInfo();
10071 if (NameInfo.getName()) {
10072 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10073 if (!NameInfo.getName())
10074 return nullptr;
10075 }
10076 // Build a list of all UDR decls with the same names ranged by the Scopes.
10077 // The Scope boundary is a duplication of the previous decl.
10078 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10079 for (auto *E : C->reduction_ops()) {
10080 // Transform all the decls.
10081 if (E) {
10082 auto *ULE = cast<UnresolvedLookupExpr>(E);
10083 UnresolvedSet<8> Decls;
10084 for (auto *D : ULE->decls()) {
10085 NamedDecl *InstD =
10086 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10087 Decls.addDecl(InstD, InstD->getAccess());
10088 }
10089 UnresolvedReductions.push_back(
10090 UnresolvedLookupExpr::Create(
10091 SemaRef.Context, /*NamingClass=*/nullptr,
10092 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
10093 NameInfo, /*ADL=*/true, ULE->isOverloaded(),
10094 Decls.begin(), Decls.end()));
10095 } else
10096 UnresolvedReductions.push_back(nullptr);
10097 }
10098 return getDerived().RebuildOMPReductionClause(
10099 Vars, C->getModifier(), C->getBeginLoc(), C->getLParenLoc(),
10100 C->getModifierLoc(), C->getColonLoc(), C->getEndLoc(),
10101 ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10102}
10103
10104template <typename Derived>
10105OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
10106 OMPTaskReductionClause *C) {
10107 llvm::SmallVector<Expr *, 16> Vars;
10108 Vars.reserve(C->varlist_size());
10109 for (auto *VE : C->varlists()) {
10110 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10111 if (EVar.isInvalid())
10112 return nullptr;
10113 Vars.push_back(EVar.get());
10114 }
10115 CXXScopeSpec ReductionIdScopeSpec;
10116 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10117
10118 DeclarationNameInfo NameInfo = C->getNameInfo();
10119 if (NameInfo.getName()) {
10120 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10121 if (!NameInfo.getName())
10122 return nullptr;
10123 }
10124 // Build a list of all UDR decls with the same names ranged by the Scopes.
10125 // The Scope boundary is a duplication of the previous decl.
10126 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10127 for (auto *E : C->reduction_ops()) {
10128 // Transform all the decls.
10129 if (E) {
10130 auto *ULE = cast<UnresolvedLookupExpr>(E);
10131 UnresolvedSet<8> Decls;
10132 for (auto *D : ULE->decls()) {
10133 NamedDecl *InstD =
10134 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10135 Decls.addDecl(InstD, InstD->getAccess());
10136 }
10137 UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
10138 SemaRef.Context, /*NamingClass=*/nullptr,
10139 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
10140 /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
10141 } else
10142 UnresolvedReductions.push_back(nullptr);
10143 }
10144 return getDerived().RebuildOMPTaskReductionClause(
10145 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10146 C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10147}
10148
10149template <typename Derived>
10150OMPClause *
10151TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
10152 llvm::SmallVector<Expr *, 16> Vars;
10153 Vars.reserve(C->varlist_size());
10154 for (auto *VE : C->varlists()) {
10155 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10156 if (EVar.isInvalid())
10157 return nullptr;
10158 Vars.push_back(EVar.get());
10159 }
10160 CXXScopeSpec ReductionIdScopeSpec;
10161 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10162
10163 DeclarationNameInfo NameInfo = C->getNameInfo();
10164 if (NameInfo.getName()) {
10165 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10166 if (!NameInfo.getName())
10167 return nullptr;
10168 }
10169 // Build a list of all UDR decls with the same names ranged by the Scopes.
10170 // The Scope boundary is a duplication of the previous decl.
10171 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10172 for (auto *E : C->reduction_ops()) {
10173 // Transform all the decls.
10174 if (E) {
10175 auto *ULE = cast<UnresolvedLookupExpr>(E);
10176 UnresolvedSet<8> Decls;
10177 for (auto *D : ULE->decls()) {
10178 NamedDecl *InstD =
10179 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10180 Decls.addDecl(InstD, InstD->getAccess());
10181 }
10182 UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
10183 SemaRef.Context, /*NamingClass=*/nullptr,
10184 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
10185 /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
10186 } else
10187 UnresolvedReductions.push_back(nullptr);
10188 }
10189 return getDerived().RebuildOMPInReductionClause(
10190 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10191 C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10192}
10193
10194template <typename Derived>
10195OMPClause *
10196TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
10197 llvm::SmallVector<Expr *, 16> Vars;
10198 Vars.reserve(C->varlist_size());
10199 for (auto *VE : C->varlists()) {
10200 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10201 if (EVar.isInvalid())
10202 return nullptr;
10203 Vars.push_back(EVar.get());
10204 }
10205 ExprResult Step = getDerived().TransformExpr(C->getStep());
10206 if (Step.isInvalid())
10207 return nullptr;
10208 return getDerived().RebuildOMPLinearClause(
10209 Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
10210 C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
10211}
10212
10213template <typename Derived>
10214OMPClause *
10215TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
10216 llvm::SmallVector<Expr *, 16> Vars;
10217 Vars.reserve(C->varlist_size());
10218 for (auto *VE : C->varlists()) {
10219 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10220 if (EVar.isInvalid())
10221 return nullptr;
10222 Vars.push_back(EVar.get());
10223 }
10224 ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
10225 if (Alignment.isInvalid())
10226 return nullptr;
10227 return getDerived().RebuildOMPAlignedClause(
10228 Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
10229 C->getColonLoc(), C->getEndLoc());
10230}
10231
10232template <typename Derived>
10233OMPClause *
10234TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
10235 llvm::SmallVector<Expr *, 16> Vars;
10236 Vars.reserve(C->varlist_size());
10237 for (auto *VE : C->varlists()) {
10238 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10239 if (EVar.isInvalid())
10240 return nullptr;
10241 Vars.push_back(EVar.get());
10242 }
10243 return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
10244 C->getLParenLoc(), C->getEndLoc());
10245}
10246
10247template <typename Derived>
10248OMPClause *
10249TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
10250 llvm::SmallVector<Expr *, 16> Vars;
10251 Vars.reserve(C->varlist_size());
10252 for (auto *VE : C->varlists()) {
10253 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10254 if (EVar.isInvalid())
10255 return nullptr;
10256 Vars.push_back(EVar.get());
10257 }
10258 return getDerived().RebuildOMPCopyprivateClause(
10259 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10260}
10261
10262template <typename Derived>
10263OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
10264 llvm::SmallVector<Expr *, 16> Vars;
10265 Vars.reserve(C->varlist_size());
10266 for (auto *VE : C->varlists()) {
10267 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10268 if (EVar.isInvalid())
10269 return nullptr;
10270 Vars.push_back(EVar.get());
10271 }
10272 return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
10273 C->getLParenLoc(), C->getEndLoc());
10274}
10275
10276template <typename Derived>
10277OMPClause *
10278TreeTransform<Derived>::TransformOMPDepobjClause(OMPDepobjClause *C) {
10279 ExprResult E = getDerived().TransformExpr(C->getDepobj());
10280 if (E.isInvalid())
10281 return nullptr;
10282 return getDerived().RebuildOMPDepobjClause(E.get(), C->getBeginLoc(),
10283 C->getLParenLoc(), C->getEndLoc());
10284}
10285
10286template <typename Derived>
10287OMPClause *
10288TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
10289 llvm::SmallVector<Expr *, 16> Vars;
10290 Expr *DepModifier = C->getModifier();
10291 if (DepModifier) {
10292 ExprResult DepModRes = getDerived().TransformExpr(DepModifier);
10293 if (DepModRes.isInvalid())
10294 return nullptr;
10295 DepModifier = DepModRes.get();
10296 }
10297 Vars.reserve(C->varlist_size());
10298 for (auto *VE : C->varlists()) {
10299 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10300 if (EVar.isInvalid())
10301 return nullptr;
10302 Vars.push_back(EVar.get());
10303 }
10304 return getDerived().RebuildOMPDependClause(
10305 {C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(),
10306 C->getOmpAllMemoryLoc()},
10307 DepModifier, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10308}
10309
10310template <typename Derived>
10311OMPClause *
10312TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
10313 ExprResult E = getDerived().TransformExpr(C->getDevice());
10314 if (E.isInvalid())
10315 return nullptr;
10316 return getDerived().RebuildOMPDeviceClause(
10317 C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10318 C->getModifierLoc(), C->getEndLoc());
10319}
10320
10321template <typename Derived, class T>
10322bool transformOMPMappableExprListClause(
10323 TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
10324 llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
10325 DeclarationNameInfo &MapperIdInfo,
10326 llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
10327 // Transform expressions in the list.
10328 Vars.reserve(C->varlist_size());
10329 for (auto *VE : C->varlists()) {
10330 ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
10331 if (EVar.isInvalid())
10332 return true;
10333 Vars.push_back(EVar.get());
10334 }
10335 // Transform mapper scope specifier and identifier.
10336 NestedNameSpecifierLoc QualifierLoc;
10337 if (C->getMapperQualifierLoc()) {
10338 QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
10339 C->getMapperQualifierLoc());
10340 if (!QualifierLoc)
10341 return true;
10342 }
10343 MapperIdScopeSpec.Adopt(QualifierLoc);
10344 MapperIdInfo = C->getMapperIdInfo();
10345 if (MapperIdInfo.getName()) {
10346 MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
10347 if (!MapperIdInfo.getName())
10348 return true;
10349 }
10350 // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
10351 // the previous user-defined mapper lookup in dependent environment.
10352 for (auto *E : C->mapperlists()) {
10353 // Transform all the decls.
10354 if (E) {
10355 auto *ULE = cast<UnresolvedLookupExpr>(E);
10356 UnresolvedSet<8> Decls;
10357 for (auto *D : ULE->decls()) {
10358 NamedDecl *InstD =
10359 cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
10360 Decls.addDecl(InstD, InstD->getAccess());
10361 }
10362 UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
10363 TT.getSema().Context, /*NamingClass=*/nullptr,
10364 MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
10365 MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
10366 Decls.end()));
10367 } else {
10368 UnresolvedMappers.push_back(nullptr);
10369 }
10370 }
10371 return false;
10372}
10373
10374template <typename Derived>
10375OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
10376 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10377 llvm::SmallVector<Expr *, 16> Vars;
10378 Expr *IteratorModifier = C->getIteratorModifier();
10379 if (IteratorModifier) {
10380 ExprResult MapModRes = getDerived().TransformExpr(IteratorModifier);
10381 if (MapModRes.isInvalid())
10382 return nullptr;
10383 IteratorModifier = MapModRes.get();
10384 }
10385 CXXScopeSpec MapperIdScopeSpec;
10386 DeclarationNameInfo MapperIdInfo;
10387 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10388 if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
10389 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10390 return nullptr;
10391 return getDerived().RebuildOMPMapClause(
10392 IteratorModifier, C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
10393 MapperIdScopeSpec, MapperIdInfo, C->getMapType(), C->isImplicitMapType(),
10394 C->getMapLoc(), C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10395}
10396
10397template <typename Derived>
10398OMPClause *
10399TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
10400 Expr *Allocator = C->getAllocator();
10401 if (Allocator) {
10402 ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
10403 if (AllocatorRes.isInvalid())
10404 return nullptr;
10405 Allocator = AllocatorRes.get();
10406 }
10407 llvm::SmallVector<Expr *, 16> Vars;
10408 Vars.reserve(C->varlist_size());
10409 for (auto *VE : C->varlists()) {
10410 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10411 if (EVar.isInvalid())
10412 return nullptr;
10413 Vars.push_back(EVar.get());
10414 }
10415 return getDerived().RebuildOMPAllocateClause(
10416 Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10417 C->getEndLoc());
10418}
10419
10420template <typename Derived>
10421OMPClause *
10422TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
10423 ExprResult E = getDerived().TransformExpr(C->getNumTeams());
10424 if (E.isInvalid())
10425 return nullptr;
10426 return getDerived().RebuildOMPNumTeamsClause(
10427 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10428}
10429
10430template <typename Derived>
10431OMPClause *
10432TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
10433 ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
10434 if (E.isInvalid())
10435 return nullptr;
10436 return getDerived().RebuildOMPThreadLimitClause(
10437 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10438}
10439
10440template <typename Derived>
10441OMPClause *
10442TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
10443 ExprResult E = getDerived().TransformExpr(C->getPriority());
10444 if (E.isInvalid())
10445 return nullptr;
10446 return getDerived().RebuildOMPPriorityClause(
10447 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10448}
10449
10450template <typename Derived>
10451OMPClause *
10452TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
10453 ExprResult E = getDerived().TransformExpr(C->getGrainsize());
10454 if (E.isInvalid())
10455 return nullptr;
10456 return getDerived().RebuildOMPGrainsizeClause(
10457 C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10458 C->getModifierLoc(), C->getEndLoc());
10459}
10460
10461template <typename Derived>
10462OMPClause *
10463TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
10464 ExprResult E = getDerived().TransformExpr(C->getNumTasks());
10465 if (E.isInvalid())
10466 return nullptr;
10467 return getDerived().RebuildOMPNumTasksClause(
10468 C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10469 C->getModifierLoc(), C->getEndLoc());
10470}
10471
10472template <typename Derived>
10473OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
10474 ExprResult E = getDerived().TransformExpr(C->getHint());
10475 if (E.isInvalid())
10476 return nullptr;
10477 return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
10478 C->getLParenLoc(), C->getEndLoc());
10479}
10480
10481template <typename Derived>
10482OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
10483 OMPDistScheduleClause *C) {
10484 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
10485 if (E.isInvalid())
10486 return nullptr;
10487 return getDerived().RebuildOMPDistScheduleClause(
10488 C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10489 C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
10490}
10491
10492template <typename Derived>
10493OMPClause *
10494TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
10495 // Rebuild Defaultmap Clause since we need to invoke the checking of
10496 // defaultmap(none:variable-category) after template initialization.
10497 return getDerived().RebuildOMPDefaultmapClause(C->getDefaultmapModifier(),
10498 C->getDefaultmapKind(),
10499 C->getBeginLoc(),
10500 C->getLParenLoc(),
10501 C->getDefaultmapModifierLoc(),
10502 C->getDefaultmapKindLoc(),
10503 C->getEndLoc());
10504}
10505
10506template <typename Derived>
10507OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
10508 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10509 llvm::SmallVector<Expr *, 16> Vars;
10510 CXXScopeSpec MapperIdScopeSpec;
10511 DeclarationNameInfo MapperIdInfo;
10512 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10513 if (transformOMPMappableExprListClause<Derived, OMPToClause>(
10514 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10515 return nullptr;
10516 return getDerived().RebuildOMPToClause(
10517 C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10518 MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10519}
10520
10521template <typename Derived>
10522OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
10523 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10524 llvm::SmallVector<Expr *, 16> Vars;
10525 CXXScopeSpec MapperIdScopeSpec;
10526 DeclarationNameInfo MapperIdInfo;
10527 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10528 if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
10529 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10530 return nullptr;
10531 return getDerived().RebuildOMPFromClause(
10532 C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10533 MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10534}
10535
10536template <typename Derived>
10537OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
10538 OMPUseDevicePtrClause *C) {
10539 llvm::SmallVector<Expr *, 16> Vars;
10540 Vars.reserve(C->varlist_size());
10541 for (auto *VE : C->varlists()) {
10542 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10543 if (EVar.isInvalid())
10544 return nullptr;
10545 Vars.push_back(EVar.get());
10546 }
10547 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10548 return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
10549}
10550
10551template <typename Derived>
10552OMPClause *TreeTransform<Derived>::TransformOMPUseDeviceAddrClause(
10553 OMPUseDeviceAddrClause *C) {
10554 llvm::SmallVector<Expr *, 16> Vars;
10555 Vars.reserve(C->varlist_size());
10556 for (auto *VE : C->varlists()) {
10557 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10558 if (EVar.isInvalid())
10559 return nullptr;
10560 Vars.push_back(EVar.get());
10561 }
10562 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10563 return getDerived().RebuildOMPUseDeviceAddrClause(Vars, Locs);
10564}
10565
10566template <typename Derived>
10567OMPClause *
10568TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
10569 llvm::SmallVector<Expr *, 16> Vars;
10570 Vars.reserve(C->varlist_size());
10571 for (auto *VE : C->varlists()) {
10572 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10573 if (EVar.isInvalid())
10574 return nullptr;
10575 Vars.push_back(EVar.get());
10576 }
10577 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10578 return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
10579}
10580
10581template <typename Derived>
10582OMPClause *TreeTransform<Derived>::TransformOMPHasDeviceAddrClause(
10583 OMPHasDeviceAddrClause *C) {
10584 llvm::SmallVector<Expr *, 16> Vars;
10585 Vars.reserve(C->varlist_size());
10586 for (auto *VE : C->varlists()) {
10587 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10588 if (EVar.isInvalid())
10589 return nullptr;
10590 Vars.push_back(EVar.get());
10591 }
10592 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10593 return getDerived().RebuildOMPHasDeviceAddrClause(Vars, Locs);
10594}
10595
10596template <typename Derived>
10597OMPClause *
10598TreeTransform<Derived>::TransformOMPNontemporalClause(OMPNontemporalClause *C) {
10599 llvm::SmallVector<Expr *, 16> Vars;
10600 Vars.reserve(C->varlist_size());
10601 for (auto *VE : C->varlists()) {
10602 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10603 if (EVar.isInvalid())
10604 return nullptr;
10605 Vars.push_back(EVar.get());
10606 }
10607 return getDerived().RebuildOMPNontemporalClause(
10608 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10609}
10610
10611template <typename Derived>
10612OMPClause *
10613TreeTransform<Derived>::TransformOMPInclusiveClause(OMPInclusiveClause *C) {
10614 llvm::SmallVector<Expr *, 16> Vars;
10615 Vars.reserve(C->varlist_size());
10616 for (auto *VE : C->varlists()) {
10617 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10618 if (EVar.isInvalid())
10619 return nullptr;
10620 Vars.push_back(EVar.get());
10621 }
10622 return getDerived().RebuildOMPInclusiveClause(
10623 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10624}
10625
10626template <typename Derived>
10627OMPClause *
10628TreeTransform<Derived>::TransformOMPExclusiveClause(OMPExclusiveClause *C) {
10629 llvm::SmallVector<Expr *, 16> Vars;
10630 Vars.reserve(C->varlist_size());
10631 for (auto *VE : C->varlists()) {
10632 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10633 if (EVar.isInvalid())
10634 return nullptr;
10635 Vars.push_back(EVar.get());
10636 }
10637 return getDerived().RebuildOMPExclusiveClause(
10638 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10639}
10640
10641template <typename Derived>
10642OMPClause *TreeTransform<Derived>::TransformOMPUsesAllocatorsClause(
10643 OMPUsesAllocatorsClause *C) {
10644 SmallVector<Sema::UsesAllocatorsData, 16> Data;
10645 Data.reserve(C->getNumberOfAllocators());
10646 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
10647 OMPUsesAllocatorsClause::Data D = C->getAllocatorData(I);
10648 ExprResult Allocator = getDerived().TransformExpr(D.Allocator);
10649 if (Allocator.isInvalid())
10650 continue;
10651 ExprResult AllocatorTraits;
10652 if (Expr *AT = D.AllocatorTraits) {
10653 AllocatorTraits = getDerived().TransformExpr(AT);
10654 if (AllocatorTraits.isInvalid())
10655 continue;
10656 }
10657 Sema::UsesAllocatorsData &NewD = Data.emplace_back();
10658 NewD.Allocator = Allocator.get();
10659 NewD.AllocatorTraits = AllocatorTraits.get();
10660 NewD.LParenLoc = D.LParenLoc;
10661 NewD.RParenLoc = D.RParenLoc;
10662 }
10663 return getDerived().RebuildOMPUsesAllocatorsClause(
10664 Data, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10665}
10666
10667template <typename Derived>
10668OMPClause *
10669TreeTransform<Derived>::TransformOMPAffinityClause(OMPAffinityClause *C) {
10670 SmallVector<Expr *, 4> Locators;
10671 Locators.reserve(C->varlist_size());
10672 ExprResult ModifierRes;
10673 if (Expr *Modifier = C->getModifier()) {
10674 ModifierRes = getDerived().TransformExpr(Modifier);
10675 if (ModifierRes.isInvalid())
10676 return nullptr;
10677 }
10678 for (Expr *E : C->varlists()) {
10679 ExprResult Locator = getDerived().TransformExpr(E);
10680 if (Locator.isInvalid())
10681 continue;
10682 Locators.push_back(Locator.get());
10683 }
10684 return getDerived().RebuildOMPAffinityClause(
10685 C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(), C->getEndLoc(),
10686 ModifierRes.get(), Locators);
10687}
10688
10689template <typename Derived>
10690OMPClause *TreeTransform<Derived>::TransformOMPOrderClause(OMPOrderClause *C) {
10691 return getDerived().RebuildOMPOrderClause(
10692 C->getKind(), C->getKindKwLoc(), C->getBeginLoc(), C->getLParenLoc(),
10693 C->getEndLoc(), C->getModifier(), C->getModifierKwLoc());
10694}
10695
10696template <typename Derived>
10697OMPClause *TreeTransform<Derived>::TransformOMPBindClause(OMPBindClause *C) {
10698 return getDerived().RebuildOMPBindClause(
10699 C->getBindKind(), C->getBindKindLoc(), C->getBeginLoc(),
10700 C->getLParenLoc(), C->getEndLoc());
10701}
10702
10703template <typename Derived>
10704OMPClause *TreeTransform<Derived>::TransformOMPXDynCGroupMemClause(
10705 OMPXDynCGroupMemClause *C) {
10706 ExprResult Size = getDerived().TransformExpr(C->getSize());
10707 if (Size.isInvalid())
10708 return nullptr;
10709 return getDerived().RebuildOMPXDynCGroupMemClause(
10710 Size.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10711}
10712
10713//===----------------------------------------------------------------------===//
10714// Expression transformation
10715//===----------------------------------------------------------------------===//
10716template<typename Derived>
10717ExprResult
10718TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
10719 return TransformExpr(E->getSubExpr());
10720}
10721
10722template <typename Derived>
10723ExprResult TreeTransform<Derived>::TransformSYCLUniqueStableNameExpr(
10724 SYCLUniqueStableNameExpr *E) {
10725 if (!E->isTypeDependent())
10726 return E;
10727
10728 TypeSourceInfo *NewT = getDerived().TransformType(E->getTypeSourceInfo());
10729
10730 if (!NewT)
10731 return ExprError();
10732
10733 if (!getDerived().AlwaysRebuild() && E->getTypeSourceInfo() == NewT)
10734 return E;
10735
10736 return getDerived().RebuildSYCLUniqueStableNameExpr(
10737 E->getLocation(), E->getLParenLocation(), E->getRParenLocation(), NewT);
10738}
10739
10740template<typename Derived>
10741ExprResult
10742TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
10743 if (!E->isTypeDependent())
10744 return E;
10745
10746 return getDerived().RebuildPredefinedExpr(E->getLocation(),
10747 E->getIdentKind());
10748}
10749
10750template<typename Derived>
10751ExprResult
10752TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
10753 NestedNameSpecifierLoc QualifierLoc;
10754 if (E->getQualifierLoc()) {
10755 QualifierLoc
10756 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10757 if (!QualifierLoc)
10758 return ExprError();
10759 }
10760
10761 ValueDecl *ND
10762 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
10763 E->getDecl()));
10764 if (!ND)
10765 return ExprError();
10766
10767 NamedDecl *Found = ND;
10768 if (E->getFoundDecl() != E->getDecl()) {
10769 Found = cast_or_null<NamedDecl>(
10770 getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
10771 if (!Found)
10772 return ExprError();
10773 }
10774
10775 DeclarationNameInfo NameInfo = E->getNameInfo();
10776 if (NameInfo.getName()) {
10777 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10778 if (!NameInfo.getName())
10779 return ExprError();
10780 }
10781
10782 if (!getDerived().AlwaysRebuild() &&
10783 QualifierLoc == E->getQualifierLoc() &&
10784 ND == E->getDecl() &&
10785 Found == E->getFoundDecl() &&
10786 NameInfo.getName() == E->getDecl()->getDeclName() &&
10787 !E->hasExplicitTemplateArgs()) {
10788
10789 // Mark it referenced in the new context regardless.
10790 // FIXME: this is a bit instantiation-specific.
10791 SemaRef.MarkDeclRefReferenced(E);
10792
10793 return E;
10794 }
10795
10796 TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
10797 if (E->hasExplicitTemplateArgs()) {
10798 TemplateArgs = &TransArgs;
10799 TransArgs.setLAngleLoc(E->getLAngleLoc());
10800 TransArgs.setRAngleLoc(E->getRAngleLoc());
10801 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10802 E->getNumTemplateArgs(),
10803 TransArgs))
10804 return ExprError();
10805 }
10806
10807 return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
10808 Found, TemplateArgs);
10809}
10810
10811template<typename Derived>
10812ExprResult
10813TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
10814 return E;
10815}
10816
10817template <typename Derived>
10818ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
10819 FixedPointLiteral *E) {
10820 return E;
10821}
10822
10823template<typename Derived>
10824ExprResult
10825TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
10826 return E;
10827}
10828
10829template<typename Derived>
10830ExprResult
10831TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
10832 return E;
10833}
10834
10835template<typename Derived>
10836ExprResult
10837TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
10838 return E;
10839}
10840
10841template<typename Derived>
10842ExprResult
10843TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
10844 return E;
10845}
10846
10847template<typename Derived>
10848ExprResult
10849TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
10850 return getDerived().TransformCallExpr(E);
10851}
10852
10853template<typename Derived>
10854ExprResult
10855TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
10856 ExprResult ControllingExpr =
10857 getDerived().TransformExpr(E->getControllingExpr());
10858 if (ControllingExpr.isInvalid())
10859 return ExprError();
10860
10861 SmallVector<Expr *, 4> AssocExprs;
10862 SmallVector<TypeSourceInfo *, 4> AssocTypes;
10863 for (const GenericSelectionExpr::Association Assoc : E->associations()) {
10864 TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
10865 if (TSI) {
10866 TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
10867 if (!AssocType)
10868 return ExprError();
10869 AssocTypes.push_back(AssocType);
10870 } else {
10871 AssocTypes.push_back(nullptr);
10872 }
10873
10874 ExprResult AssocExpr =
10875 getDerived().TransformExpr(Assoc.getAssociationExpr());
10876 if (AssocExpr.isInvalid())
10877 return ExprError();
10878 AssocExprs.push_back(AssocExpr.get());
10879 }
10880
10881 return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
10882 E->getDefaultLoc(),
10883 E->getRParenLoc(),
10884 ControllingExpr.get(),
10885 AssocTypes,
10886 AssocExprs);
10887}
10888
10889template<typename Derived>
10890ExprResult
10891TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
10892 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10893 if (SubExpr.isInvalid())
10894 return ExprError();
10895
10896 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10897 return E;
10898
10899 return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
10900 E->getRParen());
10901}
10902
10903/// The operand of a unary address-of operator has special rules: it's
10904/// allowed to refer to a non-static member of a class even if there's no 'this'
10905/// object available.
10906template<typename Derived>
10907ExprResult
10908TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
10909 if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
10910 return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
10911 else
10912 return getDerived().TransformExpr(E);
10913}
10914
10915template<typename Derived>
10916ExprResult
10917TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
10918 ExprResult SubExpr;
10919 if (E->getOpcode() == UO_AddrOf)
10920 SubExpr = TransformAddressOfOperand(E->getSubExpr());
10921 else
10922 SubExpr = TransformExpr(E->getSubExpr());
10923 if (SubExpr.isInvalid())
10924 return ExprError();
10925
10926 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10927 return E;
10928
10929 return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
10930 E->getOpcode(),
10931 SubExpr.get());
10932}
10933
10934template<typename Derived>
10935ExprResult
10936TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
10937 // Transform the type.
10938 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
10939 if (!Type)
10940 return ExprError();
10941
10942 // Transform all of the components into components similar to what the
10943 // parser uses.
10944 // FIXME: It would be slightly more efficient in the non-dependent case to
10945 // just map FieldDecls, rather than requiring the rebuilder to look for
10946 // the fields again. However, __builtin_offsetof is rare enough in
10947 // template code that we don't care.
10948 bool ExprChanged = false;
10949 typedef Sema::OffsetOfComponent Component;
10950 SmallVector<Component, 4> Components;
10951 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
10952 const OffsetOfNode &ON = E->getComponent(I);
10953 Component Comp;
10954 Comp.isBrackets = true;
10955 Comp.LocStart = ON.getSourceRange().getBegin();
10956 Comp.LocEnd = ON.getSourceRange().getEnd();
10957 switch (ON.getKind()) {
10958 case OffsetOfNode::Array: {
10959 Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
10960 ExprResult Index = getDerived().TransformExpr(FromIndex);
10961 if (Index.isInvalid())
10962 return ExprError();
10963
10964 ExprChanged = ExprChanged || Index.get() != FromIndex;
10965 Comp.isBrackets = true;
10966 Comp.U.E = Index.get();
10967 break;
10968 }
10969
10970 case OffsetOfNode::Field:
10971 case OffsetOfNode::Identifier:
10972 Comp.isBrackets = false;
10973 Comp.U.IdentInfo = ON.getFieldName();
10974 if (!Comp.U.IdentInfo)
10975 continue;
10976
10977 break;
10978
10979 case OffsetOfNode::Base:
10980 // Will be recomputed during the rebuild.
10981 continue;
10982 }
10983
10984 Components.push_back(Comp);
10985 }
10986
10987 // If nothing changed, retain the existing expression.
10988 if (!getDerived().AlwaysRebuild() &&
10989 Type == E->getTypeSourceInfo() &&
10990 !ExprChanged)
10991 return E;
10992
10993 // Build a new offsetof expression.
10994 return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
10995 Components, E->getRParenLoc());
10996}
10997
10998template<typename Derived>
10999ExprResult
11000TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
11001 assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&(static_cast <bool> ((!E->getSourceExpr() || getDerived
().AlreadyTransformed(E->getType())) && "opaque value expression requires transformation"
) ? void (0) : __assert_fail ("(!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) && \"opaque value expression requires transformation\""
, "clang/lib/Sema/TreeTransform.h", 11002, __extension__ __PRETTY_FUNCTION__
))
11002 "opaque value expression requires transformation")(static_cast <bool> ((!E->getSourceExpr() || getDerived
().AlreadyTransformed(E->getType())) && "opaque value expression requires transformation"
) ? void (0) : __assert_fail ("(!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) && \"opaque value expression requires transformation\""
, "clang/lib/Sema/TreeTransform.h", 11002, __extension__ __PRETTY_FUNCTION__
))
;
11003 return E;
11004}
11005
11006template<typename Derived>
11007ExprResult
11008TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
11009 return E;
11010}
11011
11012template <typename Derived>
11013ExprResult TreeTransform<Derived>::TransformRecoveryExpr(RecoveryExpr *E) {
11014 llvm::SmallVector<Expr *, 8> Children;
11015 bool Changed = false;
11016 for (Expr *C : E->subExpressions()) {
11017 ExprResult NewC = getDerived().TransformExpr(C);
11018 if (NewC.isInvalid())
11019 return ExprError();
11020 Children.push_back(NewC.get());
11021
11022 Changed |= NewC.get() != C;
11023 }
11024 if (!getDerived().AlwaysRebuild() && !Changed)
11025 return E;
11026 return getDerived().RebuildRecoveryExpr(E->getBeginLoc(), E->getEndLoc(),
11027 Children, E->getType());
11028}
11029
11030template<typename Derived>
11031ExprResult
11032TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
11033 // Rebuild the syntactic form. The original syntactic form has
11034 // opaque-value expressions in it, so strip those away and rebuild
11035 // the result. This is a really awful way of doing this, but the
11036 // better solution (rebuilding the semantic expressions and
11037 // rebinding OVEs as necessary) doesn't work; we'd need
11038 // TreeTransform to not strip away implicit conversions.
11039 Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
11040 ExprResult result = getDerived().TransformExpr(newSyntacticForm);
11041 if (result.isInvalid()) return ExprError();
11042
11043 // If that gives us a pseudo-object result back, the pseudo-object
11044 // expression must have been an lvalue-to-rvalue conversion which we
11045 // should reapply.
11046 if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
11047 result = SemaRef.checkPseudoObjectRValue(result.get());
11048
11049 return result;
11050}
11051
11052template<typename Derived>
11053ExprResult
11054TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
11055 UnaryExprOrTypeTraitExpr *E) {
11056 if (E->isArgumentType()) {
11057 TypeSourceInfo *OldT = E->getArgumentTypeInfo();
11058
11059 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11060 if (!NewT)
11061 return ExprError();
11062
11063 if (!getDerived().AlwaysRebuild() && OldT == NewT)
11064 return E;
11065
11066 return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
11067 E->getKind(),
11068 E->getSourceRange());
11069 }
11070
11071 // C++0x [expr.sizeof]p1:
11072 // The operand is either an expression, which is an unevaluated operand
11073 // [...]
11074 EnterExpressionEvaluationContext Unevaluated(
11075 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
11076 Sema::ReuseLambdaContextDecl);
11077
11078 // Try to recover if we have something like sizeof(T::X) where X is a type.
11079 // Notably, there must be *exactly* one set of parens if X is a type.
11080 TypeSourceInfo *RecoveryTSI = nullptr;
11081 ExprResult SubExpr;
11082 auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
11083 if (auto *DRE =
11084 PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
11085 SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
11086 PE, DRE, false, &RecoveryTSI);
11087 else
11088 SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
11089
11090 if (RecoveryTSI) {
11091 return getDerived().RebuildUnaryExprOrTypeTrait(
11092 RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
11093 } else if (SubExpr.isInvalid())
11094 return ExprError();
11095
11096 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
11097 return E;
11098
11099 return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
11100 E->getOperatorLoc(),
11101 E->getKind(),
11102 E->getSourceRange());
11103}
11104
11105template<typename Derived>
11106ExprResult
11107TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
11108 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11109 if (LHS.isInvalid())
11110 return ExprError();
11111
11112 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11113 if (RHS.isInvalid())
11114 return ExprError();
11115
11116
11117 if (!getDerived().AlwaysRebuild() &&
11118 LHS.get() == E->getLHS() &&
11119 RHS.get() == E->getRHS())
11120 return E;
11121
11122 return getDerived().RebuildArraySubscriptExpr(
11123 LHS.get(),
11124 /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
11125}
11126
11127template <typename Derived>
11128ExprResult
11129TreeTransform<Derived>::TransformMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
11130 ExprResult Base = getDerived().TransformExpr(E->getBase());
11131 if (Base.isInvalid())
11132 return ExprError();
11133
11134 ExprResult RowIdx = getDerived().TransformExpr(E->getRowIdx());
11135 if (RowIdx.isInvalid())
11136 return ExprError();
11137
11138 ExprResult ColumnIdx = getDerived().TransformExpr(E->getColumnIdx());
11139 if (ColumnIdx.isInvalid())
11140 return ExprError();
11141
11142 if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
11143 RowIdx.get() == E->getRowIdx() && ColumnIdx.get() == E->getColumnIdx())
11144 return E;
11145
11146 return getDerived().RebuildMatrixSubscriptExpr(
11147 Base.get(), RowIdx.get(), ColumnIdx.get(), E->getRBracketLoc());
11148}
11149
11150template <typename Derived>
11151ExprResult
11152TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
11153 ExprResult Base = getDerived().TransformExpr(E->getBase());
11154 if (Base.isInvalid())
11155 return ExprError();
11156
11157 ExprResult LowerBound;
11158 if (E->getLowerBound()) {
11159 LowerBound = getDerived().TransformExpr(E->getLowerBound());
11160 if (LowerBound.isInvalid())
11161 return ExprError();
11162 }
11163
11164 ExprResult Length;
11165 if (E->getLength()) {
11166 Length = getDerived().TransformExpr(E->getLength());
11167 if (Length.isInvalid())
11168 return ExprError();
11169 }
11170
11171 ExprResult Stride;
11172 if (Expr *Str = E->getStride()) {
11173 Stride = getDerived().TransformExpr(Str);
11174 if (Stride.isInvalid())
11175 return ExprError();
11176 }
11177
11178 if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
11179 LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
11180 return E;
11181
11182 return getDerived().RebuildOMPArraySectionExpr(
11183 Base.get(), E->getBase()->getEndLoc(), LowerBound.get(),
11184 E->getColonLocFirst(), E->getColonLocSecond(), Length.get(), Stride.get(),
11185 E->getRBracketLoc());
11186}
11187
11188template <typename Derived>
11189ExprResult
11190TreeTransform<Derived>::TransformOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
11191 ExprResult Base = getDerived().TransformExpr(E->getBase());
11192 if (Base.isInvalid())
11193 return ExprError();
11194
11195 SmallVector<Expr *, 4> Dims;
11196 bool ErrorFound = false;
11197 for (Expr *Dim : E->getDimensions()) {
11198 ExprResult DimRes = getDerived().TransformExpr(Dim);
11199 if (DimRes.isInvalid()) {
11200 ErrorFound = true;
11201 continue;
11202 }
11203 Dims.push_back(DimRes.get());
11204 }
11205
11206 if (ErrorFound)
11207 return ExprError();
11208 return getDerived().RebuildOMPArrayShapingExpr(Base.get(), E->getLParenLoc(),
11209 E->getRParenLoc(), Dims,
11210 E->getBracketsRanges());
11211}
11212
11213template <typename Derived>
11214ExprResult
11215TreeTransform<Derived>::TransformOMPIteratorExpr(OMPIteratorExpr *E) {
11216 unsigned NumIterators = E->numOfIterators();
11217 SmallVector<Sema::OMPIteratorData, 4> Data(NumIterators);
11218
11219 bool ErrorFound = false;
11220 bool NeedToRebuild = getDerived().AlwaysRebuild();
11221 for (unsigned I = 0; I < NumIterators; ++I) {
11222 auto *D = cast<VarDecl>(E->getIteratorDecl(I));
11223 Data[I].DeclIdent = D->getIdentifier();
11224 Data[I].DeclIdentLoc = D->getLocation();
11225 if (D->getLocation() == D->getBeginLoc()) {
11226 assert(SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) &&(static_cast <bool> (SemaRef.Context.hasSameType(D->
getType(), SemaRef.Context.IntTy) && "Implicit type must be int."
) ? void (0) : __assert_fail ("SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) && \"Implicit type must be int.\""
, "clang/lib/Sema/TreeTransform.h", 11227, __extension__ __PRETTY_FUNCTION__
))
11227 "Implicit type must be int.")(static_cast <bool> (SemaRef.Context.hasSameType(D->
getType(), SemaRef.Context.IntTy) && "Implicit type must be int."
) ? void (0) : __assert_fail ("SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) && \"Implicit type must be int.\""
, "clang/lib/Sema/TreeTransform.h", 11227, __extension__ __PRETTY_FUNCTION__
))
;
11228 } else {
11229 TypeSourceInfo *TSI = getDerived().TransformType(D->getTypeSourceInfo());
11230 QualType DeclTy = getDerived().TransformType(D->getType());
11231 Data[I].Type = SemaRef.CreateParsedType(DeclTy, TSI);
11232 }
11233 OMPIteratorExpr::IteratorRange Range = E->getIteratorRange(I);
11234 ExprResult Begin = getDerived().TransformExpr(Range.Begin);
11235 ExprResult End = getDerived().TransformExpr(Range.End);
11236 ExprResult Step = getDerived().TransformExpr(Range.Step);
11237 ErrorFound = ErrorFound ||
11238 !(!D->getTypeSourceInfo() || (Data[I].Type.getAsOpaquePtr() &&
11239 !Data[I].Type.get().isNull())) ||
11240 Begin.isInvalid() || End.isInvalid() || Step.isInvalid();
11241 if (ErrorFound)
11242 continue;
11243 Data[I].Range.Begin = Begin.get();
11244 Data[I].Range.End = End.get();
11245 Data[I].Range.Step = Step.get();
11246 Data[I].AssignLoc = E->getAssignLoc(I);
11247 Data[I].ColonLoc = E->getColonLoc(I);
11248 Data[I].SecColonLoc = E->getSecondColonLoc(I);
11249 NeedToRebuild =
11250 NeedToRebuild ||
11251 (D->getTypeSourceInfo() && Data[I].Type.get().getTypePtrOrNull() !=
11252 D->getType().getTypePtrOrNull()) ||
11253 Range.Begin != Data[I].Range.Begin || Range.End != Data[I].Range.End ||
11254 Range.Step != Data[I].Range.Step;
11255 }
11256 if (ErrorFound)
11257 return ExprError();
11258 if (!NeedToRebuild)
11259 return E;
11260
11261 ExprResult Res = getDerived().RebuildOMPIteratorExpr(
11262 E->getIteratorKwLoc(), E->getLParenLoc(), E->getRParenLoc(), Data);
11263 if (!Res.isUsable())
11264 return Res;
11265 auto *IE = cast<OMPIteratorExpr>(Res.get());
11266 for (unsigned I = 0; I < NumIterators; ++I)
11267 getDerived().transformedLocalDecl(E->getIteratorDecl(I),
11268 IE->getIteratorDecl(I));
11269 return Res;
11270}
11271
11272template<typename Derived>
11273ExprResult
11274TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
11275 // Transform the callee.
11276 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11277 if (Callee.isInvalid())
11278 return ExprError();
11279
11280 // Transform arguments.
11281 bool ArgChanged = false;
11282 SmallVector<Expr*, 8> Args;
11283 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11284 &ArgChanged))
11285 return ExprError();
11286
11287 if (!getDerived().AlwaysRebuild() &&
11288 Callee.get() == E->getCallee() &&
11289 !ArgChanged)
11290 return SemaRef.MaybeBindToTemporary(E);
11291
11292 // FIXME: Wrong source location information for the '('.
11293 SourceLocation FakeLParenLoc
11294 = ((Expr *)Callee.get())->getSourceRange().getBegin();
11295
11296 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11297 if (E->hasStoredFPFeatures()) {
11298 FPOptionsOverride NewOverrides = E->getFPFeatures();
11299 getSema().CurFPFeatures =
11300 NewOverrides.applyOverrides(getSema().getLangOpts());
11301 getSema().FpPragmaStack.CurrentValue = NewOverrides;
11302 }
11303
11304 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
11305 Args,
11306 E->getRParenLoc());
11307}
11308
11309template<typename Derived>
11310ExprResult
11311TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
11312 ExprResult Base = getDerived().TransformExpr(E->getBase());
11313 if (Base.isInvalid())
11314 return ExprError();
11315
11316 NestedNameSpecifierLoc QualifierLoc;
11317 if (E->hasQualifier()) {
11318 QualifierLoc
11319 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
11320
11321 if (!QualifierLoc)
11322 return ExprError();
11323 }
11324 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11325
11326 ValueDecl *Member
11327 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
11328 E->getMemberDecl()));
11329 if (!Member)
11330 return ExprError();
11331
11332 NamedDecl *FoundDecl = E->getFoundDecl();
11333 if (FoundDecl == E->getMemberDecl()) {
11334 FoundDecl = Member;
11335 } else {
11336 FoundDecl = cast_or_null<NamedDecl>(
11337 getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
11338 if (!FoundDecl)
11339 return ExprError();
11340 }
11341
11342 if (!getDerived().AlwaysRebuild() &&
11343 Base.get() == E->getBase() &&
11344 QualifierLoc == E->getQualifierLoc() &&
11345 Member == E->getMemberDecl() &&
11346 FoundDecl == E->getFoundDecl() &&
11347 !E->hasExplicitTemplateArgs()) {
11348
11349 // Skip for member expression of (this->f), rebuilt thisi->f is needed
11350 // for Openmp where the field need to be privatizized in the case.
11351 if (!(isa<CXXThisExpr>(E->getBase()) &&
11352 getSema().isOpenMPRebuildMemberExpr(cast<ValueDecl>(Member)))) {
11353 // Mark it referenced in the new context regardless.
11354 // FIXME: this is a bit instantiation-specific.
11355 SemaRef.MarkMemberReferenced(E);
11356 return E;
11357 }
11358 }
11359
11360 TemplateArgumentListInfo TransArgs;
11361 if (E->hasExplicitTemplateArgs()) {
11362 TransArgs.setLAngleLoc(E->getLAngleLoc());
11363 TransArgs.setRAngleLoc(E->getRAngleLoc());
11364 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11365 E->getNumTemplateArgs(),
11366 TransArgs))
11367 return ExprError();
11368 }
11369
11370 // FIXME: Bogus source location for the operator
11371 SourceLocation FakeOperatorLoc =
11372 SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
11373
11374 // FIXME: to do this check properly, we will need to preserve the
11375 // first-qualifier-in-scope here, just in case we had a dependent
11376 // base (and therefore couldn't do the check) and a
11377 // nested-name-qualifier (and therefore could do the lookup).
11378 NamedDecl *FirstQualifierInScope = nullptr;
11379 DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
11380 if (MemberNameInfo.getName()) {
11381 MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
11382 if (!MemberNameInfo.getName())
11383 return ExprError();
11384 }
11385
11386 return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
11387 E->isArrow(),
11388 QualifierLoc,
11389 TemplateKWLoc,
11390 MemberNameInfo,
11391 Member,
11392 FoundDecl,
11393 (E->hasExplicitTemplateArgs()
11394 ? &TransArgs : nullptr),
11395 FirstQualifierInScope);
11396}
11397
11398template<typename Derived>
11399ExprResult
11400TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
11401 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11402 if (LHS.isInvalid())
11403 return ExprError();
11404
11405 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11406 if (RHS.isInvalid())
11407 return ExprError();
11408
11409 if (!getDerived().AlwaysRebuild() &&
11410 LHS.get() == E->getLHS() &&
11411 RHS.get() == E->getRHS())
11412 return E;
11413
11414 if (E->isCompoundAssignmentOp())
11415 // FPFeatures has already been established from trailing storage
11416 return getDerived().RebuildBinaryOperator(
11417 E->getOperatorLoc(), E->getOpcode(), LHS.get(), RHS.get());
11418 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11419 FPOptionsOverride NewOverrides(E->getFPFeatures());
11420 getSema().CurFPFeatures =
11421 NewOverrides.applyOverrides(getSema().getLangOpts());
11422 getSema().FpPragmaStack.CurrentValue = NewOverrides;
11423 return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
11424 LHS.get(), RHS.get());
11425}
11426
11427template <typename Derived>
11428ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
11429 CXXRewrittenBinaryOperator *E) {
11430 CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
11431
11432 ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
11433 if (LHS.isInvalid())
11434 return ExprError();
11435
11436 ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
11437 if (RHS.isInvalid())
11438 return ExprError();
11439
11440 // Extract the already-resolved callee declarations so that we can restrict
11441 // ourselves to using them as the unqualified lookup results when rebuilding.
11442 UnresolvedSet<2> UnqualLookups;
11443 bool ChangedAnyLookups = false;
11444 Expr *PossibleBinOps[] = {E->getSemanticForm(),
11445 const_cast<Expr *>(Decomp.InnerBinOp)};
11446 for (Expr *PossibleBinOp : PossibleBinOps) {
11447 auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
11448 if (!Op)
11449 continue;
11450 auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
11451 if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
11452 continue;
11453
11454 // Transform the callee in case we built a call to a local extern
11455 // declaration.
11456 NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
11457 E->getOperatorLoc(), Callee->getFoundDecl()));
11458 if (!Found)
11459 return ExprError();
11460 if (Found != Callee->getFoundDecl())
11461 ChangedAnyLookups = true;
11462 UnqualLookups.addDecl(Found);
11463 }
11464
11465 if (!getDerived().AlwaysRebuild() && !ChangedAnyLookups &&
11466 LHS.get() == Decomp.LHS && RHS.get() == Decomp.RHS) {
11467 // Mark all functions used in the rewrite as referenced. Note that when
11468 // a < b is rewritten to (a <=> b) < 0, both the <=> and the < might be
11469 // function calls, and/or there might be a user-defined conversion sequence
11470 // applied to the operands of the <.
11471 // FIXME: this is a bit instantiation-specific.
11472 const Expr *StopAt[] = {Decomp.LHS, Decomp.RHS};
11473 SemaRef.MarkDeclarationsReferencedInExpr(E, false, StopAt);
11474 return E;
11475 }
11476
11477 return getDerived().RebuildCXXRewrittenBinaryOperator(
11478 E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
11479}
11480
11481template<typename Derived>
11482ExprResult
11483TreeTransform<Derived>::TransformCompoundAssignOperator(
11484 CompoundAssignOperator *E) {
11485 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11486 FPOptionsOverride NewOverrides(E->getFPFeatures());
11487 getSema().CurFPFeatures =
11488 NewOverrides.applyOverrides(getSema().getLangOpts());
11489 getSema().FpPragmaStack.CurrentValue = NewOverrides;
11490 return getDerived().TransformBinaryOperator(E);
11491}
11492
11493template<typename Derived>
11494ExprResult TreeTransform<Derived>::
11495TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
11496 // Just rebuild the common and RHS expressions and see whether we
11497 // get any changes.
11498
11499 ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
11500 if (commonExpr.isInvalid())
11501 return ExprError();
11502
11503 ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
11504 if (rhs.isInvalid())
11505 return ExprError();
11506
11507 if (!getDerived().AlwaysRebuild() &&
11508 commonExpr.get() == e->getCommon() &&
11509 rhs.get() == e->getFalseExpr())
11510 return e;
11511
11512 return getDerived().RebuildConditionalOperator(commonExpr.get(),
11513 e->getQuestionLoc(),
11514 nullptr,
11515 e->getColonLoc(),
11516 rhs.get());
11517}
11518
11519template<typename Derived>
11520ExprResult
11521TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
11522 ExprResult Cond = getDerived().TransformExpr(E->getCond());
11523 if (Cond.isInvalid())
11524 return ExprError();
11525
11526 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11527 if (LHS.isInvalid())
11528 return ExprError();
11529
11530 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11531 if (RHS.isInvalid())
11532 return ExprError();
11533
11534 if (!getDerived().AlwaysRebuild() &&
11535 Cond.get() == E->getCond() &&
11536 LHS.get() == E->getLHS() &&
11537 RHS.get() == E->getRHS())
11538 return E;
11539
11540 return getDerived().RebuildConditionalOperator(Cond.get(),
11541 E->getQuestionLoc(),
11542 LHS.get(),
11543 E->getColonLoc(),
11544 RHS.get());
11545}
11546
11547template<typename Derived>
11548ExprResult
11549TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
11550 // Implicit casts are eliminated during transformation, since they
11551 // will be recomputed by semantic analysis after transformation.
11552 return getDerived().TransformExpr(E->getSubExprAsWritten());
11553}
11554
11555template<typename Derived>
11556ExprResult
11557TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
11558 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11559 if (!Type)
11560 return ExprError();
11561
11562 ExprResult SubExpr
11563 = getDerived().TransformExpr(E->getSubExprAsWritten());
11564 if (SubExpr.isInvalid())
11565 return ExprError();
11566
11567 if (!getDerived().AlwaysRebuild() &&
11568 Type == E->getTypeInfoAsWritten() &&
11569 SubExpr.get() == E->getSubExpr())
11570 return E;
11571
11572 return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
11573 Type,
11574 E->getRParenLoc(),
11575 SubExpr.get());
11576}
11577
11578template<typename Derived>
11579ExprResult
11580TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
11581 TypeSourceInfo *OldT = E->getTypeSourceInfo();
11582 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11583 if (!NewT)
11584 return ExprError();
11585
11586 ExprResult Init = getDerived().TransformExpr(E->getInitializer());
11587 if (Init.isInvalid())
11588 return ExprError();
11589
11590 if (!getDerived().AlwaysRebuild() &&
11591 OldT == NewT &&
11592 Init.get() == E->getInitializer())
11593 return SemaRef.MaybeBindToTemporary(E);
11594
11595 // Note: the expression type doesn't necessarily match the
11596 // type-as-written, but that's okay, because it should always be
11597 // derivable from the initializer.
11598
11599 return getDerived().RebuildCompoundLiteralExpr(
11600 E->getLParenLoc(), NewT,
11601 /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
11602}
11603
11604template<typename Derived>
11605ExprResult
11606TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
11607 ExprResult Base = getDerived().TransformExpr(E->getBase());
11608 if (Base.isInvalid())
11609 return ExprError();
11610
11611 if (!getDerived().AlwaysRebuild() &&
11612 Base.get() == E->getBase())
11613 return E;
11614
11615 // FIXME: Bad source location
11616 SourceLocation FakeOperatorLoc =
11617 SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
11618 return getDerived().RebuildExtVectorElementExpr(
11619 Base.get(), FakeOperatorLoc, E->isArrow(), E->getAccessorLoc(),
11620 E->getAccessor());
11621}
11622
11623template<typename Derived>
11624ExprResult
11625TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
11626 if (InitListExpr *Syntactic = E->getSyntacticForm())
11627 E = Syntactic;
11628
11629 bool InitChanged = false;
11630
11631 EnterExpressionEvaluationContext Context(
11632 getSema(), EnterExpressionEvaluationContext::InitList);
11633
11634 SmallVector<Expr*, 4> Inits;
11635 if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
11636 Inits, &InitChanged))
11637 return ExprError();
11638
11639 if (!getDerived().AlwaysRebuild() && !InitChanged) {
11640 // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
11641 // in some cases. We can't reuse it in general, because the syntactic and
11642 // semantic forms are linked, and we can't know that semantic form will
11643 // match even if the syntactic form does.
11644 }
11645
11646 return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
11647 E->getRBraceLoc());
11648}
11649
11650template<typename Derived>
11651ExprResult
11652TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
11653 Designation Desig;
11654
11655 // transform the initializer value
11656 ExprResult Init = getDerived().TransformExpr(E->getInit());
11657 if (Init.isInvalid())
11658 return ExprError();
11659
11660 // transform the designators.
11661 SmallVector<Expr*, 4> ArrayExprs;
11662 bool ExprChanged = false;
11663 for (const DesignatedInitExpr::Designator &D : E->designators()) {
11664 if (D.isFieldDesignator()) {
11665 Desig.AddDesignator(Designator::CreateFieldDesignator(
11666 D.getFieldName(), D.getDotLoc(), D.getFieldLoc()));
11667 if (D.getFieldDecl()) {
11668 FieldDecl *Field = cast_or_null<FieldDecl>(
11669 getDerived().TransformDecl(D.getFieldLoc(), D.getFieldDecl()));
11670 if (Field != D.getFieldDecl())
11671 // Rebuild the expression when the transformed FieldDecl is
11672 // different to the already assigned FieldDecl.
11673 ExprChanged = true;
11674 } else {
11675 // Ensure that the designator expression is rebuilt when there isn't
11676 // a resolved FieldDecl in the designator as we don't want to assign
11677 // a FieldDecl to a pattern designator that will be instantiated again.
11678 ExprChanged = true;
11679 }
11680 continue;
11681 }
11682
11683 if (D.isArrayDesignator()) {
11684 ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
11685 if (Index.isInvalid())
11686 return ExprError();
11687
11688 Desig.AddDesignator(
11689 Designator::CreateArrayDesignator(Index.get(), D.getLBracketLoc()));
11690
11691 ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
11692 ArrayExprs.push_back(Index.get());
11693 continue;
11694 }
11695
11696 assert(D.isArrayRangeDesignator() && "New kind of designator?")(static_cast <bool> (D.isArrayRangeDesignator() &&
"New kind of designator?") ? void (0) : __assert_fail ("D.isArrayRangeDesignator() && \"New kind of designator?\""
, "clang/lib/Sema/TreeTransform.h", 11696, __extension__ __PRETTY_FUNCTION__
))
;
11697 ExprResult Start
11698 = getDerived().TransformExpr(E->getArrayRangeStart(D));
11699 if (Start.isInvalid())
11700 return ExprError();
11701
11702 ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
11703 if (End.isInvalid())
11704 return ExprError();
11705
11706 Desig.AddDesignator(Designator::CreateArrayRangeDesignator(
11707 Start.get(), End.get(), D.getLBracketLoc(), D.getEllipsisLoc()));
11708
11709 ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
11710 End.get() != E->getArrayRangeEnd(D);
11711
11712 ArrayExprs.push_back(Start.get());
11713 ArrayExprs.push_back(End.get());
11714 }
11715
11716 if (!getDerived().AlwaysRebuild() &&
11717 Init.get() == E->getInit() &&
11718 !ExprChanged)
11719 return E;
11720
11721 return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
11722 E->getEqualOrColonLoc(),
11723 E->usesGNUSyntax(), Init.get());
11724}
11725
11726// Seems that if TransformInitListExpr() only works on the syntactic form of an
11727// InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
11728template<typename Derived>
11729ExprResult
11730TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
11731 DesignatedInitUpdateExpr *E) {
11732 llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "::llvm::llvm_unreachable_internal("Unexpected DesignatedInitUpdateExpr in syntactic form of "
"initializer", "clang/lib/Sema/TreeTransform.h", 11733)
11733 "initializer")::llvm::llvm_unreachable_internal("Unexpected DesignatedInitUpdateExpr in syntactic form of "
"initializer", "clang/lib/Sema/TreeTransform.h", 11733)
;
11734 return ExprError();
11735}
11736
11737template<typename Derived>
11738ExprResult
11739TreeTransform<Derived>::TransformNoInitExpr(
11740 NoInitExpr *E) {
11741 llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer")::llvm::llvm_unreachable_internal("Unexpected NoInitExpr in syntactic form of initializer"
, "clang/lib/Sema/TreeTransform.h", 11741)
;
11742 return ExprError();
11743}
11744
11745template<typename Derived>
11746ExprResult
11747TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
11748 llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer")::llvm::llvm_unreachable_internal("Unexpected ArrayInitLoopExpr outside of initializer"
, "clang/lib/Sema/TreeTransform.h", 11748)
;
11749 return ExprError();
11750}
11751
11752template<typename Derived>
11753ExprResult
11754TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
11755 llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer")::llvm::llvm_unreachable_internal("Unexpected ArrayInitIndexExpr outside of initializer"
, "clang/lib/Sema/TreeTransform.h", 11755)
;
11756 return ExprError();
11757}
11758
11759template<typename Derived>
11760ExprResult
11761TreeTransform<Derived>::TransformImplicitValueInitExpr(
11762 ImplicitValueInitExpr *E) {
11763 TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
11764
11765 // FIXME: Will we ever have proper type location here? Will we actually
11766 // need to transform the type?
11767 QualType T = getDerived().TransformType(E->getType());
11768 if (T.isNull())
11769 return ExprError();
11770
11771 if (!getDerived().AlwaysRebuild() &&
11772 T == E->getType())
11773 return E;
11774
11775 return getDerived().RebuildImplicitValueInitExpr(T);
11776}
11777
11778template<typename Derived>
11779ExprResult
11780TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
11781 TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
11782 if (!TInfo)
11783 return ExprError();
11784
11785 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11786 if (SubExpr.isInvalid())
11787 return ExprError();
11788
11789 if (!getDerived().AlwaysRebuild() &&
11790 TInfo == E->getWrittenTypeInfo() &&
11791 SubExpr.get() == E->getSubExpr())
11792 return E;
11793
11794 return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
11795 TInfo, E->getRParenLoc());
11796}
11797
11798template<typename Derived>
11799ExprResult
11800TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
11801 bool ArgumentChanged = false;
11802 SmallVector<Expr*, 4> Inits;
11803 if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
11804 &ArgumentChanged))
11805 return ExprError();
11806
11807 return getDerived().RebuildParenListExpr(E->getLParenLoc(),
11808 Inits,
11809 E->getRParenLoc());
11810}
11811
11812/// Transform an address-of-label expression.
11813///
11814/// By default, the transformation of an address-of-label expression always
11815/// rebuilds the expression, so that the label identifier can be resolved to
11816/// the corresponding label statement by semantic analysis.
11817template<typename Derived>
11818ExprResult
11819TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
11820 Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
11821 E->getLabel());
11822 if (!LD)
11823 return ExprError();
11824
11825 return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
11826 cast<LabelDecl>(LD));
11827}
11828
11829template<typename Derived>
11830ExprResult
11831TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
11832 SemaRef.ActOnStartStmtExpr();
11833 StmtResult SubStmt
11834 = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
11835 if (SubStmt.isInvalid()) {
11836 SemaRef.ActOnStmtExprError();
11837 return ExprError();
11838 }
11839
11840 unsigned OldDepth = E->getTemplateDepth();
11841 unsigned NewDepth = getDerived().TransformTemplateDepth(OldDepth);
11842
11843 if (!getDerived().AlwaysRebuild() && OldDepth == NewDepth &&
11844 SubStmt.get() == E->getSubStmt()) {
11845 // Calling this an 'error' is unintuitive, but it does the right thing.
11846 SemaRef.ActOnStmtExprError();
11847 return SemaRef.MaybeBindToTemporary(E);
11848 }
11849
11850 return getDerived().RebuildStmtExpr(E->getLParenLoc(), SubStmt.get(),
11851 E->getRParenLoc(), NewDepth);
11852}
11853
11854template<typename Derived>
11855ExprResult
11856TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
11857 ExprResult Cond = getDerived().TransformExpr(E->getCond());
11858 if (Cond.isInvalid())
11859 return ExprError();
11860
11861 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11862 if (LHS.isInvalid())
11863 return ExprError();
11864
11865 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11866 if (RHS.isInvalid())
11867 return ExprError();
11868
11869 if (!getDerived().AlwaysRebuild() &&
11870 Cond.get() == E->getCond() &&
11871 LHS.get() == E->getLHS() &&
11872 RHS.get() == E->getRHS())
11873 return E;
11874
11875 return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
11876 Cond.get(), LHS.get(), RHS.get(),
11877 E->getRParenLoc());
11878}
11879
11880template<typename Derived>
11881ExprResult
11882TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
11883 return E;
11884}
11885
11886template<typename Derived>
11887ExprResult
11888TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11889 switch (E->getOperator()) {
11890 case OO_New:
11891 case OO_Delete:
11892 case OO_Array_New:
11893 case OO_Array_Delete:
11894 llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr")::llvm::llvm_unreachable_internal("new and delete operators cannot use CXXOperatorCallExpr"
, "clang/lib/Sema/TreeTransform.h", 11894)
;
11895
11896 case OO_Subscript:
11897 case OO_Call: {
11898 // This is a call to an object's operator().
11899 assert(E->getNumArgs() >= 1 && "Object call is missing arguments")(static_cast <bool> (E->getNumArgs() >= 1 &&
"Object call is missing arguments") ? void (0) : __assert_fail
("E->getNumArgs() >= 1 && \"Object call is missing arguments\""
, "clang/lib/Sema/TreeTransform.h", 11899, __extension__ __PRETTY_FUNCTION__
))
;
11900
11901 // Transform the object itself.
11902 ExprResult Object = getDerived().TransformExpr(E->getArg(0));
11903 if (Object.isInvalid())
11904 return ExprError();
11905
11906 // FIXME: Poor location information
11907 SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
11908 static_cast<Expr *>(Object.get())->getEndLoc());
11909
11910 // Transform the call arguments.
11911 SmallVector<Expr*, 8> Args;
11912 if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
11913 Args))
11914 return ExprError();
11915
11916 if (E->getOperator() == OO_Subscript)
11917 return getDerived().RebuildCxxSubscriptExpr(Object.get(), FakeLParenLoc,
11918 Args, E->getEndLoc());
11919
11920 return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
11921 E->getEndLoc());
11922 }
11923
11924#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
11925 case OO_##Name: \
11926 break;
11927
11928#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
11929#include "clang/Basic/OperatorKinds.def"
11930
11931 case OO_Conditional:
11932 llvm_unreachable("conditional operator is not actually overloadable")::llvm::llvm_unreachable_internal("conditional operator is not actually overloadable"
, "clang/lib/Sema/TreeTransform.h", 11932)
;
11933
11934 case OO_None:
11935 case NUM_OVERLOADED_OPERATORS:
11936 llvm_unreachable("not an overloaded operator?")::llvm::llvm_unreachable_internal("not an overloaded operator?"
, "clang/lib/Sema/TreeTransform.h", 11936)
;
11937 }
11938
11939 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11940 if (Callee.isInvalid())
11941 return ExprError();
11942
11943 ExprResult First;
11944 if (E->getOperator() == OO_Amp)
11945 First = getDerived().TransformAddressOfOperand(E->getArg(0));
11946 else
11947 First = getDerived().TransformExpr(E->getArg(0));
11948 if (First.isInvalid())
11949 return ExprError();
11950
11951 ExprResult Second;
11952 if (E->getNumArgs() == 2) {
11953 Second = getDerived().TransformExpr(E->getArg(1));
11954 if (Second.isInvalid())
11955 return ExprError();
11956 }
11957
11958 if (!getDerived().AlwaysRebuild() &&
11959 Callee.get() == E->getCallee() &&
11960 First.get() == E->getArg(0) &&
11961 (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
11962 return SemaRef.MaybeBindToTemporary(E);
11963
11964 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11965 FPOptionsOverride NewOverrides(E->getFPFeatures());
11966 getSema().CurFPFeatures =
11967 NewOverrides.applyOverrides(getSema().getLangOpts());
11968 getSema().FpPragmaStack.CurrentValue = NewOverrides;
11969
11970 return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
11971 E->getOperatorLoc(),
11972 Callee.get(),
11973 First.get(),
11974 Second.get());
11975}
11976
11977template<typename Derived>
11978ExprResult
11979TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
11980 return getDerived().TransformCallExpr(E);
11981}
11982
11983template <typename Derived>
11984ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
11985 bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
11986 getSema().CurContext != E->getParentContext();
11987
11988 if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
11989 return E;
11990
11991 return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getType(),
11992 E->getBeginLoc(), E->getEndLoc(),
11993 getSema().CurContext);
11994}
11995
11996template<typename Derived>
11997ExprResult
11998TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
11999 // Transform the callee.
12000 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
12001 if (Callee.isInvalid())
12002 return ExprError();
12003
12004 // Transform exec config.
12005 ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
12006 if (EC.isInvalid())
12007 return ExprError();
12008
12009 // Transform arguments.
12010 bool ArgChanged = false;
12011 SmallVector<Expr*, 8> Args;
12012 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12013 &ArgChanged))
12014 return ExprError();
12015
12016 if (!getDerived().AlwaysRebuild() &&
12017 Callee.get() == E->getCallee() &&
12018 !ArgChanged)
12019 return SemaRef.MaybeBindToTemporary(E);
12020
12021 // FIXME: Wrong source location information for the '('.
12022 SourceLocation FakeLParenLoc
12023 = ((Expr *)Callee.get())->getSourceRange().getBegin();
12024 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
12025 Args,
12026 E->getRParenLoc(), EC.get());
12027}
12028
12029template<typename Derived>
12030ExprResult
12031TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
12032 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
12033 if (!Type)
12034 return ExprError();
12035
12036 ExprResult SubExpr
12037 = getDerived().TransformExpr(E->getSubExprAsWritten());
12038 if (SubExpr.isInvalid())
12039 return ExprError();
12040
12041 if (!getDerived().AlwaysRebuild() &&
12042 Type == E->getTypeInfoAsWritten() &&
12043 SubExpr.get() == E->getSubExpr())
12044 return E;
12045 return getDerived().RebuildCXXNamedCastExpr(
12046 E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
12047 Type, E->getAngleBrackets().getEnd(),
12048 // FIXME. this should be '(' location
12049 E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
12050}
12051
12052template<typename Derived>
12053ExprResult
12054TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
12055 TypeSourceInfo *TSI =
12056 getDerived().TransformType(BCE->getTypeInfoAsWritten());
12057 if (!TSI)
12058 return ExprError();
12059
12060 ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
12061 if (Sub.isInvalid())
12062 return ExprError();
12063
12064 return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
12065 Sub.get(), BCE->getEndLoc());
12066}
12067
12068template<typename Derived>
12069ExprResult
12070TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
12071 return getDerived().TransformCXXNamedCastExpr(E);
12072}
12073
12074template<typename Derived>
12075ExprResult
12076TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
12077 return getDerived().TransformCXXNamedCastExpr(E);
12078}
12079
12080template<typename Derived>
12081ExprResult
12082TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
12083 CXXReinterpretCastExpr *E) {
12084 return getDerived().TransformCXXNamedCastExpr(E);
12085}
12086
12087template<typename Derived>
12088ExprResult
12089TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
12090 return getDerived().TransformCXXNamedCastExpr(E);
12091}
12092
12093template<typename Derived>
12094ExprResult
12095TreeTransform<Derived>::TransformCXXAddrspaceCastExpr(CXXAddrspaceCastExpr *E) {
12096 return getDerived().TransformCXXNamedCastExpr(E);
12097}
12098
12099template<typename Derived>
12100ExprResult
12101TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
12102 CXXFunctionalCastExpr *E) {
12103 TypeSourceInfo *Type =
12104 getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
12105 if (!Type)
12106 return ExprError();
12107
12108 ExprResult SubExpr
12109 = getDerived().TransformExpr(E->getSubExprAsWritten());
12110 if (SubExpr.isInvalid())
12111 return ExprError();
12112
12113 if (!getDerived().AlwaysRebuild() &&
12114 Type == E->getTypeInfoAsWritten() &&
12115 SubExpr.get() == E->getSubExpr())
12116 return E;
12117
12118 return getDerived().RebuildCXXFunctionalCastExpr(Type,
12119 E->getLParenLoc(),
12120 SubExpr.get(),
12121 E->getRParenLoc(),
12122 E->isListInitialization());
12123}
12124
12125template<typename Derived>
12126ExprResult
12127TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
12128 if (E->isTypeOperand()) {
12129 TypeSourceInfo *TInfo
12130 = getDerived().TransformType(E->getTypeOperandSourceInfo());
12131 if (!TInfo)
12132 return ExprError();
12133
12134 if (!getDerived().AlwaysRebuild() &&
12135 TInfo == E->getTypeOperandSourceInfo())
12136 return E;
12137
12138 return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
12139 TInfo, E->getEndLoc());
12140 }
12141
12142 // Typeid's operand is an unevaluated context, unless it's a polymorphic
12143 // type. We must not unilaterally enter unevaluated context here, as then
12144 // semantic processing can re-transform an already transformed operand.
12145 Expr *Op = E->getExprOperand();
12146 auto EvalCtx = Sema::ExpressionEvaluationContext::Unevaluated;
12147 if (E->isGLValue())
12148 if (auto *RecordT = Op->getType()->getAs<RecordType>())
12149 if (cast<CXXRecordDecl>(RecordT->getDecl())->isPolymorphic())
12150 EvalCtx = SemaRef.ExprEvalContexts.back().Context;
12151
12152 EnterExpressionEvaluationContext Unevaluated(SemaRef, EvalCtx,
12153 Sema::ReuseLambdaContextDecl);
12154
12155 ExprResult SubExpr = getDerived().TransformExpr(Op);
12156 if (SubExpr.isInvalid())
12157 return ExprError();
12158
12159 if (!getDerived().AlwaysRebuild() &&
12160 SubExpr.get() == E->getExprOperand())
12161 return E;
12162
12163 return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
12164 SubExpr.get(), E->getEndLoc());
12165}
12166
12167template<typename Derived>
12168ExprResult
12169TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
12170 if (E->isTypeOperand()) {
12171 TypeSourceInfo *TInfo
12172 = getDerived().TransformType(E->getTypeOperandSourceInfo());
12173 if (!TInfo)
12174 return ExprError();
12175
12176 if (!getDerived().AlwaysRebuild() &&
12177 TInfo == E->getTypeOperandSourceInfo())
12178 return E;
12179
12180 return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
12181 TInfo, E->getEndLoc());
12182 }
12183
12184 EnterExpressionEvaluationContext Unevaluated(
12185 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12186
12187 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
12188 if (SubExpr.isInvalid())
12189 return ExprError();
12190
12191 if (!getDerived().AlwaysRebuild() &&
12192 SubExpr.get() == E->getExprOperand())
12193 return E;
12194
12195 return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
12196 SubExpr.get(), E->getEndLoc());
12197}
12198
12199template<typename Derived>
12200ExprResult
12201TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
12202 return E;
12203}
12204
12205template<typename Derived>
12206ExprResult
12207TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
12208 CXXNullPtrLiteralExpr *E) {
12209 return E;
12210}
12211
12212template<typename Derived>
12213ExprResult
12214TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
12215 QualType T = getSema().getCurrentThisType();
12216
12217 if (!getDerived().AlwaysRebuild() && T == E->getType()) {
12218 // Mark it referenced in the new context regardless.
12219 // FIXME: this is a bit instantiation-specific.
12220 getSema().MarkThisReferenced(E);
12221 return E;
12222 }
12223
12224 return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
12225}
12226
12227template<typename Derived>
12228ExprResult
12229TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
12230 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
12231 if (SubExpr.isInvalid())
12232 return ExprError();
12233
12234 if (!getDerived().AlwaysRebuild() &&
12235 SubExpr.get() == E->getSubExpr())
12236 return E;
12237
12238 return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
12239 E->isThrownVariableInScope());
12240}
12241
12242template<typename Derived>
12243ExprResult
12244TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12245 ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
12246 getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
12247 if (!Param)
12248 return ExprError();
12249
12250 ExprResult InitRes;
12251 if (E->hasRewrittenInit()) {
12252 InitRes = getDerived().TransformExpr(E->getRewrittenExpr());
12253 if (InitRes.isInvalid())
12254 return ExprError();
12255 }
12256
12257 if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
12258 E->getUsedContext() == SemaRef.CurContext &&
12259 InitRes.get() == E->getRewrittenExpr())
12260 return E;
12261
12262 return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param,
12263 InitRes.get());
12264}
12265
12266template<typename Derived>
12267ExprResult
12268TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
12269 FieldDecl *Field = cast_or_null<FieldDecl>(
12270 getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
12271 if (!Field)
12272 return ExprError();
12273
12274 if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
12275 E->getUsedContext() == SemaRef.CurContext)
12276 return E;
12277
12278 return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
12279}
12280
12281template<typename Derived>
12282ExprResult
12283TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
12284 CXXScalarValueInitExpr *E) {
12285 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
12286 if (!T)
12287 return ExprError();
12288
12289 if (!getDerived().AlwaysRebuild() &&
12290 T == E->getTypeSourceInfo())
12291 return E;
12292
12293 return getDerived().RebuildCXXScalarValueInitExpr(T,
12294 /*FIXME:*/T->getTypeLoc().getEndLoc(),
12295 E->getRParenLoc());
12296}
12297
12298template<typename Derived>
12299ExprResult
12300TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
12301 // Transform the type that we're allocating
12302 TypeSourceInfo *AllocTypeInfo =
12303 getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
12304 if (!AllocTypeInfo)
12305 return ExprError();
12306
12307 // Transform the size of the array we're allocating (if any).
12308 std::optional<Expr *> ArraySize;
12309 if (E->isArray()) {
12310 ExprResult NewArraySize;
12311 if (std::optional<Expr *> OldArraySize = E->getArraySize()) {
12312 NewArraySize = getDerived().TransformExpr(*OldArraySize);
12313 if (NewArraySize.isInvalid())
12314 return ExprError();
12315 }
12316 ArraySize = NewArraySize.get();
12317 }
12318
12319 // Transform the placement arguments (if any).
12320 bool ArgumentChanged = false;
12321 SmallVector<Expr*, 8> PlacementArgs;
12322 if (getDerived().TransformExprs(E->getPlacementArgs(),
12323 E->getNumPlacementArgs(), true,
12324 PlacementArgs, &ArgumentChanged))
12325 return ExprError();
12326
12327 // Transform the initializer (if any).
12328 Expr *OldInit = E->getInitializer();
12329 ExprResult NewInit;
12330 if (OldInit)
12331 NewInit = getDerived().TransformInitializer(OldInit, true);
12332 if (NewInit.isInvalid())
12333 return ExprError();
12334
12335 // Transform new operator and delete operator.
12336 FunctionDecl *OperatorNew = nullptr;
12337 if (E->getOperatorNew()) {
12338 OperatorNew = cast_or_null<FunctionDecl>(
12339 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
12340 if (!OperatorNew)
12341 return ExprError();
12342 }
12343
12344 FunctionDecl *OperatorDelete = nullptr;
12345 if (E->getOperatorDelete()) {
12346 OperatorDelete = cast_or_null<FunctionDecl>(
12347 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12348 if (!OperatorDelete)
12349 return ExprError();
12350 }
12351
12352 if (!getDerived().AlwaysRebuild() &&
12353 AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
12354 ArraySize == E->getArraySize() &&
12355 NewInit.get() == OldInit &&
12356 OperatorNew == E->getOperatorNew() &&
12357 OperatorDelete == E->getOperatorDelete() &&
12358 !ArgumentChanged) {
12359 // Mark any declarations we need as referenced.
12360 // FIXME: instantiation-specific.
12361 if (OperatorNew)
12362 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
12363 if (OperatorDelete)
12364 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12365
12366 if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
12367 QualType ElementType
12368 = SemaRef.Context.getBaseElementType(E->getAllocatedType());
12369 if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
12370 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
12371 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
12372 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
12373 }
12374 }
12375 }
12376
12377 return E;
12378 }
12379
12380 QualType AllocType = AllocTypeInfo->getType();
12381 if (!ArraySize) {
12382 // If no array size was specified, but the new expression was
12383 // instantiated with an array type (e.g., "new T" where T is
12384 // instantiated with "int[4]"), extract the outer bound from the
12385 // array type as our array size. We do this with constant and
12386 // dependently-sized array types.
12387 const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
12388 if (!ArrayT) {
12389 // Do nothing
12390 } else if (const ConstantArrayType *ConsArrayT
12391 = dyn_cast<ConstantArrayType>(ArrayT)) {
12392 ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
12393 SemaRef.Context.getSizeType(),
12394 /*FIXME:*/ E->getBeginLoc());
12395 AllocType = ConsArrayT->getElementType();
12396 } else if (const DependentSizedArrayType *DepArrayT
12397 = dyn_cast<DependentSizedArrayType>(ArrayT)) {
12398 if (DepArrayT->getSizeExpr()) {
12399 ArraySize = DepArrayT->getSizeExpr();
12400 AllocType = DepArrayT->getElementType();
12401 }
12402 }
12403 }
12404
12405 return getDerived().RebuildCXXNewExpr(
12406 E->getBeginLoc(), E->isGlobalNew(),
12407 /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
12408 /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
12409 AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
12410}
12411
12412template<typename Derived>
12413ExprResult
12414TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
12415 ExprResult Operand = getDerived().TransformExpr(E->getArgument());
12416 if (Operand.isInvalid())
12417 return ExprError();
12418
12419 // Transform the delete operator, if known.
12420 FunctionDecl *OperatorDelete = nullptr;
12421 if (E->getOperatorDelete()) {
12422 OperatorDelete = cast_or_null<FunctionDecl>(
12423 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12424 if (!OperatorDelete)
12425 return ExprError();
12426 }
12427
12428 if (!getDerived().AlwaysRebuild() &&
12429 Operand.get() == E->getArgument() &&
12430 OperatorDelete == E->getOperatorDelete()) {
12431 // Mark any declarations we need as referenced.
12432 // FIXME: instantiation-specific.
12433 if (OperatorDelete)
12434 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12435
12436 if (!E->getArgument()->isTypeDependent()) {
12437 QualType Destroyed = SemaRef.Context.getBaseElementType(
12438 E->getDestroyedType());
12439 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12440 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12441 SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
12442 SemaRef.LookupDestructor(Record));
12443 }
12444 }
12445
12446 return E;
12447 }
12448
12449 return getDerived().RebuildCXXDeleteExpr(
12450 E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
12451}
12452
12453template<typename Derived>
12454ExprResult
12455TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
12456 CXXPseudoDestructorExpr *E) {
12457 ExprResult Base = getDerived().TransformExpr(E->getBase());
12458 if (Base.isInvalid())
12459 return ExprError();
12460
12461 ParsedType ObjectTypePtr;
12462 bool MayBePseudoDestructor = false;
12463 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
12464 E->getOperatorLoc(),
12465 E->isArrow()? tok::arrow : tok::period,
12466 ObjectTypePtr,
12467 MayBePseudoDestructor);
12468 if (Base.isInvalid())
12469 return ExprError();
12470
12471 QualType ObjectType = ObjectTypePtr.get();
12472 NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
12473 if (QualifierLoc) {
12474 QualifierLoc
12475 = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
12476 if (!QualifierLoc)
12477 return ExprError();
12478 }
12479 CXXScopeSpec SS;
12480 SS.Adopt(QualifierLoc);
12481
12482 PseudoDestructorTypeStorage Destroyed;
12483 if (E->getDestroyedTypeInfo()) {
12484 TypeSourceInfo *DestroyedTypeInfo
12485 = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
12486 ObjectType, nullptr, SS);
12487 if (!DestroyedTypeInfo)
12488 return ExprError();
12489 Destroyed = DestroyedTypeInfo;
12490 } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
12491 // We aren't likely to be able to resolve the identifier down to a type
12492 // now anyway, so just retain the identifier.
12493 Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
12494 E->getDestroyedTypeLoc());
12495 } else {
12496 // Look for a destructor known with the given name.
12497 ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
12498 *E->getDestroyedTypeIdentifier(),
12499 E->getDestroyedTypeLoc(),
12500 /*Scope=*/nullptr,
12501 SS, ObjectTypePtr,
12502 false);
12503 if (!T)
12504 return ExprError();
12505
12506 Destroyed
12507 = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
12508 E->getDestroyedTypeLoc());
12509 }
12510
12511 TypeSourceInfo *ScopeTypeInfo = nullptr;
12512 if (E->getScopeTypeInfo()) {
12513 CXXScopeSpec EmptySS;
12514 ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
12515 E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
12516 if (!ScopeTypeInfo)
12517 return ExprError();
12518 }
12519
12520 return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
12521 E->getOperatorLoc(),
12522 E->isArrow(),
12523 SS,
12524 ScopeTypeInfo,
12525 E->getColonColonLoc(),
12526 E->getTildeLoc(),
12527 Destroyed);
12528}
12529
12530template <typename Derived>
12531bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
12532 bool RequiresADL,
12533 LookupResult &R) {
12534 // Transform all the decls.
12535 bool AllEmptyPacks = true;
12536 for (auto *OldD : Old->decls()) {
12537 Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
12538 if (!InstD) {
12539 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
12540 // This can happen because of dependent hiding.
12541 if (isa<UsingShadowDecl>(OldD))
12542 continue;
12543 else {
12544 R.clear();
12545 return true;
12546 }
12547 }
12548
12549 // Expand using pack declarations.
12550 NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
12551 ArrayRef<NamedDecl*> Decls = SingleDecl;
12552 if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
12553 Decls = UPD->expansions();
12554
12555 // Expand using declarations.
12556 for (auto *D : Decls) {
12557 if (auto *UD = dyn_cast<UsingDecl>(D)) {
12558 for (auto *SD : UD->shadows())
12559 R.addDecl(SD);
12560 } else {
12561 R.addDecl(D);
12562 }
12563 }
12564
12565 AllEmptyPacks &= Decls.empty();
12566 };
12567
12568 // C++ [temp.res]/8.4.2:
12569 // The program is ill-formed, no diagnostic required, if [...] lookup for
12570 // a name in the template definition found a using-declaration, but the
12571 // lookup in the corresponding scope in the instantiation odoes not find
12572 // any declarations because the using-declaration was a pack expansion and
12573 // the corresponding pack is empty
12574 if (AllEmptyPacks && !RequiresADL) {
12575 getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
12576 << isa<UnresolvedMemberExpr>(Old) << Old->getName();
12577 return true;
12578 }
12579
12580 // Resolve a kind, but don't do any further analysis. If it's
12581 // ambiguous, the callee needs to deal with it.
12582 R.resolveKind();
12583 return false;
12584}
12585
12586template<typename Derived>
12587ExprResult
12588TreeTransform<Derived>::TransformUnresolvedLookupExpr(
12589 UnresolvedLookupExpr *Old) {
12590 LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
12591 Sema::LookupOrdinaryName);
12592
12593 // Transform the declaration set.
12594 if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
12595 return ExprError();
12596
12597 // Rebuild the nested-name qualifier, if present.
12598 CXXScopeSpec SS;
12599 if (Old->getQualifierLoc()) {
12600 NestedNameSpecifierLoc QualifierLoc
12601 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
12602 if (!QualifierLoc)
12603 return ExprError();
12604
12605 SS.Adopt(QualifierLoc);
12606 }
12607
12608 if (Old->getNamingClass()) {
12609 CXXRecordDecl *NamingClass
12610 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
12611 Old->getNameLoc(),
12612 Old->getNamingClass()));
12613 if (!NamingClass) {
12614 R.clear();
12615 return ExprError();
12616 }
12617
12618 R.setNamingClass(NamingClass);
12619 }
12620
12621 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
12622
12623 // If we have neither explicit template arguments, nor the template keyword,
12624 // it's a normal declaration name or member reference.
12625 if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
12626 NamedDecl *D = R.getAsSingle<NamedDecl>();
12627 // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
12628 // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
12629 // give a good diagnostic.
12630 if (D && D->isCXXInstanceMember()) {
12631 return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12632 /*TemplateArgs=*/nullptr,
12633 /*Scope=*/nullptr);
12634 }
12635
12636 return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
12637 }
12638
12639 // If we have template arguments, rebuild them, then rebuild the
12640 // templateid expression.
12641 TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
12642 if (Old->hasExplicitTemplateArgs() &&
12643 getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12644 Old->getNumTemplateArgs(),
12645 TransArgs)) {
12646 R.clear();
12647 return ExprError();
12648 }
12649
12650 return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
12651 Old->requiresADL(), &TransArgs);
12652}
12653
12654template<typename Derived>
12655ExprResult
12656TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
12657 bool ArgChanged = false;
12658 SmallVector<TypeSourceInfo *, 4> Args;
12659 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
12660 TypeSourceInfo *From = E->getArg(I);
12661 TypeLoc FromTL = From->getTypeLoc();
12662 if (!FromTL.getAs<PackExpansionTypeLoc>()) {
12663 TypeLocBuilder TLB;
12664 TLB.reserve(FromTL.getFullDataSize());
12665 QualType To = getDerived().TransformType(TLB, FromTL);
12666 if (To.isNull())
12667 return ExprError();
12668
12669 if (To == From->getType())
12670 Args.push_back(From);
12671 else {
12672 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12673 ArgChanged = true;
12674 }
12675 continue;
12676 }
12677
12678 ArgChanged = true;
12679
12680 // We have a pack expansion. Instantiate it.
12681 PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
12682 TypeLoc PatternTL = ExpansionTL.getPatternLoc();
12683 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12684 SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
12685
12686 // Determine whether the set of unexpanded parameter packs can and should
12687 // be expanded.
12688 bool Expand = true;
12689 bool RetainExpansion = false;
12690 std::optional<unsigned> OrigNumExpansions =
12691 ExpansionTL.getTypePtr()->getNumExpansions();
12692 std::optional<unsigned> NumExpansions = OrigNumExpansions;
12693 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
12694 PatternTL.getSourceRange(),
12695 Unexpanded,
12696 Expand, RetainExpansion,
12697 NumExpansions))
12698 return ExprError();
12699
12700 if (!Expand) {
12701 // The transform has determined that we should perform a simple
12702 // transformation on the pack expansion, producing another pack
12703 // expansion.
12704 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12705
12706 TypeLocBuilder TLB;
12707 TLB.reserve(From->getTypeLoc().getFullDataSize());
12708
12709 QualType To = getDerived().TransformType(TLB, PatternTL);
12710 if (To.isNull())
12711 return ExprError();
12712
12713 To = getDerived().RebuildPackExpansionType(To,
12714 PatternTL.getSourceRange(),
12715 ExpansionTL.getEllipsisLoc(),
12716 NumExpansions);
12717 if (To.isNull())
12718 return ExprError();
12719
12720 PackExpansionTypeLoc ToExpansionTL
12721 = TLB.push<PackExpansionTypeLoc>(To);
12722 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12723 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12724 continue;
12725 }
12726
12727 // Expand the pack expansion by substituting for each argument in the
12728 // pack(s).
12729 for (unsigned I = 0; I != *NumExpansions; ++I) {
12730 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
12731 TypeLocBuilder TLB;
12732 TLB.reserve(PatternTL.getFullDataSize());
12733 QualType To = getDerived().TransformType(TLB, PatternTL);
12734 if (To.isNull())
12735 return ExprError();
12736
12737 if (To->containsUnexpandedParameterPack()) {
12738 To = getDerived().RebuildPackExpansionType(To,
12739 PatternTL.getSourceRange(),
12740 ExpansionTL.getEllipsisLoc(),
12741 NumExpansions);
12742 if (To.isNull())
12743 return ExprError();
12744
12745 PackExpansionTypeLoc ToExpansionTL
12746 = TLB.push<PackExpansionTypeLoc>(To);
12747 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12748 }
12749
12750 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12751 }
12752
12753 if (!RetainExpansion)
12754 continue;
12755
12756 // If we're supposed to retain a pack expansion, do so by temporarily
12757 // forgetting the partially-substituted parameter pack.
12758 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12759
12760 TypeLocBuilder TLB;
12761 TLB.reserve(From->getTypeLoc().getFullDataSize());
12762
12763 QualType To = getDerived().TransformType(TLB, PatternTL);
12764 if (To.isNull())
12765 return ExprError();
12766
12767 To = getDerived().RebuildPackExpansionType(To,
12768 PatternTL.getSourceRange(),
12769 ExpansionTL.getEllipsisLoc(),
12770 NumExpansions);
12771 if (To.isNull())
12772 return ExprError();
12773
12774 PackExpansionTypeLoc ToExpansionTL
12775 = TLB.push<PackExpansionTypeLoc>(To);
12776 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12777 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12778 }
12779
12780 if (!getDerived().AlwaysRebuild() && !ArgChanged)
12781 return E;
12782
12783 return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
12784 E->getEndLoc());
12785}
12786
12787template<typename Derived>
12788ExprResult
12789TreeTransform<Derived>::TransformConceptSpecializationExpr(
12790 ConceptSpecializationExpr *E) {
12791 const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
12792 TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
12793 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12794 Old->NumTemplateArgs, TransArgs))
12795 return ExprError();
12796
12797 return getDerived().RebuildConceptSpecializationExpr(
12798 E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
12799 E->getConceptNameInfo(), E->getFoundDecl(), E->getNamedConcept(),
12800 &TransArgs);
12801}
12802
12803template<typename Derived>
12804ExprResult
12805TreeTransform<Derived>::TransformRequiresExpr(RequiresExpr *E) {
12806 SmallVector<ParmVarDecl*, 4> TransParams;
12807 SmallVector<QualType, 4> TransParamTypes;
12808 Sema::ExtParameterInfoBuilder ExtParamInfos;
12809
12810 // C++2a [expr.prim.req]p2
12811 // Expressions appearing within a requirement-body are unevaluated operands.
12812 EnterExpressionEvaluationContext Ctx(
12813 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
12814 Sema::ReuseLambdaContextDecl);
12815
12816 RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(
12817 getSema().Context, getSema().CurContext,
12818 E->getBody()->getBeginLoc());
12819
12820 Sema::ContextRAII SavedContext(getSema(), Body, /*NewThisContext*/false);
12821
12822 ExprResult TypeParamResult = getDerived().TransformRequiresTypeParams(
12823 E->getRequiresKWLoc(), E->getRBraceLoc(), E, Body,
12824 E->getLocalParameters(), TransParamTypes, TransParams, ExtParamInfos);
12825
12826 for (ParmVarDecl *Param : TransParams)
12827 if (Param)
12828 Param->setDeclContext(Body);
12829
12830 // On failure to transform, TransformRequiresTypeParams returns an expression
12831 // in the event that the transformation of the type params failed in some way.
12832 // It is expected that this will result in a 'not satisfied' Requires clause
12833 // when instantiating.
12834 if (!TypeParamResult.isUnset())
12835 return TypeParamResult;
12836
12837 SmallVector<concepts::Requirement *, 4> TransReqs;
12838 if (getDerived().TransformRequiresExprRequirements(E->getRequirements(),
12839 TransReqs))
12840 return ExprError();
12841
12842 for (concepts::Requirement *Req : TransReqs) {
12843 if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
12844 if (ER->getReturnTypeRequirement().isTypeConstraint()) {
12845 ER->getReturnTypeRequirement()
12846 .getTypeConstraintTemplateParameterList()->getParam(0)
12847 ->setDeclContext(Body);
12848 }
12849 }
12850 }
12851
12852 return getDerived().RebuildRequiresExpr(E->getRequiresKWLoc(), Body,
12853 TransParams, TransReqs,
12854 E->getRBraceLoc());
12855}
12856
12857template<typename Derived>
12858bool TreeTransform<Derived>::TransformRequiresExprRequirements(
12859 ArrayRef<concepts::Requirement *> Reqs,
12860 SmallVectorImpl<concepts::Requirement *> &Transformed) {
12861 for (concepts::Requirement *Req : Reqs) {
12862 concepts::Requirement *TransReq = nullptr;
12863 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
12864 TransReq = getDerived().TransformTypeRequirement(TypeReq);
12865 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
12866 TransReq = getDerived().TransformExprRequirement(ExprReq);
12867 else
12868 TransReq = getDerived().TransformNestedRequirement(
12869 cast<concepts::NestedRequirement>(Req));
12870 if (!TransReq)
12871 return true;
12872 Transformed.push_back(TransReq);
12873 }
12874 return false;
12875}
12876
12877template<typename Derived>
12878concepts::TypeRequirement *
12879TreeTransform<Derived>::TransformTypeRequirement(
12880 concepts::TypeRequirement *Req) {
12881 if (Req->isSubstitutionFailure()) {
12882 if (getDerived().AlwaysRebuild())
12883 return getDerived().RebuildTypeRequirement(
12884 Req->getSubstitutionDiagnostic());
12885 return Req;
12886 }
12887 TypeSourceInfo *TransType = getDerived().TransformType(Req->getType());
12888 if (!TransType)
12889 return nullptr;
12890 return getDerived().RebuildTypeRequirement(TransType);
12891}
12892
12893template<typename Derived>
12894concepts::ExprRequirement *
12895TreeTransform<Derived>::TransformExprRequirement(concepts::ExprRequirement *Req) {
12896 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> TransExpr;
12897 if (Req->isExprSubstitutionFailure())
12898 TransExpr = Req->getExprSubstitutionDiagnostic();
12899 else {
12900 ExprResult TransExprRes = getDerived().TransformExpr(Req->getExpr());
12901 if (TransExprRes.isUsable() && TransExprRes.get()->hasPlaceholderType())
12902 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
12903 if (TransExprRes.isInvalid())
12904 return nullptr;
12905 TransExpr = TransExprRes.get();
12906 }
12907
12908 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
12909 const auto &RetReq = Req->getReturnTypeRequirement();
12910 if (RetReq.isEmpty())
12911 TransRetReq.emplace();
12912 else if (RetReq.isSubstitutionFailure())
12913 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
12914 else if (RetReq.isTypeConstraint()) {
12915 TemplateParameterList *OrigTPL =
12916 RetReq.getTypeConstraintTemplateParameterList();
12917 TemplateParameterList *TPL =
12918 getDerived().TransformTemplateParameterList(OrigTPL);
12919 if (!TPL)
12920 return nullptr;
12921 TransRetReq.emplace(TPL);
12922 }
12923 assert(TransRetReq && "All code paths leading here must set TransRetReq")(static_cast <bool> (TransRetReq && "All code paths leading here must set TransRetReq"
) ? void (0) : __assert_fail ("TransRetReq && \"All code paths leading here must set TransRetReq\""
, "clang/lib/Sema/TreeTransform.h", 12923, __extension__ __PRETTY_FUNCTION__
))
;
12924 if (Expr *E = TransExpr.dyn_cast<Expr *>())
12925 return getDerived().RebuildExprRequirement(E, Req->isSimple(),
12926 Req->getNoexceptLoc(),
12927 std::move(*TransRetReq));
12928 return getDerived().RebuildExprRequirement(
12929 TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
12930 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
12931}
12932
12933template<typename Derived>
12934concepts::NestedRequirement *
12935TreeTransform<Derived>::TransformNestedRequirement(
12936 concepts::NestedRequirement *Req) {
12937 if (Req->hasInvalidConstraint()) {
12938 if (getDerived().AlwaysRebuild())
12939 return getDerived().RebuildNestedRequirement(
12940 Req->getInvalidConstraintEntity(), Req->getConstraintSatisfaction());
12941 return Req;
12942 }
12943 ExprResult TransConstraint =
12944 getDerived().TransformExpr(Req->getConstraintExpr());
12945 if (TransConstraint.isInvalid())
12946 return nullptr;
12947 return getDerived().RebuildNestedRequirement(TransConstraint.get());
12948}
12949
12950template<typename Derived>
12951ExprResult
12952TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
12953 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
12954 if (!T)
12955 return ExprError();
12956
12957 if (!getDerived().AlwaysRebuild() &&
12958 T == E->getQueriedTypeSourceInfo())
12959 return E;
12960
12961 ExprResult SubExpr;
12962 {
12963 EnterExpressionEvaluationContext Unevaluated(
12964 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12965 SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
12966 if (SubExpr.isInvalid())
12967 return ExprError();
12968
12969 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
12970 return E;
12971 }
12972
12973 return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
12974 SubExpr.get(), E->getEndLoc());
12975}
12976
12977template<typename Derived>
12978ExprResult
12979TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
12980 ExprResult SubExpr;
12981 {
12982 EnterExpressionEvaluationContext Unevaluated(
12983 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12984 SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
12985 if (SubExpr.isInvalid())
12986 return ExprError();
12987
12988 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
12989 return E;
12990 }
12991
12992 return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
12993 SubExpr.get(), E->getEndLoc());
12994}
12995
12996template <typename Derived>
12997ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
12998 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
12999 TypeSourceInfo **RecoveryTSI) {
13000 ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
13001 DRE, AddrTaken, RecoveryTSI);
13002
13003 // Propagate both errors and recovered types, which return ExprEmpty.
13004 if (!NewDRE.isUsable())
13005 return NewDRE;
13006
13007 // We got an expr, wrap it up in parens.
13008 if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
13009 return PE;
13010 return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
13011 PE->getRParen());
13012}
13013
13014template <typename Derived>
13015ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
13016 DependentScopeDeclRefExpr *E) {
13017 return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
13018 nullptr);
13019}
13020
13021template <typename Derived>
13022ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
13023 DependentScopeDeclRefExpr *E, bool IsAddressOfOperand,
13024 TypeSourceInfo **RecoveryTSI) {
13025 assert(E->getQualifierLoc())(static_cast <bool> (E->getQualifierLoc()) ? void (0
) : __assert_fail ("E->getQualifierLoc()", "clang/lib/Sema/TreeTransform.h"
, 13025, __extension__ __PRETTY_FUNCTION__))
;
13026 NestedNameSpecifierLoc QualifierLoc =
13027 getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
13028 if (!QualifierLoc)
13029 return ExprError();
13030 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13031
13032 // TODO: If this is a conversion-function-id, verify that the
13033 // destination type name (if present) resolves the same way after
13034 // instantiation as it did in the local scope.
13035
13036 DeclarationNameInfo NameInfo =
13037 getDerived().TransformDeclarationNameInfo(E->getNameInfo());
13038 if (!NameInfo.getName())
13039 return ExprError();
13040
13041 if (!E->hasExplicitTemplateArgs()) {
13042 if (!getDerived().AlwaysRebuild() && QualifierLoc == E->getQualifierLoc() &&
13043 // Note: it is sufficient to compare the Name component of NameInfo:
13044 // if name has not changed, DNLoc has not changed either.
13045 NameInfo.getName() == E->getDeclName())
13046 return E;
13047
13048 return getDerived().RebuildDependentScopeDeclRefExpr(
13049 QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
13050 IsAddressOfOperand, RecoveryTSI);
13051 }
13052
13053 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13054 if (getDerived().TransformTemplateArguments(
13055 E->getTemplateArgs(), E->getNumTemplateArgs(), TransArgs))
13056 return ExprError();
13057
13058 return getDerived().RebuildDependentScopeDeclRefExpr(
13059 QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
13060 RecoveryTSI);
13061}
13062
13063template<typename Derived>
13064ExprResult
13065TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
13066 // CXXConstructExprs other than for list-initialization and
13067 // CXXTemporaryObjectExpr are always implicit, so when we have
13068 // a 1-argument construction we just transform that argument.
13069 if (getDerived().AllowSkippingCXXConstructExpr() &&
13070 ((E->getNumArgs() == 1 ||
13071 (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
13072 (!getDerived().DropCallArgument(E->getArg(0))) &&
13073 !E->isListInitialization()))
13074 return getDerived().TransformInitializer(E->getArg(0),
13075 /*DirectInit*/ false);
13076
13077 TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
13078
13079 QualType T = getDerived().TransformType(E->getType());
13080 if (T.isNull())
13081 return ExprError();
13082
13083 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13084 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13085 if (!Constructor)
13086 return ExprError();
13087
13088 bool ArgumentChanged = false;
13089 SmallVector<Expr*, 8> Args;
13090 {
13091 EnterExpressionEvaluationContext Context(
13092 getSema(), EnterExpressionEvaluationContext::InitList,
13093 E->isListInitialization());
13094 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
13095 &ArgumentChanged))
13096 return ExprError();
13097 }
13098
13099 if (!getDerived().AlwaysRebuild() &&
13100 T == E->getType() &&
13101 Constructor == E->getConstructor() &&
13102 !ArgumentChanged) {
13103 // Mark the constructor as referenced.
13104 // FIXME: Instantiation-specific
13105 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13106 return E;
13107 }
13108
13109 return getDerived().RebuildCXXConstructExpr(
13110 T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
13111 E->hadMultipleCandidates(), E->isListInitialization(),
13112 E->isStdInitListInitialization(), E->requiresZeroInitialization(),
13113 E->getConstructionKind(), E->getParenOrBraceRange());
13114}
13115
13116template<typename Derived>
13117ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
13118 CXXInheritedCtorInitExpr *E) {
13119 QualType T = getDerived().TransformType(E->getType());
13120 if (T.isNull())
13121 return ExprError();
13122
13123 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13124 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13125 if (!Constructor)
13126 return ExprError();
13127
13128 if (!getDerived().AlwaysRebuild() &&
13129 T == E->getType() &&
13130 Constructor == E->getConstructor()) {
13131 // Mark the constructor as referenced.
13132 // FIXME: Instantiation-specific
13133 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13134 return E;
13135 }
13136
13137 return getDerived().RebuildCXXInheritedCtorInitExpr(
13138 T, E->getLocation(), Constructor,
13139 E->constructsVBase(), E->inheritedFromVBase());
13140}
13141
13142/// Transform a C++ temporary-binding expression.
13143///
13144/// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
13145/// transform the subexpression and return that.
13146template<typename Derived>
13147ExprResult
13148TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
13149 if (auto *Dtor = E->getTemporary()->getDestructor())
13150 SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
13151 const_cast<CXXDestructorDecl *>(Dtor));
13152 return getDerived().TransformExpr(E->getSubExpr());
13153}
13154
13155/// Transform a C++ expression that contains cleanups that should
13156/// be run after the expression is evaluated.
13157///
13158/// Since ExprWithCleanups nodes are implicitly generated, we
13159/// just transform the subexpression and return that.
13160template<typename Derived>
13161ExprResult
13162TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
13163 return getDerived().TransformExpr(E->getSubExpr());
13164}
13165
13166template<typename Derived>
13167ExprResult
13168TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
13169 CXXTemporaryObjectExpr *E) {
13170 TypeSourceInfo *T =
13171 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13172 if (!T)
13173 return ExprError();
13174
13175 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13176 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13177 if (!Constructor)
13178 return ExprError();
13179
13180 bool ArgumentChanged = false;
13181 SmallVector<Expr*, 8> Args;
13182 Args.reserve(E->getNumArgs());
13183 {
13184 EnterExpressionEvaluationContext Context(
13185 getSema(), EnterExpressionEvaluationContext::InitList,
13186 E->isListInitialization());
13187 if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
13188 &ArgumentChanged))
13189 return ExprError();
13190 }
13191
13192 if (!getDerived().AlwaysRebuild() &&
13193 T == E->getTypeSourceInfo() &&
13194 Constructor == E->getConstructor() &&
13195 !ArgumentChanged) {
13196 // FIXME: Instantiation-specific
13197 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13198 return SemaRef.MaybeBindToTemporary(E);
13199 }
13200
13201 // FIXME: We should just pass E->isListInitialization(), but we're not
13202 // prepared to handle list-initialization without a child InitListExpr.
13203 SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
13204 return getDerived().RebuildCXXTemporaryObjectExpr(
13205 T, LParenLoc, Args, E->getEndLoc(),
13206 /*ListInitialization=*/LParenLoc.isInvalid());
13207}
13208
13209template<typename Derived>
13210ExprResult
13211TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
13212 // Transform any init-capture expressions before entering the scope of the
13213 // lambda body, because they are not semantically within that scope.
13214 typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
13215 struct TransformedInitCapture {
13216 // The location of the ... if the result is retaining a pack expansion.
13217 SourceLocation EllipsisLoc;
13218 // Zero or more expansions of the init-capture.
13219 SmallVector<InitCaptureInfoTy, 4> Expansions;
13220 };
13221 SmallVector<TransformedInitCapture, 4> InitCaptures;
13222 InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
13223 for (LambdaExpr::capture_iterator C = E->capture_begin(),
3
Loop condition is false. Execution continues on line 13290
13224 CEnd = E->capture_end();
13225 C != CEnd; ++C) {
2
Assuming 'C' is equal to 'CEnd'
13226 if (!E->isInitCapture(C))
13227 continue;
13228
13229 TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
13230 auto *OldVD = cast<VarDecl>(C->getCapturedVar());
13231
13232 auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
13233 std::optional<unsigned> NumExpansions) {
13234 ExprResult NewExprInitResult = getDerived().TransformInitializer(
13235 OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
13236
13237 if (NewExprInitResult.isInvalid()) {
13238 Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
13239 return;
13240 }
13241 Expr *NewExprInit = NewExprInitResult.get();
13242
13243 QualType NewInitCaptureType =
13244 getSema().buildLambdaInitCaptureInitialization(
13245 C->getLocation(), C->getCaptureKind() == LCK_ByRef,
13246 EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
13247 cast<VarDecl>(C->getCapturedVar())->getInitStyle() !=
13248 VarDecl::CInit,
13249 NewExprInit);
13250 Result.Expansions.push_back(
13251 InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
13252 };
13253
13254 // If this is an init-capture pack, consider expanding the pack now.
13255 if (OldVD->isParameterPack()) {
13256 PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
13257 ->getTypeLoc()
13258 .castAs<PackExpansionTypeLoc>();
13259 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13260 SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
13261
13262 // Determine whether the set of unexpanded parameter packs can and should
13263 // be expanded.
13264 bool Expand = true;
13265 bool RetainExpansion = false;
13266 std::optional<unsigned> OrigNumExpansions =
13267 ExpansionTL.getTypePtr()->getNumExpansions();
13268 std::optional<unsigned> NumExpansions = OrigNumExpansions;
13269 if (getDerived().TryExpandParameterPacks(
13270 ExpansionTL.getEllipsisLoc(),
13271 OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
13272 RetainExpansion, NumExpansions))
13273 return ExprError();
13274 if (Expand) {
13275 for (unsigned I = 0; I != *NumExpansions; ++I) {
13276 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13277 SubstInitCapture(SourceLocation(), std::nullopt);
13278 }
13279 }
13280 if (!Expand || RetainExpansion) {
13281 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13282 SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
13283 Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
13284 }
13285 } else {
13286 SubstInitCapture(SourceLocation(), std::nullopt);
13287 }
13288 }
13289
13290 LambdaScopeInfo *LSI = getSema().PushLambdaScope();
13291 Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
13292
13293 // Create the local class that will describe the lambda.
13294
13295 // FIXME: DependencyKind below is wrong when substituting inside a templated
13296 // context that isn't a DeclContext (such as a variable template), or when
13297 // substituting an unevaluated lambda inside of a function's parameter's type
13298 // - as parameter types are not instantiated from within a function's DC. We
13299 // use evaluation contexts to distinguish the function parameter case.
13300 CXXRecordDecl::LambdaDependencyKind DependencyKind =
13301 CXXRecordDecl::LDK_Unknown;
13302 if ((getSema().isUnevaluatedContext() ||
13303 getSema().isConstantEvaluatedContext()) &&
13304 (getSema().CurContext->isFileContext() ||
13305 !getSema().CurContext->getParent()->isDependentContext()))
13306 DependencyKind = CXXRecordDecl::LDK_NeverDependent;
13307
13308 CXXRecordDecl *OldClass = E->getLambdaClass();
13309 CXXRecordDecl *Class = getSema().createLambdaClosureType(
13310 E->getIntroducerRange(), /*Info=*/nullptr, DependencyKind,
13311 E->getCaptureDefault());
13312 getDerived().transformedLocalDecl(OldClass, {Class});
13313
13314 CXXMethodDecl *NewCallOperator =
13315 getSema().CreateLambdaCallOperator(E->getIntroducerRange(), Class);
13316 NewCallOperator->setLexicalDeclContext(getSema().CurContext);
13317
13318 // Enter the scope of the lambda.
13319 getSema().buildLambdaScope(LSI, NewCallOperator, E->getIntroducerRange(),
13320 E->getCaptureDefault(), E->getCaptureDefaultLoc(),
13321 E->hasExplicitParameters(), E->isMutable());
13322
13323 // Introduce the context of the call operator.
13324 Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
13325 /*NewThisContext*/false);
13326
13327 bool Invalid = false;
13328
13329 // Transform captures.
13330 for (LambdaExpr::capture_iterator C = E->capture_begin(),
5
Loop condition is true. Entering loop body
13331 CEnd = E->capture_end();
13332 C != CEnd; ++C) {
4
Assuming 'C' is not equal to 'CEnd'
13333 // When we hit the first implicit capture, tell Sema that we've finished
13334 // the list of explicit captures.
13335 if (C->isImplicit())
6
Assuming the condition is false
7
Taking false branch
13336 break;
13337
13338 // Capturing 'this' is trivial.
13339 if (C->capturesThis()) {
8
Taking false branch
13340 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13341 /*BuildAndDiagnose*/ true, nullptr,
13342 C->getCaptureKind() == LCK_StarThis);
13343 continue;
13344 }
13345 // Captured expression will be recaptured during captured variables
13346 // rebuilding.
13347 if (C->capturesVLAType())
9
Taking false branch
13348 continue;
13349
13350 // Rebuild init-captures, including the implied field declaration.
13351 if (E->isInitCapture(C)) {
10
Assuming the condition is true
11
Taking true branch
13352 TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
13353
13354 auto *OldVD = cast<VarDecl>(C->getCapturedVar());
12
The object is a 'CastReturnType'
13355 llvm::SmallVector<Decl*, 4> NewVDs;
13356
13357 for (InitCaptureInfoTy &Info : NewC.Expansions) {
13
Assuming '__begin0' is equal to '__end0'
13358 ExprResult Init = Info.first;
13359 QualType InitQualType = Info.second;
13360 if (Init.isInvalid() || InitQualType.isNull()) {
13361 Invalid = true;
13362 break;
13363 }
13364 VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
13365 OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
13366 OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get(),
13367 getSema().CurContext);
13368 if (!NewVD) {
13369 Invalid = true;
13370 break;
13371 }
13372 NewVDs.push_back(NewVD);
13373 getSema().addInitCapture(LSI, NewVD, C->getCaptureKind() == LCK_ByRef);
13374 }
13375
13376 if (Invalid
13.1
'Invalid' is false
13.1
'Invalid' is false
)
14
Taking false branch
13377 break;
13378
13379 getDerived().transformedLocalDecl(OldVD, NewVDs);
15
Calling 'TemplateInstantiator::transformedLocalDecl'
13380 continue;
13381 }
13382
13383 assert(C->capturesVariable() && "unexpected kind of lambda capture")(static_cast <bool> (C->capturesVariable() &&
"unexpected kind of lambda capture") ? void (0) : __assert_fail
("C->capturesVariable() && \"unexpected kind of lambda capture\""
, "clang/lib/Sema/TreeTransform.h", 13383, __extension__ __PRETTY_FUNCTION__
))
;
13384
13385 // Determine the capture kind for Sema.
13386 Sema::TryCaptureKind Kind
13387 = C->isImplicit()? Sema::TryCapture_Implicit
13388 : C->getCaptureKind() == LCK_ByCopy
13389 ? Sema::TryCapture_ExplicitByVal
13390 : Sema::TryCapture_ExplicitByRef;
13391 SourceLocation EllipsisLoc;
13392 if (C->isPackExpansion()) {
13393 UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
13394 bool ShouldExpand = false;
13395 bool RetainExpansion = false;
13396 std::optional<unsigned> NumExpansions;
13397 if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
13398 C->getLocation(),
13399 Unexpanded,
13400 ShouldExpand, RetainExpansion,
13401 NumExpansions)) {
13402 Invalid = true;
13403 continue;
13404 }
13405
13406 if (ShouldExpand) {
13407 // The transform has determined that we should perform an expansion;
13408 // transform and capture each of the arguments.
13409 // expansion of the pattern. Do so.
13410 auto *Pack = cast<VarDecl>(C->getCapturedVar());
13411 for (unsigned I = 0; I != *NumExpansions; ++I) {
13412 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13413 VarDecl *CapturedVar
13414 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
13415 Pack));
13416 if (!CapturedVar) {
13417 Invalid = true;
13418 continue;
13419 }
13420
13421 // Capture the transformed variable.
13422 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
13423 }
13424
13425 // FIXME: Retain a pack expansion if RetainExpansion is true.
13426
13427 continue;
13428 }
13429
13430 EllipsisLoc = C->getEllipsisLoc();
13431 }
13432
13433 // Transform the captured variable.
13434 auto *CapturedVar = cast_or_null<ValueDecl>(
13435 getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13436 if (!CapturedVar || CapturedVar->isInvalidDecl()) {
13437 Invalid = true;
13438 continue;
13439 }
13440
13441 // Capture the transformed variable.
13442 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
13443 EllipsisLoc);
13444 }
13445 getSema().finishLambdaExplicitCaptures(LSI);
13446
13447 // Transform the template parameters, and add them to the current
13448 // instantiation scope. The null case is handled correctly.
13449 auto TPL = getDerived().TransformTemplateParameterList(
13450 E->getTemplateParameterList());
13451 LSI->GLTemplateParameterList = TPL;
13452
13453 // Transform the type of the original lambda's call operator.
13454 // The transformation MUST be done in the CurrentInstantiationScope since
13455 // it introduces a mapping of the original to the newly created
13456 // transformed parameters.
13457 TypeSourceInfo *NewCallOpTSI = nullptr;
13458 {
13459 TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
13460 auto OldCallOpFPTL =
13461 OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
13462
13463 TypeLocBuilder NewCallOpTLBuilder;
13464 SmallVector<QualType, 4> ExceptionStorage;
13465 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
13466 QualType NewCallOpType = TransformFunctionProtoType(
13467 NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
13468 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
13469 return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
13470 ExceptionStorage, Changed);
13471 });
13472 if (NewCallOpType.isNull())
13473 return ExprError();
13474 NewCallOpTSI =
13475 NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context, NewCallOpType);
13476 }
13477
13478 getSema().CompleteLambdaCallOperator(
13479 NewCallOperator, E->getCallOperator()->getLocation(),
13480 E->getCallOperator()->getInnerLocStart(),
13481 E->getCallOperator()->getTrailingRequiresClause(), NewCallOpTSI,
13482 E->getCallOperator()->getConstexprKind(),
13483 E->getCallOperator()->getStorageClass(),
13484 NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
13485 E->hasExplicitResultType());
13486
13487 getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
13488 getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
13489
13490 {
13491 // Number the lambda for linkage purposes if necessary.
13492 Sema::ContextRAII ManglingContext(getSema(), Class->getDeclContext());
13493
13494 std::optional<CXXRecordDecl::LambdaNumbering> Numbering;
13495 if (getDerived().ReplacingOriginal()) {
13496 Numbering = OldClass->getLambdaNumbering();
13497 }
13498
13499 getSema().handleLambdaNumbering(Class, NewCallOperator, Numbering);
13500 }
13501
13502 // FIXME: Sema's lambda-building mechanism expects us to push an expression
13503 // evaluation context even if we're not transforming the function body.
13504 getSema().PushExpressionEvaluationContext(
13505 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13506
13507 // Instantiate the body of the lambda expression.
13508 StmtResult Body =
13509 Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
13510
13511 // ActOnLambda* will pop the function scope for us.
13512 FuncScopeCleanup.disable();
13513
13514 if (Body.isInvalid()) {
13515 SavedContext.pop();
13516 getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
13517 /*IsInstantiation=*/true);
13518 return ExprError();
13519 }
13520
13521 // Copy the LSI before ActOnFinishFunctionBody removes it.
13522 // FIXME: This is dumb. Store the lambda information somewhere that outlives
13523 // the call operator.
13524 auto LSICopy = *LSI;
13525 getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
13526 /*IsInstantiation*/ true);
13527 SavedContext.pop();
13528
13529 return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
13530 &LSICopy);
13531}
13532
13533template<typename Derived>
13534StmtResult
13535TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
13536 return TransformStmt(S);
13537}
13538
13539template<typename Derived>
13540StmtResult
13541TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
13542 // Transform captures.
13543 for (LambdaExpr::capture_iterator C = E->capture_begin(),
13544 CEnd = E->capture_end();
13545 C != CEnd; ++C) {
13546 // When we hit the first implicit capture, tell Sema that we've finished
13547 // the list of explicit captures.
13548 if (!C->isImplicit())
13549 continue;
13550
13551 // Capturing 'this' is trivial.
13552 if (C->capturesThis()) {
13553 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13554 /*BuildAndDiagnose*/ true, nullptr,
13555 C->getCaptureKind() == LCK_StarThis);
13556 continue;
13557 }
13558 // Captured expression will be recaptured during captured variables
13559 // rebuilding.
13560 if (C->capturesVLAType())
13561 continue;
13562
13563 assert(C->capturesVariable() && "unexpected kind of lambda capture")(static_cast <bool> (C->capturesVariable() &&
"unexpected kind of lambda capture") ? void (0) : __assert_fail
("C->capturesVariable() && \"unexpected kind of lambda capture\""
, "clang/lib/Sema/TreeTransform.h", 13563, __extension__ __PRETTY_FUNCTION__
))
;
13564 assert(!E->isInitCapture(C) && "implicit init-capture?")(static_cast <bool> (!E->isInitCapture(C) &&
"implicit init-capture?") ? void (0) : __assert_fail ("!E->isInitCapture(C) && \"implicit init-capture?\""
, "clang/lib/Sema/TreeTransform.h", 13564, __extension__ __PRETTY_FUNCTION__
))
;
13565
13566 // Transform the captured variable.
13567 VarDecl *CapturedVar = cast_or_null<VarDecl>(
13568 getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13569 if (!CapturedVar || CapturedVar->isInvalidDecl())
13570 return StmtError();
13571
13572 // Capture the transformed variable.
13573 getSema().tryCaptureVariable(CapturedVar, C->getLocation());
13574 }
13575
13576 return S;
13577}
13578
13579template<typename Derived>
13580ExprResult
13581TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
13582 CXXUnresolvedConstructExpr *E) {
13583 TypeSourceInfo *T =
13584 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13585 if (!T)
13586 return ExprError();
13587
13588 bool ArgumentChanged = false;
13589 SmallVector<Expr*, 8> Args;
13590 Args.reserve(E->getNumArgs());
13591 {
13592 EnterExpressionEvaluationContext Context(
13593 getSema(), EnterExpressionEvaluationContext::InitList,
13594 E->isListInitialization());
13595 if (getDerived().TransformExprs(E->arg_begin(), E->getNumArgs(), true, Args,
13596 &ArgumentChanged))
13597 return ExprError();
13598 }
13599
13600 if (!getDerived().AlwaysRebuild() &&
13601 T == E->getTypeSourceInfo() &&
13602 !ArgumentChanged)
13603 return E;
13604
13605 // FIXME: we're faking the locations of the commas
13606 return getDerived().RebuildCXXUnresolvedConstructExpr(
13607 T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
13608}
13609
13610template<typename Derived>
13611ExprResult
13612TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
13613 CXXDependentScopeMemberExpr *E) {
13614 // Transform the base of the expression.
13615 ExprResult Base((Expr*) nullptr);
13616 Expr *OldBase;
13617 QualType BaseType;
13618 QualType ObjectType;
13619 if (!E->isImplicitAccess()) {
13620 OldBase = E->getBase();
13621 Base = getDerived().TransformExpr(OldBase);
13622 if (Base.isInvalid())
13623 return ExprError();
13624
13625 // Start the member reference and compute the object's type.
13626 ParsedType ObjectTy;
13627 bool MayBePseudoDestructor = false;
13628 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
13629 E->getOperatorLoc(),
13630 E->isArrow()? tok::arrow : tok::period,
13631 ObjectTy,
13632 MayBePseudoDestructor);
13633 if (Base.isInvalid())
13634 return ExprError();
13635
13636 ObjectType = ObjectTy.get();
13637 BaseType = ((Expr*) Base.get())->getType();
13638 } else {
13639 OldBase = nullptr;
13640 BaseType = getDerived().TransformType(E->getBaseType());
13641 ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
13642 }
13643
13644 // Transform the first part of the nested-name-specifier that qualifies
13645 // the member name.
13646 NamedDecl *FirstQualifierInScope
13647 = getDerived().TransformFirstQualifierInScope(
13648 E->getFirstQualifierFoundInScope(),
13649 E->getQualifierLoc().getBeginLoc());
13650
13651 NestedNameSpecifierLoc QualifierLoc;
13652 if (E->getQualifier()) {
13653 QualifierLoc
13654 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
13655 ObjectType,
13656 FirstQualifierInScope);
13657 if (!QualifierLoc)
13658 return ExprError();
13659 }
13660
13661 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13662
13663 // TODO: If this is a conversion-function-id, verify that the
13664 // destination type name (if present) resolves the same way after
13665 // instantiation as it did in the local scope.
13666
13667 DeclarationNameInfo NameInfo
13668 = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
13669 if (!NameInfo.getName())
13670 return ExprError();
13671
13672 if (!E->hasExplicitTemplateArgs()) {
13673 // This is a reference to a member without an explicitly-specified
13674 // template argument list. Optimize for this common case.
13675 if (!getDerived().AlwaysRebuild() &&
13676 Base.get() == OldBase &&
13677 BaseType == E->getBaseType() &&
13678 QualifierLoc == E->getQualifierLoc() &&
13679 NameInfo.getName() == E->getMember() &&
13680 FirstQualifierInScope == E->getFirstQualifierFoundInScope())
13681 return E;
13682
13683 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13684 BaseType,
13685 E->isArrow(),
13686 E->getOperatorLoc(),
13687 QualifierLoc,
13688 TemplateKWLoc,
13689 FirstQualifierInScope,
13690 NameInfo,
13691 /*TemplateArgs*/nullptr);
13692 }
13693
13694 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13695 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
13696 E->getNumTemplateArgs(),
13697 TransArgs))
13698 return ExprError();
13699
13700 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13701 BaseType,
13702 E->isArrow(),
13703 E->getOperatorLoc(),
13704 QualifierLoc,
13705 TemplateKWLoc,
13706 FirstQualifierInScope,
13707 NameInfo,
13708 &TransArgs);
13709}
13710
13711template <typename Derived>
13712ExprResult TreeTransform<Derived>::TransformUnresolvedMemberExpr(
13713 UnresolvedMemberExpr *Old) {
13714 // Transform the base of the expression.
13715 ExprResult Base((Expr *)nullptr);
13716 QualType BaseType;
13717 if (!Old->isImplicitAccess()) {
13718 Base = getDerived().TransformExpr(Old->getBase());
13719 if (Base.isInvalid())
13720 return ExprError();
13721 Base =
13722 getSema().PerformMemberExprBaseConversion(Base.get(), Old->isArrow());
13723 if (Base.isInvalid())
13724 return ExprError();
13725 BaseType = Base.get()->getType();
13726 } else {
13727 BaseType = getDerived().TransformType(Old->getBaseType());
13728 }
13729
13730 NestedNameSpecifierLoc QualifierLoc;
13731 if (Old->getQualifierLoc()) {
13732 QualifierLoc =
13733 getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
13734 if (!QualifierLoc)
13735 return ExprError();
13736 }
13737
13738 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
13739
13740 LookupResult R(SemaRef, Old->getMemberNameInfo(), Sema::LookupOrdinaryName);
13741
13742 // Transform the declaration set.
13743 if (TransformOverloadExprDecls(Old, /*RequiresADL*/ false, R))
13744 return ExprError();
13745
13746 // Determine the naming class.
13747 if (Old->getNamingClass()) {
13748 CXXRecordDecl *NamingClass = cast_or_null<CXXRecordDecl>(
13749 getDerived().TransformDecl(Old->getMemberLoc(), Old->getNamingClass()));
13750 if (!NamingClass)
13751 return ExprError();
13752
13753 R.setNamingClass(NamingClass);
13754 }
13755
13756 TemplateArgumentListInfo TransArgs;
13757 if (Old->hasExplicitTemplateArgs()) {
13758 TransArgs.setLAngleLoc(Old->getLAngleLoc());
13759 TransArgs.setRAngleLoc(Old->getRAngleLoc());
13760 if (getDerived().TransformTemplateArguments(
13761 Old->getTemplateArgs(), Old->getNumTemplateArgs(), TransArgs))
13762 return ExprError();
13763 }
13764
13765 // FIXME: to do this check properly, we will need to preserve the
13766 // first-qualifier-in-scope here, just in case we had a dependent
13767 // base (and therefore couldn't do the check) and a
13768 // nested-name-qualifier (and therefore could do the lookup).
13769 NamedDecl *FirstQualifierInScope = nullptr;
13770
13771 return getDerived().RebuildUnresolvedMemberExpr(
13772 Base.get(), BaseType, Old->getOperatorLoc(), Old->isArrow(), QualifierLoc,
13773 TemplateKWLoc, FirstQualifierInScope, R,
13774 (Old->hasExplicitTemplateArgs() ? &TransArgs : nullptr));
13775}
13776
13777template<typename Derived>
13778ExprResult
13779TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
13780 EnterExpressionEvaluationContext Unevaluated(
13781 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
13782 ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
13783 if (SubExpr.isInvalid())
13784 return ExprError();
13785
13786 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
13787 return E;
13788
13789 return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
13790}
13791
13792template<typename Derived>
13793ExprResult
13794TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
13795 ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
13796 if (Pattern.isInvalid())
13797 return ExprError();
13798
13799 if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
13800 return E;
13801
13802 return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
13803 E->getNumExpansions());
13804}
13805
13806template<typename Derived>
13807ExprResult
13808TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
13809 // If E is not value-dependent, then nothing will change when we transform it.
13810 // Note: This is an instantiation-centric view.
13811 if (!E->isValueDependent())
13812 return E;
13813
13814 EnterExpressionEvaluationContext Unevaluated(
13815 getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
13816
13817 ArrayRef<TemplateArgument> PackArgs;
13818 TemplateArgument ArgStorage;
13819
13820 // Find the argument list to transform.
13821 if (E->isPartiallySubstituted()) {
13822 PackArgs = E->getPartialArguments();
13823 } else if (E->isValueDependent()) {
13824 UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
13825 bool ShouldExpand = false;
13826 bool RetainExpansion = false;
13827 std::optional<unsigned> NumExpansions;
13828 if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
13829 Unexpanded,
13830 ShouldExpand, RetainExpansion,
13831 NumExpansions))
13832 return ExprError();
13833
13834 // If we need to expand the pack, build a template argument from it and
13835 // expand that.
13836 if (ShouldExpand) {
13837 auto *Pack = E->getPack();
13838 if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
13839 ArgStorage = getSema().Context.getPackExpansionType(
13840 getSema().Context.getTypeDeclType(TTPD), std::nullopt);
13841 } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
13842 ArgStorage = TemplateArgument(TemplateName(TTPD), std::nullopt);
13843 } else {
13844 auto *VD = cast<ValueDecl>(Pack);
13845 ExprResult DRE = getSema().BuildDeclRefExpr(
13846 VD, VD->getType().getNonLValueExprType(getSema().Context),
13847 VD->getType()->isReferenceType() ? VK_LValue : VK_PRValue,
13848 E->getPackLoc());
13849 if (DRE.isInvalid())
13850 return ExprError();
13851 ArgStorage = new (getSema().Context)
13852 PackExpansionExpr(getSema().Context.DependentTy, DRE.get(),
13853 E->getPackLoc(), std::nullopt);
13854 }
13855 PackArgs = ArgStorage;
13856 }
13857 }
13858
13859 // If we're not expanding the pack, just transform the decl.
13860 if (!PackArgs.size()) {
13861 auto *Pack = cast_or_null<NamedDecl>(
13862 getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
13863 if (!Pack)
13864 return ExprError();
13865 return getDerived().RebuildSizeOfPackExpr(
13866 E->getOperatorLoc(), Pack, E->getPackLoc(), E->getRParenLoc(),
13867 std::nullopt, std::nullopt);
13868 }
13869
13870 // Try to compute the result without performing a partial substitution.
13871 std::optional<unsigned> Result = 0;
13872 for (const TemplateArgument &Arg : PackArgs) {
13873 if (!Arg.isPackExpansion()) {
13874 Result = *Result + 1;
13875 continue;
13876 }
13877
13878 TemplateArgumentLoc ArgLoc;
13879 InventTemplateArgumentLoc(Arg, ArgLoc);
13880
13881 // Find the pattern of the pack expansion.
13882 SourceLocation Ellipsis;
13883 std::optional<unsigned> OrigNumExpansions;
13884 TemplateArgumentLoc Pattern =
13885 getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
13886 OrigNumExpansions);
13887
13888 // Substitute under the pack expansion. Do not expand the pack (yet).
13889 TemplateArgumentLoc OutPattern;
13890 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13891 if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
13892 /*Uneval*/ true))
13893 return true;
13894
13895 // See if we can determine the number of arguments from the result.
13896 std::optional<unsigned> NumExpansions =
13897 getSema().getFullyPackExpandedSize(OutPattern.getArgument());
13898 if (!NumExpansions) {
13899 // No: we must be in an alias template expansion, and we're going to need
13900 // to actually expand the packs.
13901 Result = std::nullopt;
13902 break;
13903 }
13904
13905 Result = *Result + *NumExpansions;
13906 }
13907
13908 // Common case: we could determine the number of expansions without
13909 // substituting.
13910 if (Result)
13911 return getDerived().RebuildSizeOfPackExpr(
13912 E->getOperatorLoc(), E->getPack(), E->getPackLoc(), E->getRParenLoc(),
13913 *Result, std::nullopt);
13914
13915 TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
13916 E->getPackLoc());
13917 {
13918 TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
13919 typedef TemplateArgumentLocInventIterator<
13920 Derived, const TemplateArgument*> PackLocIterator;
13921 if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
13922 PackLocIterator(*this, PackArgs.end()),
13923 TransformedPackArgs, /*Uneval*/true))
13924 return ExprError();
13925 }
13926
13927 // Check whether we managed to fully-expand the pack.
13928 // FIXME: Is it possible for us to do so and not hit the early exit path?
13929 SmallVector<TemplateArgument, 8> Args;
13930 bool PartialSubstitution = false;
13931 for (auto &Loc : TransformedPackArgs.arguments()) {
13932 Args.push_back(Loc.getArgument());
13933 if (Loc.getArgument().isPackExpansion())
13934 PartialSubstitution = true;
13935 }
13936
13937 if (PartialSubstitution)
13938 return getDerived().RebuildSizeOfPackExpr(
13939 E->getOperatorLoc(), E->getPack(), E->getPackLoc(), E->getRParenLoc(),
13940 std::nullopt, Args);
13941
13942 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13943 E->getPackLoc(), E->getRParenLoc(),
13944 Args.size(), std::nullopt);
13945}
13946
13947template<typename Derived>
13948ExprResult
13949TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
13950 SubstNonTypeTemplateParmPackExpr *E) {
13951 // Default behavior is to do nothing with this transformation.
13952 return E;
13953}
13954
13955template<typename Derived>
13956ExprResult
13957TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
13958 SubstNonTypeTemplateParmExpr *E) {
13959 // Default behavior is to do nothing with this transformation.
13960 return E;
13961}
13962
13963template<typename Derived>
13964ExprResult
13965TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
13966 // Default behavior is to do nothing with this transformation.
13967 return E;
13968}
13969
13970template<typename Derived>
13971ExprResult
13972TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
13973 MaterializeTemporaryExpr *E) {
13974 return getDerived().TransformExpr(E->getSubExpr());
13975}
13976
13977template<typename Derived>
13978ExprResult
13979TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
13980 UnresolvedLookupExpr *Callee = nullptr;
13981 if (Expr *OldCallee = E->getCallee()) {
13982 ExprResult CalleeResult = getDerived().TransformExpr(OldCallee);
13983 if (CalleeResult.isInvalid())
13984 return ExprError();
13985 Callee = cast<UnresolvedLookupExpr>(CalleeResult.get());
13986 }
13987
13988 Expr *Pattern = E->getPattern();
13989
13990 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13991 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
13992 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 13992, __extension__ __PRETTY_FUNCTION__
))
;
13993
13994 // Determine whether the set of unexpanded parameter packs can and should
13995 // be expanded.
13996 bool Expand = true;
13997 bool RetainExpansion = false;
13998 std::optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
13999 NumExpansions = OrigNumExpansions;
14000 if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
14001 Pattern->getSourceRange(),
14002 Unexpanded,
14003 Expand, RetainExpansion,
14004 NumExpansions))
14005 return true;
14006
14007 if (!Expand) {
14008 // Do not expand any packs here, just transform and rebuild a fold
14009 // expression.
14010 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
14011
14012 ExprResult LHS =
14013 E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
14014 if (LHS.isInvalid())
14015 return true;
14016
14017 ExprResult RHS =
14018 E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
14019 if (RHS.isInvalid())
14020 return true;
14021
14022 if (!getDerived().AlwaysRebuild() &&
14023 LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
14024 return E;
14025
14026 return getDerived().RebuildCXXFoldExpr(
14027 Callee, E->getBeginLoc(), LHS.get(), E->getOperator(),
14028 E->getEllipsisLoc(), RHS.get(), E->getEndLoc(), NumExpansions);
14029 }
14030
14031 // Formally a fold expression expands to nested parenthesized expressions.
14032 // Enforce this limit to avoid creating trees so deep we can't safely traverse
14033 // them.
14034 if (NumExpansions && SemaRef.getLangOpts().BracketDepth < NumExpansions) {
14035 SemaRef.Diag(E->getEllipsisLoc(),
14036 clang::diag::err_fold_expression_limit_exceeded)
14037 << *NumExpansions << SemaRef.getLangOpts().BracketDepth
14038 << E->getSourceRange();
14039 SemaRef.Diag(E->getEllipsisLoc(), diag::note_bracket_depth);
14040 return ExprError();
14041 }
14042
14043 // The transform has determined that we should perform an elementwise
14044 // expansion of the pattern. Do so.
14045 ExprResult Result = getDerived().TransformExpr(E->getInit());
14046 if (Result.isInvalid())
14047 return true;
14048 bool LeftFold = E->isLeftFold();
14049
14050 // If we're retaining an expansion for a right fold, it is the innermost
14051 // component and takes the init (if any).
14052 if (!LeftFold && RetainExpansion) {
14053 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
14054
14055 ExprResult Out = getDerived().TransformExpr(Pattern);
14056 if (Out.isInvalid())
14057 return true;
14058
14059 Result = getDerived().RebuildCXXFoldExpr(
14060 Callee, E->getBeginLoc(), Out.get(), E->getOperator(),
14061 E->getEllipsisLoc(), Result.get(), E->getEndLoc(), OrigNumExpansions);
14062 if (Result.isInvalid())
14063 return true;
14064 }
14065
14066 for (unsigned I = 0; I != *NumExpansions; ++I) {
14067 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
14068 getSema(), LeftFold ? I : *NumExpansions - I - 1);
14069 ExprResult Out = getDerived().TransformExpr(Pattern);
14070 if (Out.isInvalid())
14071 return true;
14072
14073 if (Out.get()->containsUnexpandedParameterPack()) {
14074 // We still have a pack; retain a pack expansion for this slice.
14075 Result = getDerived().RebuildCXXFoldExpr(
14076 Callee, E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
14077 E->getOperator(), E->getEllipsisLoc(),
14078 LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
14079 OrigNumExpansions);
14080 } else if (Result.isUsable()) {
14081 // We've got down to a single element; build a binary operator.
14082 Expr *LHS = LeftFold ? Result.get() : Out.get();
14083 Expr *RHS = LeftFold ? Out.get() : Result.get();
14084 if (Callee)
14085 Result = getDerived().RebuildCXXOperatorCallExpr(
14086 BinaryOperator::getOverloadedOperator(E->getOperator()),
14087 E->getEllipsisLoc(), Callee, LHS, RHS);
14088 else
14089 Result = getDerived().RebuildBinaryOperator(E->getEllipsisLoc(),
14090 E->getOperator(), LHS, RHS);
14091 } else
14092 Result = Out;
14093
14094 if (Result.isInvalid())
14095 return true;
14096 }
14097
14098 // If we're retaining an expansion for a left fold, it is the outermost
14099 // component and takes the complete expansion so far as its init (if any).
14100 if (LeftFold && RetainExpansion) {
14101 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
14102
14103 ExprResult Out = getDerived().TransformExpr(Pattern);
14104 if (Out.isInvalid())
14105 return true;
14106
14107 Result = getDerived().RebuildCXXFoldExpr(
14108 Callee, E->getBeginLoc(), Result.get(), E->getOperator(),
14109 E->getEllipsisLoc(), Out.get(), E->getEndLoc(), OrigNumExpansions);
14110 if (Result.isInvalid())
14111 return true;
14112 }
14113
14114 // If we had no init and an empty pack, and we're not retaining an expansion,
14115 // then produce a fallback value or error.
14116 if (Result.isUnset())
14117 return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
14118 E->getOperator());
14119
14120 return Result;
14121}
14122
14123template <typename Derived>
14124ExprResult
14125TreeTransform<Derived>::TransformCXXParenListInitExpr(CXXParenListInitExpr *E) {
14126 SmallVector<Expr *, 4> TransformedInits;
14127 ArrayRef<Expr *> InitExprs = E->getInitExprs();
14128 if (TransformExprs(InitExprs.data(), InitExprs.size(), true,
14129 TransformedInits))
14130 return ExprError();
14131
14132 return getDerived().RebuildParenListExpr(E->getBeginLoc(), TransformedInits,
14133 E->getEndLoc());
14134}
14135
14136template<typename Derived>
14137ExprResult
14138TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
14139 CXXStdInitializerListExpr *E) {
14140 return getDerived().TransformExpr(E->getSubExpr());
14141}
14142
14143template<typename Derived>
14144ExprResult
14145TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
14146 return SemaRef.MaybeBindToTemporary(E);
14147}
14148
14149template<typename Derived>
14150ExprResult
14151TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
14152 return E;
14153}
14154
14155template<typename Derived>
14156ExprResult
14157TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
14158 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
14159 if (SubExpr.isInvalid())
14160 return ExprError();
14161
14162 if (!getDerived().AlwaysRebuild() &&
14163 SubExpr.get() == E->getSubExpr())
14164 return E;
14165
14166 return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
14167}
14168
14169template<typename Derived>
14170ExprResult
14171TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
14172 // Transform each of the elements.
14173 SmallVector<Expr *, 8> Elements;
14174 bool ArgChanged = false;
14175 if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
14176 /*IsCall=*/false, Elements, &ArgChanged))
14177 return ExprError();
14178
14179 if (!getDerived().AlwaysRebuild() && !ArgChanged)
14180 return SemaRef.MaybeBindToTemporary(E);
14181
14182 return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
14183 Elements.data(),
14184 Elements.size());
14185}
14186
14187template<typename Derived>
14188ExprResult
14189TreeTransform<Derived>::TransformObjCDictionaryLiteral(
14190 ObjCDictionaryLiteral *E) {
14191 // Transform each of the elements.
14192 SmallVector<ObjCDictionaryElement, 8> Elements;
14193 bool ArgChanged = false;
14194 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
14195 ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
14196
14197 if (OrigElement.isPackExpansion()) {
14198 // This key/value element is a pack expansion.
14199 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14200 getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
14201 getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
14202 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 14202, __extension__ __PRETTY_FUNCTION__
))
;
14203
14204 // Determine whether the set of unexpanded parameter packs can
14205 // and should be expanded.
14206 bool Expand = true;
14207 bool RetainExpansion = false;
14208 std::optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
14209 std::optional<unsigned> NumExpansions = OrigNumExpansions;
14210 SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
14211 OrigElement.Value->getEndLoc());
14212 if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
14213 PatternRange, Unexpanded, Expand,
14214 RetainExpansion, NumExpansions))
14215 return ExprError();
14216
14217 if (!Expand) {
14218 // The transform has determined that we should perform a simple
14219 // transformation on the pack expansion, producing another pack
14220 // expansion.
14221 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
14222 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14223 if (Key.isInvalid())
14224 return ExprError();
14225
14226 if (Key.get() != OrigElement.Key)
14227 ArgChanged = true;
14228
14229 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
14230 if (Value.isInvalid())
14231 return ExprError();
14232
14233 if (Value.get() != OrigElement.Value)
14234 ArgChanged = true;
14235
14236 ObjCDictionaryElement Expansion = {
14237 Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
14238 };
14239 Elements.push_back(Expansion);
14240 continue;
14241 }
14242
14243 // Record right away that the argument was changed. This needs
14244 // to happen even if the array expands to nothing.
14245 ArgChanged = true;
14246
14247 // The transform has determined that we should perform an elementwise
14248 // expansion of the pattern. Do so.
14249 for (unsigned I = 0; I != *NumExpansions; ++I) {
14250 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
14251 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14252 if (Key.isInvalid())
14253 return ExprError();
14254
14255 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
14256 if (Value.isInvalid())
14257 return ExprError();
14258
14259 ObjCDictionaryElement Element = {
14260 Key.get(), Value.get(), SourceLocation(), NumExpansions
14261 };
14262
14263 // If any unexpanded parameter packs remain, we still have a
14264 // pack expansion.
14265 // FIXME: Can this really happen?
14266 if (Key.get()->containsUnexpandedParameterPack() ||
14267 Value.get()->containsUnexpandedParameterPack())
14268 Element.EllipsisLoc = OrigElement.EllipsisLoc;
14269
14270 Elements.push_back(Element);
14271 }
14272
14273 // FIXME: Retain a pack expansion if RetainExpansion is true.
14274
14275 // We've finished with this pack expansion.
14276 continue;
14277 }
14278
14279 // Transform and check key.
14280 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14281 if (Key.isInvalid())
14282 return ExprError();
14283
14284 if (Key.get() != OrigElement.Key)
14285 ArgChanged = true;
14286
14287 // Transform and check value.
14288 ExprResult Value
14289 = getDerived().TransformExpr(OrigElement.Value);
14290 if (Value.isInvalid())
14291 return ExprError();
14292
14293 if (Value.get() != OrigElement.Value)
14294 ArgChanged = true;
14295
14296 ObjCDictionaryElement Element = {Key.get(), Value.get(), SourceLocation(),
14297 std::nullopt};
14298 Elements.push_back(Element);
14299 }
14300
14301 if (!getDerived().AlwaysRebuild() && !ArgChanged)
14302 return SemaRef.MaybeBindToTemporary(E);
14303
14304 return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
14305 Elements);
14306}
14307
14308template<typename Derived>
14309ExprResult
14310TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
14311 TypeSourceInfo *EncodedTypeInfo
14312 = getDerived().TransformType(E->getEncodedTypeSourceInfo());
14313 if (!EncodedTypeInfo)
14314 return ExprError();
14315
14316 if (!getDerived().AlwaysRebuild() &&
14317 EncodedTypeInfo == E->getEncodedTypeSourceInfo())
14318 return E;
14319
14320 return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
14321 EncodedTypeInfo,
14322 E->getRParenLoc());
14323}
14324
14325template<typename Derived>
14326ExprResult TreeTransform<Derived>::
14327TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
14328 // This is a kind of implicit conversion, and it needs to get dropped
14329 // and recomputed for the same general reasons that ImplicitCastExprs
14330 // do, as well a more specific one: this expression is only valid when
14331 // it appears *immediately* as an argument expression.
14332 return getDerived().TransformExpr(E->getSubExpr());
14333}
14334
14335template<typename Derived>
14336ExprResult TreeTransform<Derived>::
14337TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
14338 TypeSourceInfo *TSInfo
14339 = getDerived().TransformType(E->getTypeInfoAsWritten());
14340 if (!TSInfo)
14341 return ExprError();
14342
14343 ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
14344 if (Result.isInvalid())
14345 return ExprError();
14346
14347 if (!getDerived().AlwaysRebuild() &&
14348 TSInfo == E->getTypeInfoAsWritten() &&
14349 Result.get() == E->getSubExpr())
14350 return E;
14351
14352 return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
14353 E->getBridgeKeywordLoc(), TSInfo,
14354 Result.get());
14355}
14356
14357template <typename Derived>
14358ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
14359 ObjCAvailabilityCheckExpr *E) {
14360 return E;
14361}
14362
14363template<typename Derived>
14364ExprResult
14365TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
14366 // Transform arguments.
14367 bool ArgChanged = false;
14368 SmallVector<Expr*, 8> Args;
14369 Args.reserve(E->getNumArgs());
14370 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
14371 &ArgChanged))
14372 return ExprError();
14373
14374 if (E->getReceiverKind() == ObjCMessageExpr::Class) {
14375 // Class message: transform the receiver type.
14376 TypeSourceInfo *ReceiverTypeInfo
14377 = getDerived().TransformType(E->getClassReceiverTypeInfo());
14378 if (!ReceiverTypeInfo)
14379 return ExprError();
14380
14381 // If nothing changed, just retain the existing message send.
14382 if (!getDerived().AlwaysRebuild() &&
14383 ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
14384 return SemaRef.MaybeBindToTemporary(E);
14385
14386 // Build a new class message send.
14387 SmallVector<SourceLocation, 16> SelLocs;
14388 E->getSelectorLocs(SelLocs);
14389 return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
14390 E->getSelector(),
14391 SelLocs,
14392 E->getMethodDecl(),
14393 E->getLeftLoc(),
14394 Args,
14395 E->getRightLoc());
14396 }
14397 else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
14398 E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14399 if (!E->getMethodDecl())
14400 return ExprError();
14401
14402 // Build a new class message send to 'super'.
14403 SmallVector<SourceLocation, 16> SelLocs;
14404 E->getSelectorLocs(SelLocs);
14405 return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
14406 E->getSelector(),
14407 SelLocs,
14408 E->getReceiverType(),
14409 E->getMethodDecl(),
14410 E->getLeftLoc(),
14411 Args,
14412 E->getRightLoc());
14413 }
14414
14415 // Instance message: transform the receiver
14416 assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&(static_cast <bool> (E->getReceiverKind() == ObjCMessageExpr
::Instance && "Only class and instance messages may be instantiated"
) ? void (0) : __assert_fail ("E->getReceiverKind() == ObjCMessageExpr::Instance && \"Only class and instance messages may be instantiated\""
, "clang/lib/Sema/TreeTransform.h", 14417, __extension__ __PRETTY_FUNCTION__
))
14417 "Only class and instance messages may be instantiated")(static_cast <bool> (E->getReceiverKind() == ObjCMessageExpr
::Instance && "Only class and instance messages may be instantiated"
) ? void (0) : __assert_fail ("E->getReceiverKind() == ObjCMessageExpr::Instance && \"Only class and instance messages may be instantiated\""
, "clang/lib/Sema/TreeTransform.h", 14417, __extension__ __PRETTY_FUNCTION__
))
;
14418 ExprResult Receiver
14419 = getDerived().TransformExpr(E->getInstanceReceiver());
14420 if (Receiver.isInvalid())
14421 return ExprError();
14422
14423 // If nothing changed, just retain the existing message send.
14424 if (!getDerived().AlwaysRebuild() &&
14425 Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
14426 return SemaRef.MaybeBindToTemporary(E);
14427
14428 // Build a new instance message send.
14429 SmallVector<SourceLocation, 16> SelLocs;
14430 E->getSelectorLocs(SelLocs);
14431 return getDerived().RebuildObjCMessageExpr(Receiver.get(),
14432 E->getSelector(),
14433 SelLocs,
14434 E->getMethodDecl(),
14435 E->getLeftLoc(),
14436 Args,
14437 E->getRightLoc());
14438}
14439
14440template<typename Derived>
14441ExprResult
14442TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
14443 return E;
14444}
14445
14446template<typename Derived>
14447ExprResult
14448TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
14449 return E;
14450}
14451
14452template<typename Derived>
14453ExprResult
14454TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
14455 // Transform the base expression.
14456 ExprResult Base = getDerived().TransformExpr(E->getBase());
14457 if (Base.isInvalid())
14458 return ExprError();
14459
14460 // We don't need to transform the ivar; it will never change.
14461
14462 // If nothing changed, just retain the existing expression.
14463 if (!getDerived().AlwaysRebuild() &&
14464 Base.get() == E->getBase())
14465 return E;
14466
14467 return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
14468 E->getLocation(),
14469 E->isArrow(), E->isFreeIvar());
14470}
14471
14472template<typename Derived>
14473ExprResult
14474TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
14475 // 'super' and types never change. Property never changes. Just
14476 // retain the existing expression.
14477 if (!E->isObjectReceiver())
14478 return E;
14479
14480 // Transform the base expression.
14481 ExprResult Base = getDerived().TransformExpr(E->getBase());
14482 if (Base.isInvalid())
14483 return ExprError();
14484
14485 // We don't need to transform the property; it will never change.
14486
14487 // If nothing changed, just retain the existing expression.
14488 if (!getDerived().AlwaysRebuild() &&
14489 Base.get() == E->getBase())
14490 return E;
14491
14492 if (E->isExplicitProperty())
14493 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14494 E->getExplicitProperty(),
14495 E->getLocation());
14496
14497 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14498 SemaRef.Context.PseudoObjectTy,
14499 E->getImplicitPropertyGetter(),
14500 E->getImplicitPropertySetter(),
14501 E->getLocation());
14502}
14503
14504template<typename Derived>
14505ExprResult
14506TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
14507 // Transform the base expression.
14508 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
14509 if (Base.isInvalid())
14510 return ExprError();
14511
14512 // Transform the key expression.
14513 ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
14514 if (Key.isInvalid())
14515 return ExprError();
14516
14517 // If nothing changed, just retain the existing expression.
14518 if (!getDerived().AlwaysRebuild() &&
14519 Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
14520 return E;
14521
14522 return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
14523 Base.get(), Key.get(),
14524 E->getAtIndexMethodDecl(),
14525 E->setAtIndexMethodDecl());
14526}
14527
14528template<typename Derived>
14529ExprResult
14530TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
14531 // Transform the base expression.
14532 ExprResult Base = getDerived().TransformExpr(E->getBase());
14533 if (Base.isInvalid())
14534 return ExprError();
14535
14536 // If nothing changed, just retain the existing expression.
14537 if (!getDerived().AlwaysRebuild() &&
14538 Base.get() == E->getBase())
14539 return E;
14540
14541 return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
14542 E->getOpLoc(),
14543 E->isArrow());
14544}
14545
14546template<typename Derived>
14547ExprResult
14548TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
14549 bool ArgumentChanged = false;
14550 SmallVector<Expr*, 8> SubExprs;
14551 SubExprs.reserve(E->getNumSubExprs());
14552 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14553 SubExprs, &ArgumentChanged))
14554 return ExprError();
14555
14556 if (!getDerived().AlwaysRebuild() &&
14557 !ArgumentChanged)
14558 return E;
14559
14560 return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
14561 SubExprs,
14562 E->getRParenLoc());
14563}
14564
14565template<typename Derived>
14566ExprResult
14567TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
14568 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14569 if (SrcExpr.isInvalid())
14570 return ExprError();
14571
14572 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
14573 if (!Type)
14574 return ExprError();
14575
14576 if (!getDerived().AlwaysRebuild() &&
14577 Type == E->getTypeSourceInfo() &&
14578 SrcExpr.get() == E->getSrcExpr())
14579 return E;
14580
14581 return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
14582 SrcExpr.get(), Type,
14583 E->getRParenLoc());
14584}
14585
14586template<typename Derived>
14587ExprResult
14588TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
14589 BlockDecl *oldBlock = E->getBlockDecl();
14590
14591 SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
14592 BlockScopeInfo *blockScope = SemaRef.getCurBlock();
14593
14594 blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
14595 blockScope->TheDecl->setBlockMissingReturnType(
14596 oldBlock->blockMissingReturnType());
14597
14598 SmallVector<ParmVarDecl*, 4> params;
14599 SmallVector<QualType, 4> paramTypes;
14600
14601 const FunctionProtoType *exprFunctionType = E->getFunctionType();
14602
14603 // Parameter substitution.
14604 Sema::ExtParameterInfoBuilder extParamInfos;
14605 if (getDerived().TransformFunctionTypeParams(
14606 E->getCaretLocation(), oldBlock->parameters(), nullptr,
14607 exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
14608 extParamInfos)) {
14609 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14610 return ExprError();
14611 }
14612
14613 QualType exprResultType =
14614 getDerived().TransformType(exprFunctionType->getReturnType());
14615
14616 auto epi = exprFunctionType->getExtProtoInfo();
14617 epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
14618
14619 QualType functionType =
14620 getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
14621 blockScope->FunctionType = functionType;
14622
14623 // Set the parameters on the block decl.
14624 if (!params.empty())
14625 blockScope->TheDecl->setParams(params);
14626
14627 if (!oldBlock->blockMissingReturnType()) {
14628 blockScope->HasImplicitReturnType = false;
14629 blockScope->ReturnType = exprResultType;
14630 }
14631
14632 // Transform the body
14633 StmtResult body = getDerived().TransformStmt(E->getBody());
14634 if (body.isInvalid()) {
14635 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14636 return ExprError();
14637 }
14638
14639#ifndef NDEBUG
14640 // In builds with assertions, make sure that we captured everything we
14641 // captured before.
14642 if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
14643 for (const auto &I : oldBlock->captures()) {
14644 VarDecl *oldCapture = I.getVariable();
14645
14646 // Ignore parameter packs.
14647 if (oldCapture->isParameterPack())
14648 continue;
14649
14650 VarDecl *newCapture =
14651 cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
14652 oldCapture));
14653 assert(blockScope->CaptureMap.count(newCapture))(static_cast <bool> (blockScope->CaptureMap.count(newCapture
)) ? void (0) : __assert_fail ("blockScope->CaptureMap.count(newCapture)"
, "clang/lib/Sema/TreeTransform.h", 14653, __extension__ __PRETTY_FUNCTION__
))
;
14654 }
14655
14656 // The this pointer may not be captured by the instantiated block, even when
14657 // it's captured by the original block, if the expression causing the
14658 // capture is in the discarded branch of a constexpr if statement.
14659 assert((!blockScope->isCXXThisCaptured() || oldBlock->capturesCXXThis()) &&(static_cast <bool> ((!blockScope->isCXXThisCaptured
() || oldBlock->capturesCXXThis()) && "this pointer isn't captured in the old block"
) ? void (0) : __assert_fail ("(!blockScope->isCXXThisCaptured() || oldBlock->capturesCXXThis()) && \"this pointer isn't captured in the old block\""
, "clang/lib/Sema/TreeTransform.h", 14660, __extension__ __PRETTY_FUNCTION__
))
14660 "this pointer isn't captured in the old block")(static_cast <bool> ((!blockScope->isCXXThisCaptured
() || oldBlock->capturesCXXThis()) && "this pointer isn't captured in the old block"
) ? void (0) : __assert_fail ("(!blockScope->isCXXThisCaptured() || oldBlock->capturesCXXThis()) && \"this pointer isn't captured in the old block\""
, "clang/lib/Sema/TreeTransform.h", 14660, __extension__ __PRETTY_FUNCTION__
))
;
14661 }
14662#endif
14663
14664 return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
14665 /*Scope=*/nullptr);
14666}
14667
14668template<typename Derived>
14669ExprResult
14670TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
14671 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14672 if (SrcExpr.isInvalid())
14673 return ExprError();
14674
14675 QualType Type = getDerived().TransformType(E->getType());
14676
14677 return SemaRef.BuildAsTypeExpr(SrcExpr.get(), Type, E->getBuiltinLoc(),
14678 E->getRParenLoc());
14679}
14680
14681template<typename Derived>
14682ExprResult
14683TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
14684 bool ArgumentChanged = false;
14685 SmallVector<Expr*, 8> SubExprs;
14686 SubExprs.reserve(E->getNumSubExprs());
14687 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14688 SubExprs, &ArgumentChanged))
14689 return ExprError();
14690
14691 if (!getDerived().AlwaysRebuild() &&
14692 !ArgumentChanged)
14693 return E;
14694
14695 return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
14696 E->getOp(), E->getRParenLoc());
14697}
14698
14699//===----------------------------------------------------------------------===//
14700// Type reconstruction
14701//===----------------------------------------------------------------------===//
14702
14703template<typename Derived>
14704QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
14705 SourceLocation Star) {
14706 return SemaRef.BuildPointerType(PointeeType, Star,
14707 getDerived().getBaseEntity());
14708}
14709
14710template<typename Derived>
14711QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
14712 SourceLocation Star) {
14713 return SemaRef.BuildBlockPointerType(PointeeType, Star,
14714 getDerived().getBaseEntity());
14715}
14716
14717template<typename Derived>
14718QualType
14719TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
14720 bool WrittenAsLValue,
14721 SourceLocation Sigil) {
14722 return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
14723 Sigil, getDerived().getBaseEntity());
14724}
14725
14726template<typename Derived>
14727QualType
14728TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
14729 QualType ClassType,
14730 SourceLocation Sigil) {
14731 return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
14732 getDerived().getBaseEntity());
14733}
14734
14735template<typename Derived>
14736QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
14737 const ObjCTypeParamDecl *Decl,
14738 SourceLocation ProtocolLAngleLoc,
14739 ArrayRef<ObjCProtocolDecl *> Protocols,
14740 ArrayRef<SourceLocation> ProtocolLocs,
14741 SourceLocation ProtocolRAngleLoc) {
14742 return SemaRef.BuildObjCTypeParamType(Decl,
14743 ProtocolLAngleLoc, Protocols,
14744 ProtocolLocs, ProtocolRAngleLoc,
14745 /*FailOnError=*/true);
14746}
14747
14748template<typename Derived>
14749QualType TreeTransform<Derived>::RebuildObjCObjectType(
14750 QualType BaseType,
14751 SourceLocation Loc,
14752 SourceLocation TypeArgsLAngleLoc,
14753 ArrayRef<TypeSourceInfo *> TypeArgs,
14754 SourceLocation TypeArgsRAngleLoc,
14755 SourceLocation ProtocolLAngleLoc,
14756 ArrayRef<ObjCProtocolDecl *> Protocols,
14757 ArrayRef<SourceLocation> ProtocolLocs,
14758 SourceLocation ProtocolRAngleLoc) {
14759 return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc, TypeArgs,
14760 TypeArgsRAngleLoc, ProtocolLAngleLoc,
14761 Protocols, ProtocolLocs, ProtocolRAngleLoc,
14762 /*FailOnError=*/true,
14763 /*Rebuilding=*/true);
14764}
14765
14766template<typename Derived>
14767QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
14768 QualType PointeeType,
14769 SourceLocation Star) {
14770 return SemaRef.Context.getObjCObjectPointerType(PointeeType);
14771}
14772
14773template<typename Derived>
14774QualType
14775TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
14776 ArrayType::ArraySizeModifier SizeMod,
14777 const llvm::APInt *Size,
14778 Expr *SizeExpr,
14779 unsigned IndexTypeQuals,
14780 SourceRange BracketsRange) {
14781 if (SizeExpr || !Size)
14782 return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
14783 IndexTypeQuals, BracketsRange,
14784 getDerived().getBaseEntity());
14785
14786 QualType Types[] = {
14787 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
14788 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
14789 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
14790 };
14791 QualType SizeType;
14792 for (const auto &T : Types)
14793 if (Size->getBitWidth() == SemaRef.Context.getIntWidth(T)) {
14794 SizeType = T;
14795 break;
14796 }
14797
14798 // Note that we can return a VariableArrayType here in the case where
14799 // the element type was a dependent VariableArrayType.
14800 IntegerLiteral *ArraySize
14801 = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
14802 /*FIXME*/BracketsRange.getBegin());
14803 return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
14804 IndexTypeQuals, BracketsRange,
14805 getDerived().getBaseEntity());
14806}
14807
14808template<typename Derived>
14809QualType
14810TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
14811 ArrayType::ArraySizeModifier SizeMod,
14812 const llvm::APInt &Size,
14813 Expr *SizeExpr,
14814 unsigned IndexTypeQuals,
14815 SourceRange BracketsRange) {
14816 return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
14817 IndexTypeQuals, BracketsRange);
14818}
14819
14820template<typename Derived>
14821QualType
14822TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
14823 ArrayType::ArraySizeModifier SizeMod,
14824 unsigned IndexTypeQuals,
14825 SourceRange BracketsRange) {
14826 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
14827 IndexTypeQuals, BracketsRange);
14828}
14829
14830template<typename Derived>
14831QualType
14832TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
14833 ArrayType::ArraySizeModifier SizeMod,
14834 Expr *SizeExpr,
14835 unsigned IndexTypeQuals,
14836 SourceRange BracketsRange) {
14837 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14838 SizeExpr,
14839 IndexTypeQuals, BracketsRange);
14840}
14841
14842template<typename Derived>
14843QualType
14844TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
14845 ArrayType::ArraySizeModifier SizeMod,
14846 Expr *SizeExpr,
14847 unsigned IndexTypeQuals,
14848 SourceRange BracketsRange) {
14849 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14850 SizeExpr,
14851 IndexTypeQuals, BracketsRange);
14852}
14853
14854template <typename Derived>
14855QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
14856 QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
14857 return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
14858 AttributeLoc);
14859}
14860
14861template <typename Derived>
14862QualType
14863TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
14864 unsigned NumElements,
14865 VectorType::VectorKind VecKind) {
14866 // FIXME: semantic checking!
14867 return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
14868}
14869
14870template <typename Derived>
14871QualType TreeTransform<Derived>::RebuildDependentVectorType(
14872 QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
14873 VectorType::VectorKind VecKind) {
14874 return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
14875}
14876
14877template<typename Derived>
14878QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
14879 unsigned NumElements,
14880 SourceLocation AttributeLoc) {
14881 llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
14882 NumElements, true);
14883 IntegerLiteral *VectorSize
14884 = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
14885 AttributeLoc);
14886 return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
14887}
14888
14889template<typename Derived>
14890QualType
14891TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
14892 Expr *SizeExpr,
14893 SourceLocation AttributeLoc) {
14894 return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
14895}
14896
14897template <typename Derived>
14898QualType TreeTransform<Derived>::RebuildConstantMatrixType(
14899 QualType ElementType, unsigned NumRows, unsigned NumColumns) {
14900 return SemaRef.Context.getConstantMatrixType(ElementType, NumRows,
14901 NumColumns);
14902}
14903
14904template <typename Derived>
14905QualType TreeTransform<Derived>::RebuildDependentSizedMatrixType(
14906 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr,
14907 SourceLocation AttributeLoc) {
14908 return SemaRef.BuildMatrixType(ElementType, RowExpr, ColumnExpr,
14909 AttributeLoc);
14910}
14911
14912template<typename Derived>
14913QualType TreeTransform<Derived>::RebuildFunctionProtoType(
14914 QualType T,
14915 MutableArrayRef<QualType> ParamTypes,
14916 const FunctionProtoType::ExtProtoInfo &EPI) {
14917 return SemaRef.BuildFunctionType(T, ParamTypes,
14918 getDerived().getBaseLocation(),
14919 getDerived().getBaseEntity(),
14920 EPI);
14921}
14922
14923template<typename Derived>
14924QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
14925 return SemaRef.Context.getFunctionNoProtoType(T);
14926}
14927
14928template<typename Derived>
14929QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
14930 Decl *D) {
14931 assert(D && "no decl found")(static_cast <bool> (D && "no decl found") ? void
(0) : __assert_fail ("D && \"no decl found\"", "clang/lib/Sema/TreeTransform.h"
, 14931, __extension__ __PRETTY_FUNCTION__))
;
14932 if (D->isInvalidDecl()) return QualType();
14933
14934 // FIXME: Doesn't account for ObjCInterfaceDecl!
14935 if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
14936 // A valid resolved using typename pack expansion decl can have multiple
14937 // UsingDecls, but they must each have exactly one type, and it must be
14938 // the same type in every case. But we must have at least one expansion!
14939 if (UPD->expansions().empty()) {
14940 getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
14941 << UPD->isCXXClassMember() << UPD;
14942 return QualType();
14943 }
14944
14945 // We might still have some unresolved types. Try to pick a resolved type
14946 // if we can. The final instantiation will check that the remaining
14947 // unresolved types instantiate to the type we pick.
14948 QualType FallbackT;
14949 QualType T;
14950 for (auto *E : UPD->expansions()) {
14951 QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
14952 if (ThisT.isNull())
14953 continue;
14954 else if (ThisT->getAs<UnresolvedUsingType>())
14955 FallbackT = ThisT;
14956 else if (T.isNull())
14957 T = ThisT;
14958 else
14959 assert(getSema().Context.hasSameType(ThisT, T) &&(static_cast <bool> (getSema().Context.hasSameType(ThisT
, T) && "mismatched resolved types in using pack expansion"
) ? void (0) : __assert_fail ("getSema().Context.hasSameType(ThisT, T) && \"mismatched resolved types in using pack expansion\""
, "clang/lib/Sema/TreeTransform.h", 14960, __extension__ __PRETTY_FUNCTION__
))
14960 "mismatched resolved types in using pack expansion")(static_cast <bool> (getSema().Context.hasSameType(ThisT
, T) && "mismatched resolved types in using pack expansion"
) ? void (0) : __assert_fail ("getSema().Context.hasSameType(ThisT, T) && \"mismatched resolved types in using pack expansion\""
, "clang/lib/Sema/TreeTransform.h", 14960, __extension__ __PRETTY_FUNCTION__
))
;
14961 }
14962 return T.isNull() ? FallbackT : T;
14963 } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
14964 assert(Using->hasTypename() &&(static_cast <bool> (Using->hasTypename() &&
"UnresolvedUsingTypenameDecl transformed to non-typename using"
) ? void (0) : __assert_fail ("Using->hasTypename() && \"UnresolvedUsingTypenameDecl transformed to non-typename using\""
, "clang/lib/Sema/TreeTransform.h", 14965, __extension__ __PRETTY_FUNCTION__
))
14965 "UnresolvedUsingTypenameDecl transformed to non-typename using")(static_cast <bool> (Using->hasTypename() &&
"UnresolvedUsingTypenameDecl transformed to non-typename using"
) ? void (0) : __assert_fail ("Using->hasTypename() && \"UnresolvedUsingTypenameDecl transformed to non-typename using\""
, "clang/lib/Sema/TreeTransform.h", 14965, __extension__ __PRETTY_FUNCTION__
))
;
14966
14967 // A valid resolved using typename decl points to exactly one type decl.
14968 assert(++Using->shadow_begin() == Using->shadow_end())(static_cast <bool> (++Using->shadow_begin() == Using
->shadow_end()) ? void (0) : __assert_fail ("++Using->shadow_begin() == Using->shadow_end()"
, "clang/lib/Sema/TreeTransform.h", 14968, __extension__ __PRETTY_FUNCTION__
))
;
14969
14970 UsingShadowDecl *Shadow = *Using->shadow_begin();
14971 if (SemaRef.DiagnoseUseOfDecl(Shadow->getTargetDecl(), Loc))
14972 return QualType();
14973 return SemaRef.Context.getUsingType(
14974 Shadow, SemaRef.Context.getTypeDeclType(
14975 cast<TypeDecl>(Shadow->getTargetDecl())));
14976 } else {
14977 assert(isa<UnresolvedUsingTypenameDecl>(D) &&(static_cast <bool> (isa<UnresolvedUsingTypenameDecl
>(D) && "UnresolvedUsingTypenameDecl transformed to non-using decl"
) ? void (0) : __assert_fail ("isa<UnresolvedUsingTypenameDecl>(D) && \"UnresolvedUsingTypenameDecl transformed to non-using decl\""
, "clang/lib/Sema/TreeTransform.h", 14978, __extension__ __PRETTY_FUNCTION__
))
14978 "UnresolvedUsingTypenameDecl transformed to non-using decl")(static_cast <bool> (isa<UnresolvedUsingTypenameDecl
>(D) && "UnresolvedUsingTypenameDecl transformed to non-using decl"
) ? void (0) : __assert_fail ("isa<UnresolvedUsingTypenameDecl>(D) && \"UnresolvedUsingTypenameDecl transformed to non-using decl\""
, "clang/lib/Sema/TreeTransform.h", 14978, __extension__ __PRETTY_FUNCTION__
))
;
14979 return SemaRef.Context.getTypeDeclType(
14980 cast<UnresolvedUsingTypenameDecl>(D));
14981 }
14982}
14983
14984template <typename Derived>
14985QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E, SourceLocation,
14986 TypeOfKind Kind) {
14987 return SemaRef.BuildTypeofExprType(E, Kind);
14988}
14989
14990template<typename Derived>
14991QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying,
14992 TypeOfKind Kind) {
14993 return SemaRef.Context.getTypeOfType(Underlying, Kind);
14994}
14995
14996template <typename Derived>
14997QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E, SourceLocation) {
14998 return SemaRef.BuildDecltypeType(E);
14999}
15000
15001template<typename Derived>
15002QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
15003 UnaryTransformType::UTTKind UKind,
15004 SourceLocation Loc) {
15005 return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
15006}
15007
15008template<typename Derived>
15009QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
15010 TemplateName Template,
15011 SourceLocation TemplateNameLoc,
15012 TemplateArgumentListInfo &TemplateArgs) {
15013 return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
15014}
15015
15016template<typename Derived>
15017QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
15018 SourceLocation KWLoc) {
15019 return SemaRef.BuildAtomicType(ValueType, KWLoc);
15020}
15021
15022template<typename Derived>
15023QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
15024 SourceLocation KWLoc,
15025 bool isReadPipe) {
15026 return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
15027 : SemaRef.BuildWritePipeType(ValueType, KWLoc);
15028}
15029
15030template <typename Derived>
15031QualType TreeTransform<Derived>::RebuildBitIntType(bool IsUnsigned,
15032 unsigned NumBits,
15033 SourceLocation Loc) {
15034 llvm::APInt NumBitsAP(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
15035 NumBits, true);
15036 IntegerLiteral *Bits = IntegerLiteral::Create(SemaRef.Context, NumBitsAP,
15037 SemaRef.Context.IntTy, Loc);
15038 return SemaRef.BuildBitIntType(IsUnsigned, Bits, Loc);
15039}
15040
15041template <typename Derived>
15042QualType TreeTransform<Derived>::RebuildDependentBitIntType(
15043 bool IsUnsigned, Expr *NumBitsExpr, SourceLocation Loc) {
15044 return SemaRef.BuildBitIntType(IsUnsigned, NumBitsExpr, Loc);
15045}
15046
15047template<typename Derived>
15048TemplateName
15049TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15050 bool TemplateKW,
15051 TemplateDecl *Template) {
15052 return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
15053 TemplateName(Template));
15054}
15055
15056template<typename Derived>
15057TemplateName
15058TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15059 SourceLocation TemplateKWLoc,
15060 const IdentifierInfo &Name,
15061 SourceLocation NameLoc,
15062 QualType ObjectType,
15063 NamedDecl *FirstQualifierInScope,
15064 bool AllowInjectedClassName) {
15065 UnqualifiedId TemplateName;
15066 TemplateName.setIdentifier(&Name, NameLoc);
15067 Sema::TemplateTy Template;
15068 getSema().ActOnTemplateName(/*Scope=*/nullptr, SS, TemplateKWLoc,
15069 TemplateName, ParsedType::make(ObjectType),
15070 /*EnteringContext=*/false, Template,
15071 AllowInjectedClassName);
15072 return Template.get();
15073}
15074
15075template<typename Derived>
15076TemplateName
15077TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15078 SourceLocation TemplateKWLoc,
15079 OverloadedOperatorKind Operator,
15080 SourceLocation NameLoc,
15081 QualType ObjectType,
15082 bool AllowInjectedClassName) {
15083 UnqualifiedId Name;
15084 // FIXME: Bogus location information.
15085 SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
15086 Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
15087 Sema::TemplateTy Template;
15088 getSema().ActOnTemplateName(
15089 /*Scope=*/nullptr, SS, TemplateKWLoc, Name, ParsedType::make(ObjectType),
15090 /*EnteringContext=*/false, Template, AllowInjectedClassName);
15091 return Template.get();
15092}
15093
15094template<typename Derived>
15095ExprResult
15096TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
15097 SourceLocation OpLoc,
15098 Expr *OrigCallee,
15099 Expr *First,
15100 Expr *Second) {
15101 Expr *Callee = OrigCallee->IgnoreParenCasts();
15102 bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
15103
15104 if (First->getObjectKind() == OK_ObjCProperty) {
15105 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15106 if (BinaryOperator::isAssignmentOp(Opc))
15107 return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
15108 First, Second);
15109 ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
15110 if (Result.isInvalid())
15111 return ExprError();
15112 First = Result.get();
15113 }
15114
15115 if (Second && Second->getObjectKind() == OK_ObjCProperty) {
15116 ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
15117 if (Result.isInvalid())
15118 return ExprError();
15119 Second = Result.get();
15120 }
15121
15122 // Determine whether this should be a builtin operation.
15123 if (Op == OO_Subscript) {
15124 if (!First->getType()->isOverloadableType() &&
15125 !Second->getType()->isOverloadableType())
15126 return getSema().CreateBuiltinArraySubscriptExpr(
15127 First, Callee->getBeginLoc(), Second, OpLoc);
15128 } else if (Op == OO_Arrow) {
15129 // It is possible that the type refers to a RecoveryExpr created earlier
15130 // in the tree transformation.
15131 if (First->getType()->isDependentType())
15132 return ExprError();
15133 // -> is never a builtin operation.
15134 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
15135 } else if (Second == nullptr || isPostIncDec) {
15136 if (!First->getType()->isOverloadableType() ||
15137 (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
15138 // The argument is not of overloadable type, or this is an expression
15139 // of the form &Class::member, so try to create a built-in unary
15140 // operation.
15141 UnaryOperatorKind Opc
15142 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
15143
15144 return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
15145 }
15146 } else {
15147 if (!First->getType()->isOverloadableType() &&
15148 !Second->getType()->isOverloadableType()) {
15149 // Neither of the arguments is an overloadable type, so try to
15150 // create a built-in binary operation.
15151 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15152 ExprResult Result
15153 = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
15154 if (Result.isInvalid())
15155 return ExprError();
15156
15157 return Result;
15158 }
15159 }
15160
15161 // Compute the transformed set of functions (and function templates) to be
15162 // used during overload resolution.
15163 UnresolvedSet<16> Functions;
15164 bool RequiresADL;
15165
15166 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
15167 Functions.append(ULE->decls_begin(), ULE->decls_end());
15168 // If the overload could not be resolved in the template definition
15169 // (because we had a dependent argument), ADL is performed as part of
15170 // template instantiation.
15171 RequiresADL = ULE->requiresADL();
15172 } else {
15173 // If we've resolved this to a particular non-member function, just call
15174 // that function. If we resolved it to a member function,
15175 // CreateOverloaded* will find that function for us.
15176 NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
15177 if (!isa<CXXMethodDecl>(ND))
15178 Functions.addDecl(ND);
15179 RequiresADL = false;
15180 }
15181
15182 // Add any functions found via argument-dependent lookup.
15183 Expr *Args[2] = { First, Second };
15184 unsigned NumArgs = 1 + (Second != nullptr);
15185
15186 // Create the overloaded operator invocation for unary operators.
15187 if (NumArgs == 1 || isPostIncDec) {
15188 UnaryOperatorKind Opc
15189 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
15190 return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
15191 RequiresADL);
15192 }
15193
15194 if (Op == OO_Subscript) {
15195 SourceLocation LBrace;
15196 SourceLocation RBrace;
15197
15198 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
15199 DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
15200 LBrace = NameLoc.getCXXOperatorNameBeginLoc();
15201 RBrace = NameLoc.getCXXOperatorNameEndLoc();
15202 } else {
15203 LBrace = Callee->getBeginLoc();
15204 RBrace = OpLoc;
15205 }
15206
15207 return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
15208 First, Second);
15209 }
15210
15211 // Create the overloaded operator invocation for binary operators.
15212 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15213 ExprResult Result = SemaRef.CreateOverloadedBinOp(
15214 OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
15215 if (Result.isInvalid())
15216 return ExprError();
15217
15218 return Result;
15219}
15220
15221template<typename Derived>
15222ExprResult
15223TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
15224 SourceLocation OperatorLoc,
15225 bool isArrow,
15226 CXXScopeSpec &SS,
15227 TypeSourceInfo *ScopeType,
15228 SourceLocation CCLoc,
15229 SourceLocation TildeLoc,
15230 PseudoDestructorTypeStorage Destroyed) {
15231 QualType BaseType = Base->getType();
15232 if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
15233 (!isArrow && !BaseType->getAs<RecordType>()) ||
15234 (isArrow && BaseType->getAs<PointerType>() &&
15235 !BaseType->castAs<PointerType>()->getPointeeType()
15236 ->template getAs<RecordType>())){
15237 // This pseudo-destructor expression is still a pseudo-destructor.
15238 return SemaRef.BuildPseudoDestructorExpr(
15239 Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
15240 CCLoc, TildeLoc, Destroyed);
15241 }
15242
15243 TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
15244 DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
15245 SemaRef.Context.getCanonicalType(DestroyedType->getType())));
15246 DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
15247 NameInfo.setNamedTypeInfo(DestroyedType);
15248
15249 // The scope type is now known to be a valid nested name specifier
15250 // component. Tack it on to the end of the nested name specifier.
15251 if (ScopeType) {
15252 if (!ScopeType->getType()->getAs<TagType>()) {
15253 getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
15254 diag::err_expected_class_or_namespace)
15255 << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
15256 return ExprError();
15257 }
15258 SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
15259 CCLoc);
15260 }
15261
15262 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
15263 return getSema().BuildMemberReferenceExpr(Base, BaseType,
15264 OperatorLoc, isArrow,
15265 SS, TemplateKWLoc,
15266 /*FIXME: FirstQualifier*/ nullptr,
15267 NameInfo,
15268 /*TemplateArgs*/ nullptr,
15269 /*S*/nullptr);
15270}
15271
15272template<typename Derived>
15273StmtResult
15274TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
15275 SourceLocation Loc = S->getBeginLoc();
15276 CapturedDecl *CD = S->getCapturedDecl();
15277 unsigned NumParams = CD->getNumParams();
15278 unsigned ContextParamPos = CD->getContextParamPosition();
15279 SmallVector<Sema::CapturedParamNameType, 4> Params;
15280 for (unsigned I = 0; I < NumParams; ++I) {
15281 if (I != ContextParamPos) {
15282 Params.push_back(
15283 std::make_pair(
15284 CD->getParam(I)->getName(),
15285 getDerived().TransformType(CD->getParam(I)->getType())));
15286 } else {
15287 Params.push_back(std::make_pair(StringRef(), QualType()));
15288 }
15289 }
15290 getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
15291 S->getCapturedRegionKind(), Params);
15292 StmtResult Body;
15293 {
15294 Sema::CompoundScopeRAII CompoundScope(getSema());
15295 Body = getDerived().TransformStmt(S->getCapturedStmt());
15296 }
15297
15298 if (Body.isInvalid()) {
15299 getSema().ActOnCapturedRegionError();
15300 return StmtError();
15301 }
15302
15303 return getSema().ActOnCapturedRegionEnd(Body.get());
15304}
15305
15306} // end namespace clang
15307
15308#endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H