Bug Summary

File:tools/clang/lib/Sema/TreeTransform.h
Warning:line 5110, column 24
Forming reference to null pointer

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateInstantiate.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -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 -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn338205/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/8/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-07-29-043837-17923-1 -x c++ /build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp -faddrsig

/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp

1//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation.
10//
11//===----------------------------------------------------------------------===/
12
13#include "clang/Sema/SemaInternal.h"
14#include "TreeTransform.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/PrettyDeclStackTrace.h"
22#include "clang/Basic/LangOptions.h"
23#include "clang/Sema/DeclSpec.h"
24#include "clang/Sema/Initialization.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/Template.h"
27#include "clang/Sema/TemplateDeduction.h"
28#include "clang/Sema/TemplateInstCallback.h"
29
30using namespace clang;
31using namespace sema;
32
33//===----------------------------------------------------------------------===/
34// Template Instantiation Support
35//===----------------------------------------------------------------------===/
36
37/// Retrieve the template argument list(s) that should be used to
38/// instantiate the definition of the given declaration.
39///
40/// \param D the declaration for which we are computing template instantiation
41/// arguments.
42///
43/// \param Innermost if non-NULL, the innermost template argument list.
44///
45/// \param RelativeToPrimary true if we should get the template
46/// arguments relative to the primary template, even when we're
47/// dealing with a specialization. This is only relevant for function
48/// template specializations.
49///
50/// \param Pattern If non-NULL, indicates the pattern from which we will be
51/// instantiating the definition of the given declaration, \p D. This is
52/// used to determine the proper set of template instantiation arguments for
53/// friend function template specializations.
54MultiLevelTemplateArgumentList
55Sema::getTemplateInstantiationArgs(NamedDecl *D,
56 const TemplateArgumentList *Innermost,
57 bool RelativeToPrimary,
58 const FunctionDecl *Pattern) {
59 // Accumulate the set of template argument lists in this structure.
60 MultiLevelTemplateArgumentList Result;
61
62 if (Innermost)
63 Result.addOuterTemplateArguments(Innermost);
64
65 DeclContext *Ctx = dyn_cast<DeclContext>(D);
66 if (!Ctx) {
67 Ctx = D->getDeclContext();
68
69 // Add template arguments from a variable template instantiation.
70 if (VarTemplateSpecializationDecl *Spec =
71 dyn_cast<VarTemplateSpecializationDecl>(D)) {
72 // We're done when we hit an explicit specialization.
73 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
74 !isa<VarTemplatePartialSpecializationDecl>(Spec))
75 return Result;
76
77 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
78
79 // If this variable template specialization was instantiated from a
80 // specialized member that is a variable template, we're done.
81 assert(Spec->getSpecializedTemplate() && "No variable template?")(static_cast <bool> (Spec->getSpecializedTemplate() &&
"No variable template?") ? void (0) : __assert_fail ("Spec->getSpecializedTemplate() && \"No variable template?\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 81, __extension__ __PRETTY_FUNCTION__))
;
82 llvm::PointerUnion<VarTemplateDecl*,
83 VarTemplatePartialSpecializationDecl*> Specialized
84 = Spec->getSpecializedTemplateOrPartial();
85 if (VarTemplatePartialSpecializationDecl *Partial =
86 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
87 if (Partial->isMemberSpecialization())
88 return Result;
89 } else {
90 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
91 if (Tmpl->isMemberSpecialization())
92 return Result;
93 }
94 }
95
96 // If we have a template template parameter with translation unit context,
97 // then we're performing substitution into a default template argument of
98 // this template template parameter before we've constructed the template
99 // that will own this template template parameter. In this case, we
100 // use empty template parameter lists for all of the outer templates
101 // to avoid performing any substitutions.
102 if (Ctx->isTranslationUnit()) {
103 if (TemplateTemplateParmDecl *TTP
104 = dyn_cast<TemplateTemplateParmDecl>(D)) {
105 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
106 Result.addOuterTemplateArguments(None);
107 return Result;
108 }
109 }
110 }
111
112 while (!Ctx->isFileContext()) {
113 // Add template arguments from a class template instantiation.
114 if (ClassTemplateSpecializationDecl *Spec
115 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
116 // We're done when we hit an explicit specialization.
117 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
118 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
119 break;
120
121 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
122
123 // If this class template specialization was instantiated from a
124 // specialized member that is a class template, we're done.
125 assert(Spec->getSpecializedTemplate() && "No class template?")(static_cast <bool> (Spec->getSpecializedTemplate() &&
"No class template?") ? void (0) : __assert_fail ("Spec->getSpecializedTemplate() && \"No class template?\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 125, __extension__ __PRETTY_FUNCTION__))
;
126 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
127 break;
128 }
129 // Add template arguments from a function template specialization.
130 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
131 if (!RelativeToPrimary &&
132 (Function->getTemplateSpecializationKind() ==
133 TSK_ExplicitSpecialization &&
134 !Function->getClassScopeSpecializationPattern()))
135 break;
136
137 if (const TemplateArgumentList *TemplateArgs
138 = Function->getTemplateSpecializationArgs()) {
139 // Add the template arguments for this specialization.
140 Result.addOuterTemplateArguments(TemplateArgs);
141
142 // If this function was instantiated from a specialized member that is
143 // a function template, we're done.
144 assert(Function->getPrimaryTemplate() && "No function template?")(static_cast <bool> (Function->getPrimaryTemplate() &&
"No function template?") ? void (0) : __assert_fail ("Function->getPrimaryTemplate() && \"No function template?\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 144, __extension__ __PRETTY_FUNCTION__))
;
145 if (Function->getPrimaryTemplate()->isMemberSpecialization())
146 break;
147
148 // If this function is a generic lambda specialization, we are done.
149 if (isGenericLambdaCallOperatorSpecialization(Function))
150 break;
151
152 } else if (FunctionTemplateDecl *FunTmpl
153 = Function->getDescribedFunctionTemplate()) {
154 // Add the "injected" template arguments.
155 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
156 }
157
158 // If this is a friend declaration and it declares an entity at
159 // namespace scope, take arguments from its lexical parent
160 // instead of its semantic parent, unless of course the pattern we're
161 // instantiating actually comes from the file's context!
162 if (Function->getFriendObjectKind() &&
163 Function->getDeclContext()->isFileContext() &&
164 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
165 Ctx = Function->getLexicalDeclContext();
166 RelativeToPrimary = false;
167 continue;
168 }
169 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
170 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
171 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
172 const TemplateSpecializationType *TST =
173 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
174 Result.addOuterTemplateArguments(
175 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
176 if (ClassTemplate->isMemberSpecialization())
177 break;
178 }
179 }
180
181 Ctx = Ctx->getParent();
182 RelativeToPrimary = false;
183 }
184
185 return Result;
186}
187
188bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
189 switch (Kind) {
190 case TemplateInstantiation:
191 case ExceptionSpecInstantiation:
192 case DefaultTemplateArgumentInstantiation:
193 case DefaultFunctionArgumentInstantiation:
194 case ExplicitTemplateArgumentSubstitution:
195 case DeducedTemplateArgumentSubstitution:
196 case PriorTemplateArgumentSubstitution:
197 return true;
198
199 case DefaultTemplateArgumentChecking:
200 case DeclaringSpecialMember:
201 case DefiningSynthesizedFunction:
202 return false;
203
204 // This function should never be called when Kind's value is Memoization.
205 case Memoization:
206 break;
207 }
208
209 llvm_unreachable("Invalid SynthesisKind!")::llvm::llvm_unreachable_internal("Invalid SynthesisKind!", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 209)
;
210}
211
212Sema::InstantiatingTemplate::InstantiatingTemplate(
213 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
214 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
215 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
216 sema::TemplateDeductionInfo *DeductionInfo)
217 : SemaRef(SemaRef) {
218 // Don't allow further instantiation if a fatal error and an uncompilable
219 // error have occurred. Any diagnostics we might have raised will not be
220 // visible, and we do not need to construct a correct AST.
221 if (SemaRef.Diags.hasFatalErrorOccurred() &&
222 SemaRef.Diags.hasUncompilableErrorOccurred()) {
223 Invalid = true;
224 return;
225 }
226 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
227 if (!Invalid) {
228 CodeSynthesisContext Inst;
229 Inst.Kind = Kind;
230 Inst.PointOfInstantiation = PointOfInstantiation;
231 Inst.Entity = Entity;
232 Inst.Template = Template;
233 Inst.TemplateArgs = TemplateArgs.data();
234 Inst.NumTemplateArgs = TemplateArgs.size();
235 Inst.DeductionInfo = DeductionInfo;
236 Inst.InstantiationRange = InstantiationRange;
237 SemaRef.pushCodeSynthesisContext(Inst);
238
239 AlreadyInstantiating =
240 !SemaRef.InstantiatingSpecializations
241 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
242 .second;
243 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
244 }
245}
246
247Sema::InstantiatingTemplate::InstantiatingTemplate(
248 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
249 SourceRange InstantiationRange)
250 : InstantiatingTemplate(SemaRef,
251 CodeSynthesisContext::TemplateInstantiation,
252 PointOfInstantiation, InstantiationRange, Entity) {}
253
254Sema::InstantiatingTemplate::InstantiatingTemplate(
255 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
256 ExceptionSpecification, SourceRange InstantiationRange)
257 : InstantiatingTemplate(
258 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
259 PointOfInstantiation, InstantiationRange, Entity) {}
260
261Sema::InstantiatingTemplate::InstantiatingTemplate(
262 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
263 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
264 SourceRange InstantiationRange)
265 : InstantiatingTemplate(
266 SemaRef,
267 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
268 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
269 Template, TemplateArgs) {}
270
271Sema::InstantiatingTemplate::InstantiatingTemplate(
272 Sema &SemaRef, SourceLocation PointOfInstantiation,
273 FunctionTemplateDecl *FunctionTemplate,
274 ArrayRef<TemplateArgument> TemplateArgs,
275 CodeSynthesisContext::SynthesisKind Kind,
276 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
277 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
278 InstantiationRange, FunctionTemplate, nullptr,
279 TemplateArgs, &DeductionInfo) {
280 assert((static_cast <bool> (Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? void (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 282, __extension__ __PRETTY_FUNCTION__))
281 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||(static_cast <bool> (Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? void (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 282, __extension__ __PRETTY_FUNCTION__))
282 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution)(static_cast <bool> (Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? void (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 282, __extension__ __PRETTY_FUNCTION__))
;
283}
284
285Sema::InstantiatingTemplate::InstantiatingTemplate(
286 Sema &SemaRef, SourceLocation PointOfInstantiation,
287 TemplateDecl *Template,
288 ArrayRef<TemplateArgument> TemplateArgs,
289 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
290 : InstantiatingTemplate(
291 SemaRef,
292 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
293 PointOfInstantiation, InstantiationRange, Template, nullptr,
294 TemplateArgs, &DeductionInfo) {}
295
296Sema::InstantiatingTemplate::InstantiatingTemplate(
297 Sema &SemaRef, SourceLocation PointOfInstantiation,
298 ClassTemplatePartialSpecializationDecl *PartialSpec,
299 ArrayRef<TemplateArgument> TemplateArgs,
300 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
301 : InstantiatingTemplate(
302 SemaRef,
303 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
304 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
305 TemplateArgs, &DeductionInfo) {}
306
307Sema::InstantiatingTemplate::InstantiatingTemplate(
308 Sema &SemaRef, SourceLocation PointOfInstantiation,
309 VarTemplatePartialSpecializationDecl *PartialSpec,
310 ArrayRef<TemplateArgument> TemplateArgs,
311 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
312 : InstantiatingTemplate(
313 SemaRef,
314 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
315 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
316 TemplateArgs, &DeductionInfo) {}
317
318Sema::InstantiatingTemplate::InstantiatingTemplate(
319 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
320 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
321 : InstantiatingTemplate(
322 SemaRef,
323 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
324 PointOfInstantiation, InstantiationRange, Param, nullptr,
325 TemplateArgs) {}
326
327Sema::InstantiatingTemplate::InstantiatingTemplate(
328 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
329 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
330 SourceRange InstantiationRange)
331 : InstantiatingTemplate(
332 SemaRef,
333 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
334 PointOfInstantiation, InstantiationRange, Param, Template,
335 TemplateArgs) {}
336
337Sema::InstantiatingTemplate::InstantiatingTemplate(
338 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
339 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
340 SourceRange InstantiationRange)
341 : InstantiatingTemplate(
342 SemaRef,
343 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
344 PointOfInstantiation, InstantiationRange, Param, Template,
345 TemplateArgs) {}
346
347Sema::InstantiatingTemplate::InstantiatingTemplate(
348 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
349 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
350 SourceRange InstantiationRange)
351 : InstantiatingTemplate(
352 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
353 PointOfInstantiation, InstantiationRange, Param, Template,
354 TemplateArgs) {}
355
356void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
357 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
358 InNonInstantiationSFINAEContext = false;
359
360 CodeSynthesisContexts.push_back(Ctx);
361
362 if (!Ctx.isInstantiationRecord())
363 ++NonInstantiationEntries;
364}
365
366void Sema::popCodeSynthesisContext() {
367 auto &Active = CodeSynthesisContexts.back();
368 if (!Active.isInstantiationRecord()) {
369 assert(NonInstantiationEntries > 0)(static_cast <bool> (NonInstantiationEntries > 0) ? void
(0) : __assert_fail ("NonInstantiationEntries > 0", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 369, __extension__ __PRETTY_FUNCTION__))
;
370 --NonInstantiationEntries;
371 }
372
373 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
374
375 // Name lookup no longer looks in this template's defining module.
376 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 378, __extension__ __PRETTY_FUNCTION__))
377 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 378, __extension__ __PRETTY_FUNCTION__))
378 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 378, __extension__ __PRETTY_FUNCTION__))
;
379 if (CodeSynthesisContexts.size() ==
380 CodeSynthesisContextLookupModules.size()) {
381 if (Module *M = CodeSynthesisContextLookupModules.back())
382 LookupModulesCache.erase(M);
383 CodeSynthesisContextLookupModules.pop_back();
384 }
385
386 // If we've left the code synthesis context for the current context stack,
387 // stop remembering that we've emitted that stack.
388 if (CodeSynthesisContexts.size() ==
389 LastEmittedCodeSynthesisContextDepth)
390 LastEmittedCodeSynthesisContextDepth = 0;
391
392 CodeSynthesisContexts.pop_back();
393}
394
395void Sema::InstantiatingTemplate::Clear() {
396 if (!Invalid) {
397 if (!AlreadyInstantiating) {
398 auto &Active = SemaRef.CodeSynthesisContexts.back();
399 SemaRef.InstantiatingSpecializations.erase(
400 std::make_pair(Active.Entity, Active.Kind));
401 }
402
403 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
404 SemaRef.CodeSynthesisContexts.back());
405
406 SemaRef.popCodeSynthesisContext();
407 Invalid = true;
408 }
409}
410
411bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
412 SourceLocation PointOfInstantiation,
413 SourceRange InstantiationRange) {
414 assert(SemaRef.NonInstantiationEntries <=(static_cast <bool> (SemaRef.NonInstantiationEntries <=
SemaRef.CodeSynthesisContexts.size()) ? void (0) : __assert_fail
("SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 415, __extension__ __PRETTY_FUNCTION__))
415 SemaRef.CodeSynthesisContexts.size())(static_cast <bool> (SemaRef.NonInstantiationEntries <=
SemaRef.CodeSynthesisContexts.size()) ? void (0) : __assert_fail
("SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 415, __extension__ __PRETTY_FUNCTION__))
;
416 if ((SemaRef.CodeSynthesisContexts.size() -
417 SemaRef.NonInstantiationEntries)
418 <= SemaRef.getLangOpts().InstantiationDepth)
419 return false;
420
421 SemaRef.Diag(PointOfInstantiation,
422 diag::err_template_recursion_depth_exceeded)
423 << SemaRef.getLangOpts().InstantiationDepth
424 << InstantiationRange;
425 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
426 << SemaRef.getLangOpts().InstantiationDepth;
427 return true;
428}
429
430/// Prints the current instantiation stack through a series of
431/// notes.
432void Sema::PrintInstantiationStack() {
433 // Determine which template instantiations to skip, if any.
434 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
435 unsigned Limit = Diags.getTemplateBacktraceLimit();
436 if (Limit && Limit < CodeSynthesisContexts.size()) {
437 SkipStart = Limit / 2 + Limit % 2;
438 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
439 }
440
441 // FIXME: In all of these cases, we need to show the template arguments
442 unsigned InstantiationIdx = 0;
443 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
444 Active = CodeSynthesisContexts.rbegin(),
445 ActiveEnd = CodeSynthesisContexts.rend();
446 Active != ActiveEnd;
447 ++Active, ++InstantiationIdx) {
448 // Skip this instantiation?
449 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
450 if (InstantiationIdx == SkipStart) {
451 // Note that we're skipping instantiations.
452 Diags.Report(Active->PointOfInstantiation,
453 diag::note_instantiation_contexts_suppressed)
454 << unsigned(CodeSynthesisContexts.size() - Limit);
455 }
456 continue;
457 }
458
459 switch (Active->Kind) {
460 case CodeSynthesisContext::TemplateInstantiation: {
461 Decl *D = Active->Entity;
462 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
463 unsigned DiagID = diag::note_template_member_class_here;
464 if (isa<ClassTemplateSpecializationDecl>(Record))
465 DiagID = diag::note_template_class_instantiation_here;
466 Diags.Report(Active->PointOfInstantiation, DiagID)
467 << Record << Active->InstantiationRange;
468 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
469 unsigned DiagID;
470 if (Function->getPrimaryTemplate())
471 DiagID = diag::note_function_template_spec_here;
472 else
473 DiagID = diag::note_template_member_function_here;
474 Diags.Report(Active->PointOfInstantiation, DiagID)
475 << Function
476 << Active->InstantiationRange;
477 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
478 Diags.Report(Active->PointOfInstantiation,
479 VD->isStaticDataMember()?
480 diag::note_template_static_data_member_def_here
481 : diag::note_template_variable_def_here)
482 << VD
483 << Active->InstantiationRange;
484 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
485 Diags.Report(Active->PointOfInstantiation,
486 diag::note_template_enum_def_here)
487 << ED
488 << Active->InstantiationRange;
489 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
490 Diags.Report(Active->PointOfInstantiation,
491 diag::note_template_nsdmi_here)
492 << FD << Active->InstantiationRange;
493 } else {
494 Diags.Report(Active->PointOfInstantiation,
495 diag::note_template_type_alias_instantiation_here)
496 << cast<TypeAliasTemplateDecl>(D)
497 << Active->InstantiationRange;
498 }
499 break;
500 }
501
502 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
503 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
504 SmallVector<char, 128> TemplateArgsStr;
505 llvm::raw_svector_ostream OS(TemplateArgsStr);
506 Template->printName(OS);
507 printTemplateArgumentList(OS, Active->template_arguments(),
508 getPrintingPolicy());
509 Diags.Report(Active->PointOfInstantiation,
510 diag::note_default_arg_instantiation_here)
511 << OS.str()
512 << Active->InstantiationRange;
513 break;
514 }
515
516 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
517 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
518 Diags.Report(Active->PointOfInstantiation,
519 diag::note_explicit_template_arg_substitution_here)
520 << FnTmpl
521 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
522 Active->TemplateArgs,
523 Active->NumTemplateArgs)
524 << Active->InstantiationRange;
525 break;
526 }
527
528 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
529 if (FunctionTemplateDecl *FnTmpl =
530 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
531 Diags.Report(Active->PointOfInstantiation,
532 diag::note_function_template_deduction_instantiation_here)
533 << FnTmpl
534 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
535 Active->TemplateArgs,
536 Active->NumTemplateArgs)
537 << Active->InstantiationRange;
538 } else {
539 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
540 isa<VarTemplateSpecializationDecl>(Active->Entity);
541 bool IsTemplate = false;
542 TemplateParameterList *Params;
543 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
544 IsTemplate = true;
545 Params = D->getTemplateParameters();
546 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
547 Active->Entity)) {
548 Params = D->getTemplateParameters();
549 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
550 Active->Entity)) {
551 Params = D->getTemplateParameters();
552 } else {
553 llvm_unreachable("unexpected template kind")::llvm::llvm_unreachable_internal("unexpected template kind",
"/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 553)
;
554 }
555
556 Diags.Report(Active->PointOfInstantiation,
557 diag::note_deduced_template_arg_substitution_here)
558 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
559 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
560 Active->NumTemplateArgs)
561 << Active->InstantiationRange;
562 }
563 break;
564 }
565
566 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
567 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
568 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
569
570 SmallVector<char, 128> TemplateArgsStr;
571 llvm::raw_svector_ostream OS(TemplateArgsStr);
572 FD->printName(OS);
573 printTemplateArgumentList(OS, Active->template_arguments(),
574 getPrintingPolicy());
575 Diags.Report(Active->PointOfInstantiation,
576 diag::note_default_function_arg_instantiation_here)
577 << OS.str()
578 << Active->InstantiationRange;
579 break;
580 }
581
582 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
583 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
584 std::string Name;
585 if (!Parm->getName().empty())
586 Name = std::string(" '") + Parm->getName().str() + "'";
587
588 TemplateParameterList *TemplateParams = nullptr;
589 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
590 TemplateParams = Template->getTemplateParameters();
591 else
592 TemplateParams =
593 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
594 ->getTemplateParameters();
595 Diags.Report(Active->PointOfInstantiation,
596 diag::note_prior_template_arg_substitution)
597 << isa<TemplateTemplateParmDecl>(Parm)
598 << Name
599 << getTemplateArgumentBindingsText(TemplateParams,
600 Active->TemplateArgs,
601 Active->NumTemplateArgs)
602 << Active->InstantiationRange;
603 break;
604 }
605
606 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
607 TemplateParameterList *TemplateParams = nullptr;
608 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
609 TemplateParams = Template->getTemplateParameters();
610 else
611 TemplateParams =
612 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
613 ->getTemplateParameters();
614
615 Diags.Report(Active->PointOfInstantiation,
616 diag::note_template_default_arg_checking)
617 << getTemplateArgumentBindingsText(TemplateParams,
618 Active->TemplateArgs,
619 Active->NumTemplateArgs)
620 << Active->InstantiationRange;
621 break;
622 }
623
624 case CodeSynthesisContext::ExceptionSpecInstantiation:
625 Diags.Report(Active->PointOfInstantiation,
626 diag::note_template_exception_spec_instantiation_here)
627 << cast<FunctionDecl>(Active->Entity)
628 << Active->InstantiationRange;
629 break;
630
631 case CodeSynthesisContext::DeclaringSpecialMember:
632 Diags.Report(Active->PointOfInstantiation,
633 diag::note_in_declaration_of_implicit_special_member)
634 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
635 break;
636
637 case CodeSynthesisContext::DefiningSynthesizedFunction: {
638 // FIXME: For synthesized members other than special members, produce a note.
639 auto *MD = dyn_cast<CXXMethodDecl>(Active->Entity);
640 auto CSM = MD ? getSpecialMember(MD) : CXXInvalid;
641 if (CSM != CXXInvalid) {
642 Diags.Report(Active->PointOfInstantiation,
643 diag::note_member_synthesized_at)
644 << CSM << Context.getTagDeclType(MD->getParent());
645 }
646 break;
647 }
648
649 case CodeSynthesisContext::Memoization:
650 break;
651 }
652 }
653}
654
655Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
656 if (InNonInstantiationSFINAEContext)
657 return Optional<TemplateDeductionInfo *>(nullptr);
658
659 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
660 Active = CodeSynthesisContexts.rbegin(),
661 ActiveEnd = CodeSynthesisContexts.rend();
662 Active != ActiveEnd;
663 ++Active)
664 {
665 switch (Active->Kind) {
666 case CodeSynthesisContext::TemplateInstantiation:
667 // An instantiation of an alias template may or may not be a SFINAE
668 // context, depending on what else is on the stack.
669 if (isa<TypeAliasTemplateDecl>(Active->Entity))
670 break;
671 // Fall through.
672 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
673 case CodeSynthesisContext::ExceptionSpecInstantiation:
674 // This is a template instantiation, so there is no SFINAE.
675 return None;
676
677 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
678 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
679 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
680 // A default template argument instantiation and substitution into
681 // template parameters with arguments for prior parameters may or may
682 // not be a SFINAE context; look further up the stack.
683 break;
684
685 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
686 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
687 // We're either substitution explicitly-specified template arguments
688 // or deduced template arguments, so SFINAE applies.
689 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 689, __extension__ __PRETTY_FUNCTION__))
;
690 return Active->DeductionInfo;
691
692 case CodeSynthesisContext::DeclaringSpecialMember:
693 case CodeSynthesisContext::DefiningSynthesizedFunction:
694 // This happens in a context unrelated to template instantiation, so
695 // there is no SFINAE.
696 return None;
697
698 case CodeSynthesisContext::Memoization:
699 break;
700 }
701
702 // The inner context was transparent for SFINAE. If it occurred within a
703 // non-instantiation SFINAE context, then SFINAE applies.
704 if (Active->SavedInNonInstantiationSFINAEContext)
705 return Optional<TemplateDeductionInfo *>(nullptr);
706 }
707
708 return None;
709}
710
711//===----------------------------------------------------------------------===/
712// Template Instantiation for Types
713//===----------------------------------------------------------------------===/
714namespace {
715 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
716 const MultiLevelTemplateArgumentList &TemplateArgs;
717 SourceLocation Loc;
718 DeclarationName Entity;
719
720 public:
721 typedef TreeTransform<TemplateInstantiator> inherited;
722
723 TemplateInstantiator(Sema &SemaRef,
724 const MultiLevelTemplateArgumentList &TemplateArgs,
725 SourceLocation Loc,
726 DeclarationName Entity)
727 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
728 Entity(Entity) { }
729
730 /// Determine whether the given type \p T has already been
731 /// transformed.
732 ///
733 /// For the purposes of template instantiation, a type has already been
734 /// transformed if it is NULL or if it is not dependent.
735 bool AlreadyTransformed(QualType T);
736
737 /// Returns the location of the entity being instantiated, if known.
738 SourceLocation getBaseLocation() { return Loc; }
739
740 /// Returns the name of the entity being instantiated, if any.
741 DeclarationName getBaseEntity() { return Entity; }
742
743 /// Sets the "base" location and entity when that
744 /// information is known based on another transformation.
745 void setBase(SourceLocation Loc, DeclarationName Entity) {
746 this->Loc = Loc;
747 this->Entity = Entity;
748 }
749
750 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
751 SourceRange PatternRange,
752 ArrayRef<UnexpandedParameterPack> Unexpanded,
753 bool &ShouldExpand, bool &RetainExpansion,
754 Optional<unsigned> &NumExpansions) {
755 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
756 PatternRange, Unexpanded,
757 TemplateArgs,
758 ShouldExpand,
759 RetainExpansion,
760 NumExpansions);
761 }
762
763 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
764 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
765 }
766
767 TemplateArgument ForgetPartiallySubstitutedPack() {
768 TemplateArgument Result;
769 if (NamedDecl *PartialPack
770 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
771 MultiLevelTemplateArgumentList &TemplateArgs
772 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
773 unsigned Depth, Index;
774 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
775 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
776 Result = TemplateArgs(Depth, Index);
777 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
778 }
779 }
780
781 return Result;
782 }
783
784 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
785 if (Arg.isNull())
786 return;
787
788 if (NamedDecl *PartialPack
789 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
790 MultiLevelTemplateArgumentList &TemplateArgs
791 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
792 unsigned Depth, Index;
793 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
794 TemplateArgs.setArgument(Depth, Index, Arg);
795 }
796 }
797
798 /// Transform the given declaration by instantiating a reference to
799 /// this declaration.
800 Decl *TransformDecl(SourceLocation Loc, Decl *D);
801
802 void transformAttrs(Decl *Old, Decl *New) {
803 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
804 }
805
806 void transformedLocalDecl(Decl *Old, Decl *New) {
807 // If we've instantiated the call operator of a lambda or the call
808 // operator template of a generic lambda, update the "instantiation of"
809 // information.
810 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
811 if (NewMD && isLambdaCallOperator(NewMD)) {
812 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
813 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
814 NewTD->setInstantiatedFromMemberTemplate(
815 OldMD->getDescribedFunctionTemplate());
816 else
817 NewMD->setInstantiationOfMemberFunction(OldMD,
818 TSK_ImplicitInstantiation);
819 }
820
821 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
822
823 // We recreated a local declaration, but not by instantiating it. There
824 // may be pending dependent diagnostics to produce.
825 if (auto *DC = dyn_cast<DeclContext>(Old))
826 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
827 }
828
829 /// Transform the definition of the given declaration by
830 /// instantiating it.
831 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
832
833 /// Transform the first qualifier within a scope by instantiating the
834 /// declaration.
835 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
836
837 /// Rebuild the exception declaration and register the declaration
838 /// as an instantiated local.
839 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
840 TypeSourceInfo *Declarator,
841 SourceLocation StartLoc,
842 SourceLocation NameLoc,
843 IdentifierInfo *Name);
844
845 /// Rebuild the Objective-C exception declaration and register the
846 /// declaration as an instantiated local.
847 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
848 TypeSourceInfo *TSInfo, QualType T);
849
850 /// Check for tag mismatches when instantiating an
851 /// elaborated type.
852 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
853 ElaboratedTypeKeyword Keyword,
854 NestedNameSpecifierLoc QualifierLoc,
855 QualType T);
856
857 TemplateName
858 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
859 SourceLocation NameLoc,
860 QualType ObjectType = QualType(),
861 NamedDecl *FirstQualifierInScope = nullptr,
862 bool AllowInjectedClassName = false);
863
864 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
865
866 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
867 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
868 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
869
870 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
871 NonTypeTemplateParmDecl *D);
872 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
873 SubstNonTypeTemplateParmPackExpr *E);
874
875 /// Rebuild a DeclRefExpr for a ParmVarDecl reference.
876 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
877
878 /// Transform a reference to a function parameter pack.
879 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
880 ParmVarDecl *PD);
881
882 /// Transform a FunctionParmPackExpr which was built when we couldn't
883 /// expand a function parameter pack reference which refers to an expanded
884 /// pack.
885 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
886
887 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
888 FunctionProtoTypeLoc TL) {
889 // Call the base version; it will forward to our overridden version below.
890 return inherited::TransformFunctionProtoType(TLB, TL);
891 }
892
893 template<typename Fn>
894 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
895 FunctionProtoTypeLoc TL,
896 CXXRecordDecl *ThisContext,
897 unsigned ThisTypeQuals,
898 Fn TransformExceptionSpec);
899
900 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
901 int indexAdjustment,
902 Optional<unsigned> NumExpansions,
903 bool ExpectParameterPack);
904
905 /// Transforms a template type parameter type by performing
906 /// substitution of the corresponding template type argument.
907 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
908 TemplateTypeParmTypeLoc TL);
909
910 /// Transforms an already-substituted template type parameter pack
911 /// into either itself (if we aren't substituting into its pack expansion)
912 /// or the appropriate substituted argument.
913 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
914 SubstTemplateTypeParmPackTypeLoc TL);
915
916 ExprResult TransformLambdaExpr(LambdaExpr *E) {
917 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
918 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
919 }
920
921 TemplateParameterList *TransformTemplateParameterList(
922 TemplateParameterList *OrigTPL) {
923 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
924
925 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
926 TemplateDeclInstantiator DeclInstantiator(getSema(),
927 /* DeclContext *Owner */ Owner, TemplateArgs);
928 return DeclInstantiator.SubstTemplateParams(OrigTPL);
929 }
930 private:
931 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
932 SourceLocation loc,
933 TemplateArgument arg);
934 };
935}
936
937bool TemplateInstantiator::AlreadyTransformed(QualType T) {
938 if (T.isNull())
939 return true;
940
941 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
942 return false;
943
944 getSema().MarkDeclarationsReferencedInType(Loc, T);
945 return true;
946}
947
948static TemplateArgument
949getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
950 assert(S.ArgumentPackSubstitutionIndex >= 0)(static_cast <bool> (S.ArgumentPackSubstitutionIndex >=
0) ? void (0) : __assert_fail ("S.ArgumentPackSubstitutionIndex >= 0"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 950, __extension__ __PRETTY_FUNCTION__))
;
951 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()"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 951, __extension__ __PRETTY_FUNCTION__))
;
952 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
953 if (Arg.isPackExpansion())
954 Arg = Arg.getPackExpansionPattern();
955 return Arg;
956}
957
958Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
959 if (!D)
960 return nullptr;
961
962 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
963 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
964 // If the corresponding template argument is NULL or non-existent, it's
965 // because we are performing instantiation from explicitly-specified
966 // template arguments in a function template, but there were some
967 // arguments left unspecified.
968 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
969 TTP->getPosition()))
970 return D;
971
972 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
973
974 if (TTP->isParameterPack()) {
975 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 976, __extension__ __PRETTY_FUNCTION__))
976 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 976, __extension__ __PRETTY_FUNCTION__))
;
977 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
978 }
979
980 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
981 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 982, __extension__ __PRETTY_FUNCTION__))
982 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 982, __extension__ __PRETTY_FUNCTION__))
;
983 return Template.getAsTemplateDecl();
984 }
985
986 // Fall through to find the instantiated declaration for this template
987 // template parameter.
988 }
989
990 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
991}
992
993Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
994 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
995 if (!Inst)
996 return nullptr;
997
998 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
999 return Inst;
1000}
1001
1002NamedDecl *
1003TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1004 SourceLocation Loc) {
1005 // If the first part of the nested-name-specifier was a template type
1006 // parameter, instantiate that type parameter down to a tag type.
1007 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1008 const TemplateTypeParmType *TTP
1009 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1010
1011 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1012 // FIXME: This needs testing w/ member access expressions.
1013 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1014
1015 if (TTP->isParameterPack()) {
1016 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1017, __extension__ __PRETTY_FUNCTION__))
1017 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1017, __extension__ __PRETTY_FUNCTION__))
;
1018
1019 if (getSema().ArgumentPackSubstitutionIndex == -1)
1020 return nullptr;
1021
1022 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1023 }
1024
1025 QualType T = Arg.getAsType();
1026 if (T.isNull())
1027 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1028
1029 if (const TagType *Tag = T->getAs<TagType>())
1030 return Tag->getDecl();
1031
1032 // The resulting type is not a tag; complain.
1033 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1034 return nullptr;
1035 }
1036 }
1037
1038 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1039}
1040
1041VarDecl *
1042TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1043 TypeSourceInfo *Declarator,
1044 SourceLocation StartLoc,
1045 SourceLocation NameLoc,
1046 IdentifierInfo *Name) {
1047 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1048 StartLoc, NameLoc, Name);
1049 if (Var)
1050 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1051 return Var;
1052}
1053
1054VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1055 TypeSourceInfo *TSInfo,
1056 QualType T) {
1057 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1058 if (Var)
1059 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1060 return Var;
1061}
1062
1063QualType
1064TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1065 ElaboratedTypeKeyword Keyword,
1066 NestedNameSpecifierLoc QualifierLoc,
1067 QualType T) {
1068 if (const TagType *TT = T->getAs<TagType>()) {
1069 TagDecl* TD = TT->getDecl();
1070
1071 SourceLocation TagLocation = KeywordLoc;
1072
1073 IdentifierInfo *Id = TD->getIdentifier();
1074
1075 // TODO: should we even warn on struct/class mismatches for this? Seems
1076 // like it's likely to produce a lot of spurious errors.
1077 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1078 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1079 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1080 TagLocation, Id)) {
1081 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1082 << Id
1083 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1084 TD->getKindName());
1085 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1086 }
1087 }
1088 }
1089
1090 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1091 Keyword,
1092 QualifierLoc,
1093 T);
1094}
1095
1096TemplateName TemplateInstantiator::TransformTemplateName(
1097 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1098 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1099 bool AllowInjectedClassName) {
1100 if (TemplateTemplateParmDecl *TTP
1101 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1102 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1103 // If the corresponding template argument is NULL or non-existent, it's
1104 // because we are performing instantiation from explicitly-specified
1105 // template arguments in a function template, but there were some
1106 // arguments left unspecified.
1107 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1108 TTP->getPosition()))
1109 return Name;
1110
1111 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1112
1113 if (TTP->isParameterPack()) {
1114 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1115, __extension__ __PRETTY_FUNCTION__))
1115 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1115, __extension__ __PRETTY_FUNCTION__))
;
1116
1117 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1118 // We have the template argument pack to substitute, but we're not
1119 // actually expanding the enclosing pack expansion yet. So, just
1120 // keep the entire argument pack.
1121 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1122 }
1123
1124 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1125 }
1126
1127 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1128 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1128, __extension__ __PRETTY_FUNCTION__))
;
1129 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?\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1130, __extension__ __PRETTY_FUNCTION__))
1130 "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?\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1130, __extension__ __PRETTY_FUNCTION__))
;
1131
1132 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1133 return Template;
1134 }
1135 }
1136
1137 if (SubstTemplateTemplateParmPackStorage *SubstPack
1138 = Name.getAsSubstTemplateTemplateParmPack()) {
1139 if (getSema().ArgumentPackSubstitutionIndex == -1)
1140 return Name;
1141
1142 TemplateArgument Arg = SubstPack->getArgumentPack();
1143 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1144 return Arg.getAsTemplate().getNameToSubstitute();
1145 }
1146
1147 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1148 FirstQualifierInScope,
1149 AllowInjectedClassName);
1150}
1151
1152ExprResult
1153TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1154 if (!E->isTypeDependent())
1155 return E;
1156
1157 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
1158}
1159
1160ExprResult
1161TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1162 NonTypeTemplateParmDecl *NTTP) {
1163 // If the corresponding template argument is NULL or non-existent, it's
1164 // because we are performing instantiation from explicitly-specified
1165 // template arguments in a function template, but there were some
1166 // arguments left unspecified.
1167 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1168 NTTP->getPosition()))
1169 return E;
1170
1171 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1172
1173 if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1174 // We're performing a partial substitution, so the substituted argument
1175 // could be dependent. As a result we can't create a SubstNonType*Expr
1176 // node now, since that represents a fully-substituted argument.
1177 // FIXME: We should have some AST representation for this.
1178 if (Arg.getKind() == TemplateArgument::Pack) {
1179 // FIXME: This won't work for alias templates.
1180 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&(static_cast <bool> (Arg.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() && "unexpected pack arguments in partial substitution"
) ? void (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in partial substitution\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1181, __extension__ __PRETTY_FUNCTION__))
1181 "unexpected pack arguments in partial substitution")(static_cast <bool> (Arg.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() && "unexpected pack arguments in partial substitution"
) ? void (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in partial substitution\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1181, __extension__ __PRETTY_FUNCTION__))
;
1182 Arg = Arg.pack_begin()->getPackExpansionPattern();
1183 }
1184 assert(Arg.getKind() == TemplateArgument::Expression &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Expression && "unexpected nontype template argument kind in partial substitution"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Expression && \"unexpected nontype template argument kind in partial substitution\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1185, __extension__ __PRETTY_FUNCTION__))
1185 "unexpected nontype template argument kind in partial substitution")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Expression && "unexpected nontype template argument kind in partial substitution"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Expression && \"unexpected nontype template argument kind in partial substitution\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1185, __extension__ __PRETTY_FUNCTION__))
;
1186 return Arg.getAsExpr();
1187 }
1188
1189 if (NTTP->isParameterPack()) {
1190 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1191, __extension__ __PRETTY_FUNCTION__))
1191 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1191, __extension__ __PRETTY_FUNCTION__))
;
1192
1193 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1194 // We have an argument pack, but we can't select a particular argument
1195 // out of it yet. Therefore, we'll build an expression to hold on to that
1196 // argument pack.
1197 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1198 E->getLocation(),
1199 NTTP->getDeclName());
1200 if (TargetType.isNull())
1201 return ExprError();
1202
1203 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1204 TargetType.getNonLValueExprType(SemaRef.Context),
1205 TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP,
1206 E->getLocation(), Arg);
1207 }
1208
1209 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1210 }
1211
1212 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1213}
1214
1215const LoopHintAttr *
1216TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1217 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1218
1219 if (TransformedExpr == LH->getValue())
1220 return LH;
1221
1222 // Generate error if there is a problem with the value.
1223 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1224 return LH;
1225
1226 // Create new LoopHintValueAttr with integral expression in place of the
1227 // non-type template parameter.
1228 return LoopHintAttr::CreateImplicit(
1229 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1230 LH->getState(), TransformedExpr, LH->getRange());
1231}
1232
1233ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1234 NonTypeTemplateParmDecl *parm,
1235 SourceLocation loc,
1236 TemplateArgument arg) {
1237 ExprResult result;
1238 QualType type;
1239
1240 // The template argument itself might be an expression, in which
1241 // case we just return that expression.
1242 if (arg.getKind() == TemplateArgument::Expression) {
1243 Expr *argExpr = arg.getAsExpr();
1244 result = argExpr;
1245 type = argExpr->getType();
1246
1247 } else if (arg.getKind() == TemplateArgument::Declaration ||
1248 arg.getKind() == TemplateArgument::NullPtr) {
1249 ValueDecl *VD;
1250 if (arg.getKind() == TemplateArgument::Declaration) {
1251 VD = arg.getAsDecl();
1252
1253 // Find the instantiation of the template argument. This is
1254 // required for nested templates.
1255 VD = cast_or_null<ValueDecl>(
1256 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1257 if (!VD)
1258 return ExprError();
1259 } else {
1260 // Propagate NULL template argument.
1261 VD = nullptr;
1262 }
1263
1264 // Derive the type we want the substituted decl to have. This had
1265 // better be non-dependent, or these checks will have serious problems.
1266 if (parm->isExpandedParameterPack()) {
1267 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1268 } else if (parm->isParameterPack() &&
1269 isa<PackExpansionType>(parm->getType())) {
1270 type = SemaRef.SubstType(
1271 cast<PackExpansionType>(parm->getType())->getPattern(),
1272 TemplateArgs, loc, parm->getDeclName());
1273 } else {
1274 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1275 TemplateArgs, loc, parm->getDeclName());
1276 }
1277 assert(!type.isNull() && "type substitution failed for param type")(static_cast <bool> (!type.isNull() && "type substitution failed for param type"
) ? void (0) : __assert_fail ("!type.isNull() && \"type substitution failed for param type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1277, __extension__ __PRETTY_FUNCTION__))
;
1278 assert(!type->isDependentType() && "param type still dependent")(static_cast <bool> (!type->isDependentType() &&
"param type still dependent") ? void (0) : __assert_fail ("!type->isDependentType() && \"param type still dependent\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1278, __extension__ __PRETTY_FUNCTION__))
;
1279 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1280
1281 if (!result.isInvalid()) type = result.get()->getType();
1282 } else {
1283 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1284
1285 // Note that this type can be different from the type of 'result',
1286 // e.g. if it's an enum type.
1287 type = arg.getIntegralType();
1288 }
1289 if (result.isInvalid()) return ExprError();
1290
1291 Expr *resultExpr = result.get();
1292 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1293 type, resultExpr->getValueKind(), loc, parm, resultExpr);
1294}
1295
1296ExprResult
1297TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1298 SubstNonTypeTemplateParmPackExpr *E) {
1299 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1300 // We aren't expanding the parameter pack, so just return ourselves.
1301 return E;
1302 }
1303
1304 TemplateArgument Arg = E->getArgumentPack();
1305 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1306 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1307 E->getParameterPackLocation(),
1308 Arg);
1309}
1310
1311ExprResult
1312TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1313 SourceLocation Loc) {
1314 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1315 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1316}
1317
1318ExprResult
1319TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1320 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1321 // We can expand this parameter pack now.
1322 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1323 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1324 if (!VD)
1325 return ExprError();
1326 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1327 }
1328
1329 QualType T = TransformType(E->getType());
1330 if (T.isNull())
1331 return ExprError();
1332
1333 // Transform each of the parameter expansions into the corresponding
1334 // parameters in the instantiation of the function decl.
1335 SmallVector<ParmVarDecl *, 8> Parms;
1336 Parms.reserve(E->getNumExpansions());
1337 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1338 I != End; ++I) {
1339 ParmVarDecl *D =
1340 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1341 if (!D)
1342 return ExprError();
1343 Parms.push_back(D);
1344 }
1345
1346 return FunctionParmPackExpr::Create(getSema().Context, T,
1347 E->getParameterPack(),
1348 E->getParameterPackLocation(), Parms);
1349}
1350
1351ExprResult
1352TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1353 ParmVarDecl *PD) {
1354 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1355 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1356 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1357 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1357, __extension__ __PRETTY_FUNCTION__))
;
1358
1359 Decl *TransformedDecl;
1360 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1361 // If this is a reference to a function parameter pack which we can
1362 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1363 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1364 QualType T = TransformType(E->getType());
1365 if (T.isNull())
1366 return ExprError();
1367 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1368 E->getExprLoc(), *Pack);
1369 }
1370
1371 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1372 } else {
1373 TransformedDecl = Found->get<Decl*>();
1374 }
1375
1376 // We have either an unexpanded pack or a specific expansion.
1377 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1378 E->getExprLoc());
1379}
1380
1381ExprResult
1382TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1383 NamedDecl *D = E->getDecl();
1384
1385 // Handle references to non-type template parameters and non-type template
1386 // parameter packs.
1387 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1388 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1389 return TransformTemplateParmRefExpr(E, NTTP);
1390
1391 // We have a non-type template parameter that isn't fully substituted;
1392 // FindInstantiatedDecl will find it in the local instantiation scope.
1393 }
1394
1395 // Handle references to function parameter packs.
1396 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1397 if (PD->isParameterPack())
1398 return TransformFunctionParmPackRefExpr(E, PD);
1399
1400 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1401}
1402
1403ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1404 CXXDefaultArgExpr *E) {
1405 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.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1407, __extension__ __PRETTY_FUNCTION__))
1406 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.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1407, __extension__ __PRETTY_FUNCTION__))
1407 "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.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1407, __extension__ __PRETTY_FUNCTION__))
;
1408 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1409 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1410 E->getParam());
1411}
1412
1413template<typename Fn>
1414QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1415 FunctionProtoTypeLoc TL,
1416 CXXRecordDecl *ThisContext,
1417 unsigned ThisTypeQuals,
1418 Fn TransformExceptionSpec) {
1419 // We need a local instantiation scope for this function prototype.
1420 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1421 return inherited::TransformFunctionProtoType(
1422 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1423}
1424
1425ParmVarDecl *
1426TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1427 int indexAdjustment,
1428 Optional<unsigned> NumExpansions,
1429 bool ExpectParameterPack) {
1430 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1431 NumExpansions, ExpectParameterPack);
1432}
1433
1434QualType
1435TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1436 TemplateTypeParmTypeLoc TL) {
1437 const TemplateTypeParmType *T = TL.getTypePtr();
1438 if (T->getDepth() < TemplateArgs.getNumLevels()) {
1439 // Replace the template type parameter with its corresponding
1440 // template argument.
1441
1442 // If the corresponding template argument is NULL or doesn't exist, it's
1443 // because we are performing instantiation from explicitly-specified
1444 // template arguments in a function template class, but there were some
1445 // arguments left unspecified.
1446 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1447 TemplateTypeParmTypeLoc NewTL
1448 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1449 NewTL.setNameLoc(TL.getNameLoc());
1450 return TL.getType();
1451 }
1452
1453 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1454
1455 if (T->isParameterPack()) {
1456 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1457, __extension__ __PRETTY_FUNCTION__))
1457 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1457, __extension__ __PRETTY_FUNCTION__))
;
1458
1459 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1460 // We have the template argument pack, but we're not expanding the
1461 // enclosing pack expansion yet. Just save the template argument
1462 // pack for later substitution.
1463 QualType Result
1464 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1465 SubstTemplateTypeParmPackTypeLoc NewTL
1466 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1467 NewTL.setNameLoc(TL.getNameLoc());
1468 return Result;
1469 }
1470
1471 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1472 }
1473
1474 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1475, __extension__ __PRETTY_FUNCTION__))
1475 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1475, __extension__ __PRETTY_FUNCTION__))
;
1476
1477 QualType Replacement = Arg.getAsType();
1478
1479 // TODO: only do this uniquing once, at the start of instantiation.
1480 QualType Result
1481 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1482 SubstTemplateTypeParmTypeLoc NewTL
1483 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1484 NewTL.setNameLoc(TL.getNameLoc());
1485 return Result;
1486 }
1487
1488 // The template type parameter comes from an inner template (e.g.,
1489 // the template parameter list of a member template inside the
1490 // template we are instantiating). Create a new template type
1491 // parameter with the template "level" reduced by one.
1492 TemplateTypeParmDecl *NewTTPDecl = nullptr;
1493 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1494 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1495 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1496
1497 QualType Result = getSema().Context.getTemplateTypeParmType(
1498 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1499 T->isParameterPack(), NewTTPDecl);
1500 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1501 NewTL.setNameLoc(TL.getNameLoc());
1502 return Result;
1503}
1504
1505QualType
1506TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1507 TypeLocBuilder &TLB,
1508 SubstTemplateTypeParmPackTypeLoc TL) {
1509 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1510 // We aren't expanding the parameter pack, so just return ourselves.
1511 SubstTemplateTypeParmPackTypeLoc NewTL
1512 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1513 NewTL.setNameLoc(TL.getNameLoc());
1514 return TL.getType();
1515 }
1516
1517 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1518 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1519 QualType Result = Arg.getAsType();
1520
1521 Result = getSema().Context.getSubstTemplateTypeParmType(
1522 TL.getTypePtr()->getReplacedParameter(),
1523 Result);
1524 SubstTemplateTypeParmTypeLoc NewTL
1525 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1526 NewTL.setNameLoc(TL.getNameLoc());
1527 return Result;
1528}
1529
1530/// Perform substitution on the type T with a given set of template
1531/// arguments.
1532///
1533/// This routine substitutes the given template arguments into the
1534/// type T and produces the instantiated type.
1535///
1536/// \param T the type into which the template arguments will be
1537/// substituted. If this type is not dependent, it will be returned
1538/// immediately.
1539///
1540/// \param Args the template arguments that will be
1541/// substituted for the top-level template parameters within T.
1542///
1543/// \param Loc the location in the source code where this substitution
1544/// is being performed. It will typically be the location of the
1545/// declarator (if we're instantiating the type of some declaration)
1546/// or the location of the type in the source code (if, e.g., we're
1547/// instantiating the type of a cast expression).
1548///
1549/// \param Entity the name of the entity associated with a declaration
1550/// being instantiated (if any). May be empty to indicate that there
1551/// is no such entity (if, e.g., this is a type that occurs as part of
1552/// a cast expression) or that the entity has no name (e.g., an
1553/// unnamed function parameter).
1554///
1555/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1556/// acceptable as the top level type of the result.
1557///
1558/// \returns If the instantiation succeeds, the instantiated
1559/// type. Otherwise, produces diagnostics and returns a NULL type.
1560TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1561 const MultiLevelTemplateArgumentList &Args,
1562 SourceLocation Loc,
1563 DeclarationName Entity,
1564 bool AllowDeducedTST) {
1565 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1567, __extension__ __PRETTY_FUNCTION__))
1566 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1567, __extension__ __PRETTY_FUNCTION__))
1567 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1567, __extension__ __PRETTY_FUNCTION__))
;
1568
1569 if (!T->getType()->isInstantiationDependentType() &&
1570 !T->getType()->isVariablyModifiedType())
1571 return T;
1572
1573 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1574 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1575 : Instantiator.TransformType(T);
1576}
1577
1578TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1579 const MultiLevelTemplateArgumentList &Args,
1580 SourceLocation Loc,
1581 DeclarationName Entity) {
1582 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1584, __extension__ __PRETTY_FUNCTION__))
1583 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1584, __extension__ __PRETTY_FUNCTION__))
1584 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1584, __extension__ __PRETTY_FUNCTION__))
;
1585
1586 if (TL.getType().isNull())
1587 return nullptr;
1588
1589 if (!TL.getType()->isInstantiationDependentType() &&
1590 !TL.getType()->isVariablyModifiedType()) {
1591 // FIXME: Make a copy of the TypeLoc data here, so that we can
1592 // return a new TypeSourceInfo. Inefficient!
1593 TypeLocBuilder TLB;
1594 TLB.pushFullCopy(TL);
1595 return TLB.getTypeSourceInfo(Context, TL.getType());
1596 }
1597
1598 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1599 TypeLocBuilder TLB;
1600 TLB.reserve(TL.getFullDataSize());
1601 QualType Result = Instantiator.TransformType(TLB, TL);
1602 if (Result.isNull())
1603 return nullptr;
1604
1605 return TLB.getTypeSourceInfo(Context, Result);
1606}
1607
1608/// Deprecated form of the above.
1609QualType Sema::SubstType(QualType T,
1610 const MultiLevelTemplateArgumentList &TemplateArgs,
1611 SourceLocation Loc, DeclarationName Entity) {
1612 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1614, __extension__ __PRETTY_FUNCTION__))
1613 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1614, __extension__ __PRETTY_FUNCTION__))
1614 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1614, __extension__ __PRETTY_FUNCTION__))
;
1615
1616 // If T is not a dependent type or a variably-modified type, there
1617 // is nothing to do.
1618 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
1619 return T;
1620
1621 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1622 return Instantiator.TransformType(T);
1623}
1624
1625static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
1626 if (T->getType()->isInstantiationDependentType() ||
1627 T->getType()->isVariablyModifiedType())
1628 return true;
1629
1630 TypeLoc TL = T->getTypeLoc().IgnoreParens();
1631 if (!TL.getAs<FunctionProtoTypeLoc>())
1632 return false;
1633
1634 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
1635 for (ParmVarDecl *P : FP.getParams()) {
1636 // This must be synthesized from a typedef.
1637 if (!P) continue;
1638
1639 // If there are any parameters, a new TypeSourceInfo that refers to the
1640 // instantiated parameters must be built.
1641 return true;
1642 }
1643
1644 return false;
1645}
1646
1647/// A form of SubstType intended specifically for instantiating the
1648/// type of a FunctionDecl. Its purpose is solely to force the
1649/// instantiation of default-argument expressions and to avoid
1650/// instantiating an exception-specification.
1651TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1652 const MultiLevelTemplateArgumentList &Args,
1653 SourceLocation Loc,
1654 DeclarationName Entity,
1655 CXXRecordDecl *ThisContext,
1656 unsigned ThisTypeQuals) {
1657 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1659, __extension__ __PRETTY_FUNCTION__))
1658 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1659, __extension__ __PRETTY_FUNCTION__))
1659 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1659, __extension__ __PRETTY_FUNCTION__))
;
1660
1661 if (!NeedsInstantiationAsFunctionType(T))
1662 return T;
1663
1664 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1665
1666 TypeLocBuilder TLB;
1667
1668 TypeLoc TL = T->getTypeLoc();
1669 TLB.reserve(TL.getFullDataSize());
1670
1671 QualType Result;
1672
1673 if (FunctionProtoTypeLoc Proto =
1674 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1675 // Instantiate the type, other than its exception specification. The
1676 // exception specification is instantiated in InitFunctionInstantiation
1677 // once we've built the FunctionDecl.
1678 // FIXME: Set the exception specification to EST_Uninstantiated here,
1679 // instead of rebuilding the function type again later.
1680 Result = Instantiator.TransformFunctionProtoType(
1681 TLB, Proto, ThisContext, ThisTypeQuals,
1682 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1683 bool &Changed) { return false; });
1684 } else {
1685 Result = Instantiator.TransformType(TLB, TL);
1686 }
1687 if (Result.isNull())
1688 return nullptr;
1689
1690 return TLB.getTypeSourceInfo(Context, Result);
1691}
1692
1693bool Sema::SubstExceptionSpec(SourceLocation Loc,
1694 FunctionProtoType::ExceptionSpecInfo &ESI,
1695 SmallVectorImpl<QualType> &ExceptionStorage,
1696 const MultiLevelTemplateArgumentList &Args) {
1697 assert(ESI.Type != EST_Uninstantiated)(static_cast <bool> (ESI.Type != EST_Uninstantiated) ? void
(0) : __assert_fail ("ESI.Type != EST_Uninstantiated", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1697, __extension__ __PRETTY_FUNCTION__))
;
1698
1699 bool Changed = false;
1700 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
1701 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
1702 Changed);
1703}
1704
1705void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1706 const MultiLevelTemplateArgumentList &Args) {
1707 FunctionProtoType::ExceptionSpecInfo ESI =
1708 Proto->getExtProtoInfo().ExceptionSpec;
1709
1710 SmallVector<QualType, 4> ExceptionStorage;
1711 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getLocEnd(),
1712 ESI, ExceptionStorage, Args))
1713 // On error, recover by dropping the exception specification.
1714 ESI.Type = EST_None;
1715
1716 UpdateExceptionSpec(New, ESI);
1717}
1718
1719ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
1720 const MultiLevelTemplateArgumentList &TemplateArgs,
1721 int indexAdjustment,
1722 Optional<unsigned> NumExpansions,
1723 bool ExpectParameterPack) {
1724 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1725 TypeSourceInfo *NewDI = nullptr;
1726
1727 TypeLoc OldTL = OldDI->getTypeLoc();
1728 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1729
1730 // We have a function parameter pack. Substitute into the pattern of the
1731 // expansion.
1732 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1733 OldParm->getLocation(), OldParm->getDeclName());
1734 if (!NewDI)
1735 return nullptr;
1736
1737 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1738 // We still have unexpanded parameter packs, which means that
1739 // our function parameter is still a function parameter pack.
1740 // Therefore, make its type a pack expansion type.
1741 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1742 NumExpansions);
1743 } else if (ExpectParameterPack) {
1744 // We expected to get a parameter pack but didn't (because the type
1745 // itself is not a pack expansion type), so complain. This can occur when
1746 // the substitution goes through an alias template that "loses" the
1747 // pack expansion.
1748 Diag(OldParm->getLocation(),
1749 diag::err_function_parameter_pack_without_parameter_packs)
1750 << NewDI->getType();
1751 return nullptr;
1752 }
1753 } else {
1754 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1755 OldParm->getDeclName());
1756 }
1757
1758 if (!NewDI)
1759 return nullptr;
1760
1761 if (NewDI->getType()->isVoidType()) {
1762 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1763 return nullptr;
1764 }
1765
1766 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1767 OldParm->getInnerLocStart(),
1768 OldParm->getLocation(),
1769 OldParm->getIdentifier(),
1770 NewDI->getType(), NewDI,
1771 OldParm->getStorageClass());
1772 if (!NewParm)
1773 return nullptr;
1774
1775 // Mark the (new) default argument as uninstantiated (if any).
1776 if (OldParm->hasUninstantiatedDefaultArg()) {
1777 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1778 NewParm->setUninstantiatedDefaultArg(Arg);
1779 } else if (OldParm->hasUnparsedDefaultArg()) {
1780 NewParm->setUnparsedDefaultArg();
1781 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1782 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1783 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
1784 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1785 // Instantiate default arguments for methods of local classes (DR1484)
1786 // and non-defining declarations.
1787 Sema::ContextRAII SavedContext(*this, OwningFunc);
1788 LocalInstantiationScope Local(*this, true);
1789 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
1790 if (NewArg.isUsable()) {
1791 // It would be nice if we still had this.
1792 SourceLocation EqualLoc = NewArg.get()->getLocStart();
1793 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1794 }
1795 } else {
1796 // FIXME: if we non-lazily instantiated non-dependent default args for
1797 // non-dependent parameter types we could remove a bunch of duplicate
1798 // conversion warnings for such arguments.
1799 NewParm->setUninstantiatedDefaultArg(Arg);
1800 }
1801 }
1802
1803 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1804
1805 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1806 // Add the new parameter to the instantiated parameter pack.
1807 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1808 } else {
1809 // Introduce an Old -> New mapping
1810 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1811 }
1812
1813 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1814 // can be anything, is this right ?
1815 NewParm->setDeclContext(CurContext);
1816
1817 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1818 OldParm->getFunctionScopeIndex() + indexAdjustment);
1819
1820 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1821
1822 return NewParm;
1823}
1824
1825/// Substitute the given template arguments into the given set of
1826/// parameters, producing the set of parameter types that would be generated
1827/// from such a substitution.
1828bool Sema::SubstParmTypes(
1829 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1830 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1831 const MultiLevelTemplateArgumentList &TemplateArgs,
1832 SmallVectorImpl<QualType> &ParamTypes,
1833 SmallVectorImpl<ParmVarDecl *> *OutParams,
1834 ExtParameterInfoBuilder &ParamInfos) {
1835 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1837, __extension__ __PRETTY_FUNCTION__))
1836 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1837, __extension__ __PRETTY_FUNCTION__))
1837 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 1837, __extension__ __PRETTY_FUNCTION__))
;
1838
1839 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1840 DeclarationName());
1841 return Instantiator.TransformFunctionTypeParams(
2
Calling 'TreeTransform::TransformFunctionTypeParams'
1842 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
1
Passing null pointer value via 3rd parameter 'ParamTypes'
1843}
1844
1845/// Perform substitution on the base class specifiers of the
1846/// given class template specialization.
1847///
1848/// Produces a diagnostic and returns true on error, returns false and
1849/// attaches the instantiated base classes to the class template
1850/// specialization if successful.
1851bool
1852Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1853 CXXRecordDecl *Pattern,
1854 const MultiLevelTemplateArgumentList &TemplateArgs) {
1855 bool Invalid = false;
1856 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1857 for (const auto &Base : Pattern->bases()) {
1858 if (!Base.getType()->isDependentType()) {
1859 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
1860 if (RD->isInvalidDecl())
1861 Instantiation->setInvalidDecl();
1862 }
1863 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
1864 continue;
1865 }
1866
1867 SourceLocation EllipsisLoc;
1868 TypeSourceInfo *BaseTypeLoc;
1869 if (Base.isPackExpansion()) {
1870 // This is a pack expansion. See whether we should expand it now, or
1871 // wait until later.
1872 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1873 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
1874 Unexpanded);
1875 bool ShouldExpand = false;
1876 bool RetainExpansion = false;
1877 Optional<unsigned> NumExpansions;
1878 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1879 Base.getSourceRange(),
1880 Unexpanded,
1881 TemplateArgs, ShouldExpand,
1882 RetainExpansion,
1883 NumExpansions)) {
1884 Invalid = true;
1885 continue;
1886 }
1887
1888 // If we should expand this pack expansion now, do so.
1889 if (ShouldExpand) {
1890 for (unsigned I = 0; I != *NumExpansions; ++I) {
1891 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1892
1893 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1894 TemplateArgs,
1895 Base.getSourceRange().getBegin(),
1896 DeclarationName());
1897 if (!BaseTypeLoc) {
1898 Invalid = true;
1899 continue;
1900 }
1901
1902 if (CXXBaseSpecifier *InstantiatedBase
1903 = CheckBaseSpecifier(Instantiation,
1904 Base.getSourceRange(),
1905 Base.isVirtual(),
1906 Base.getAccessSpecifierAsWritten(),
1907 BaseTypeLoc,
1908 SourceLocation()))
1909 InstantiatedBases.push_back(InstantiatedBase);
1910 else
1911 Invalid = true;
1912 }
1913
1914 continue;
1915 }
1916
1917 // The resulting base specifier will (still) be a pack expansion.
1918 EllipsisLoc = Base.getEllipsisLoc();
1919 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1920 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1921 TemplateArgs,
1922 Base.getSourceRange().getBegin(),
1923 DeclarationName());
1924 } else {
1925 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1926 TemplateArgs,
1927 Base.getSourceRange().getBegin(),
1928 DeclarationName());
1929 }
1930
1931 if (!BaseTypeLoc) {
1932 Invalid = true;
1933 continue;
1934 }
1935
1936 if (CXXBaseSpecifier *InstantiatedBase
1937 = CheckBaseSpecifier(Instantiation,
1938 Base.getSourceRange(),
1939 Base.isVirtual(),
1940 Base.getAccessSpecifierAsWritten(),
1941 BaseTypeLoc,
1942 EllipsisLoc))
1943 InstantiatedBases.push_back(InstantiatedBase);
1944 else
1945 Invalid = true;
1946 }
1947
1948 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
1949 Invalid = true;
1950
1951 return Invalid;
1952}
1953
1954// Defined via #include from SemaTemplateInstantiateDecl.cpp
1955namespace clang {
1956 namespace sema {
1957 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1958 const MultiLevelTemplateArgumentList &TemplateArgs);
1959 Attr *instantiateTemplateAttributeForDecl(
1960 const Attr *At, ASTContext &C, Sema &S,
1961 const MultiLevelTemplateArgumentList &TemplateArgs);
1962 }
1963}
1964
1965/// Instantiate the definition of a class from a given pattern.
1966///
1967/// \param PointOfInstantiation The point of instantiation within the
1968/// source code.
1969///
1970/// \param Instantiation is the declaration whose definition is being
1971/// instantiated. This will be either a class template specialization
1972/// or a member class of a class template specialization.
1973///
1974/// \param Pattern is the pattern from which the instantiation
1975/// occurs. This will be either the declaration of a class template or
1976/// the declaration of a member class of a class template.
1977///
1978/// \param TemplateArgs The template arguments to be substituted into
1979/// the pattern.
1980///
1981/// \param TSK the kind of implicit or explicit instantiation to perform.
1982///
1983/// \param Complain whether to complain if the class cannot be instantiated due
1984/// to the lack of a definition.
1985///
1986/// \returns true if an error occurred, false otherwise.
1987bool
1988Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1989 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
1990 const MultiLevelTemplateArgumentList &TemplateArgs,
1991 TemplateSpecializationKind TSK,
1992 bool Complain) {
1993 CXXRecordDecl *PatternDef
1994 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
1995 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
1996 Instantiation->getInstantiatedFromMemberClass(),
1997 Pattern, PatternDef, TSK, Complain))
1998 return true;
1999 Pattern = PatternDef;
2000
2001 // Record the point of instantiation.
2002 if (MemberSpecializationInfo *MSInfo
2003 = Instantiation->getMemberSpecializationInfo()) {
2004 MSInfo->setTemplateSpecializationKind(TSK);
2005 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2006 } else if (ClassTemplateSpecializationDecl *Spec
2007 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
2008 Spec->setTemplateSpecializationKind(TSK);
2009 Spec->setPointOfInstantiation(PointOfInstantiation);
2010 }
2011
2012 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2013 if (Inst.isInvalid())
2014 return true;
2015 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2015, __extension__ __PRETTY_FUNCTION__))
;
2016 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2017 "instantiating class definition");
2018
2019 // Enter the scope of this instantiation. We don't use
2020 // PushDeclContext because we don't have a scope.
2021 ContextRAII SavedContext(*this, Instantiation);
2022 EnterExpressionEvaluationContext EvalContext(
2023 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2024
2025 // If this is an instantiation of a local class, merge this local
2026 // instantiation scope with the enclosing scope. Otherwise, every
2027 // instantiation of a class has its own local instantiation scope.
2028 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
2029 LocalInstantiationScope Scope(*this, MergeWithParentScope);
2030
2031 // Some class state isn't processed immediately but delayed till class
2032 // instantiation completes. We may not be ready to handle any delayed state
2033 // already on the stack as it might correspond to a different class, so save
2034 // it now and put it back later.
2035 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
2036
2037 // Pull attributes from the pattern onto the instantiation.
2038 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2039
2040 // Start the definition of this instantiation.
2041 Instantiation->startDefinition();
2042
2043 // The instantiation is visible here, even if it was first declared in an
2044 // unimported module.
2045 Instantiation->setVisibleDespiteOwningModule();
2046
2047 // FIXME: This loses the as-written tag kind for an explicit instantiation.
2048 Instantiation->setTagKind(Pattern->getTagKind());
2049
2050 // Do substitution on the base class specifiers.
2051 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
2052 Instantiation->setInvalidDecl();
2053
2054 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2055 SmallVector<Decl*, 4> Fields;
2056 // Delay instantiation of late parsed attributes.
2057 LateInstantiatedAttrVec LateAttrs;
2058 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2059
2060 for (auto *Member : Pattern->decls()) {
2061 // Don't instantiate members not belonging in this semantic context.
2062 // e.g. for:
2063 // @code
2064 // template <int i> class A {
2065 // class B *g;
2066 // };
2067 // @endcode
2068 // 'class B' has the template as lexical context but semantically it is
2069 // introduced in namespace scope.
2070 if (Member->getDeclContext() != Pattern)
2071 continue;
2072
2073 // BlockDecls can appear in a default-member-initializer. They must be the
2074 // child of a BlockExpr, so we only know how to instantiate them from there.
2075 if (isa<BlockDecl>(Member))
2076 continue;
2077
2078 if (Member->isInvalidDecl()) {
2079 Instantiation->setInvalidDecl();
2080 continue;
2081 }
2082
2083 Decl *NewMember = Instantiator.Visit(Member);
2084 if (NewMember) {
2085 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2086 Fields.push_back(Field);
2087 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2088 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2089 // specialization causes the implicit instantiation of the definitions
2090 // of unscoped member enumerations.
2091 // Record a point of instantiation for this implicit instantiation.
2092 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2093 Enum->isCompleteDefinition()) {
2094 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2095 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2095, __extension__ __PRETTY_FUNCTION__))
;
2096 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2097 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2098 }
2099 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2100 if (SA->isFailed()) {
2101 // A static_assert failed. Bail out; instantiating this
2102 // class is probably not meaningful.
2103 Instantiation->setInvalidDecl();
2104 break;
2105 }
2106 }
2107
2108 if (NewMember->isInvalidDecl())
2109 Instantiation->setInvalidDecl();
2110 } else {
2111 // FIXME: Eventually, a NULL return will mean that one of the
2112 // instantiations was a semantic disaster, and we'll want to mark the
2113 // declaration invalid.
2114 // For now, we expect to skip some members that we can't yet handle.
2115 }
2116 }
2117
2118 // Finish checking fields.
2119 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2120 SourceLocation(), SourceLocation(), ParsedAttributesView());
2121 CheckCompletedCXXClass(Instantiation);
2122
2123 // Default arguments are parsed, if not instantiated. We can go instantiate
2124 // default arg exprs for default constructors if necessary now.
2125 ActOnFinishCXXNonNestedClass(Instantiation);
2126
2127 // Instantiate late parsed attributes, and attach them to their decls.
2128 // See Sema::InstantiateAttrs
2129 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2130 E = LateAttrs.end(); I != E; ++I) {
2131 assert(CurrentInstantiationScope == Instantiator.getStartingScope())(static_cast <bool> (CurrentInstantiationScope == Instantiator
.getStartingScope()) ? void (0) : __assert_fail ("CurrentInstantiationScope == Instantiator.getStartingScope()"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2131, __extension__ __PRETTY_FUNCTION__))
;
2132 CurrentInstantiationScope = I->Scope;
2133
2134 // Allow 'this' within late-parsed attributes.
2135 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2136 CXXRecordDecl *ThisContext =
2137 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2138 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2139 ND && ND->isCXXInstanceMember());
2140
2141 Attr *NewAttr =
2142 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2143 I->NewDecl->addAttr(NewAttr);
2144 LocalInstantiationScope::deleteScopes(I->Scope,
2145 Instantiator.getStartingScope());
2146 }
2147 Instantiator.disableLateAttributeInstantiation();
2148 LateAttrs.clear();
2149
2150 ActOnFinishDelayedMemberInitializers(Instantiation);
2151
2152 // FIXME: We should do something similar for explicit instantiations so they
2153 // end up in the right module.
2154 if (TSK == TSK_ImplicitInstantiation) {
2155 Instantiation->setLocation(Pattern->getLocation());
2156 Instantiation->setLocStart(Pattern->getInnerLocStart());
2157 Instantiation->setBraceRange(Pattern->getBraceRange());
2158 }
2159
2160 if (!Instantiation->isInvalidDecl()) {
2161 // Perform any dependent diagnostics from the pattern.
2162 PerformDependentDiagnostics(Pattern, TemplateArgs);
2163
2164 // Instantiate any out-of-line class template partial
2165 // specializations now.
2166 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2167 P = Instantiator.delayed_partial_spec_begin(),
2168 PEnd = Instantiator.delayed_partial_spec_end();
2169 P != PEnd; ++P) {
2170 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2171 P->first, P->second)) {
2172 Instantiation->setInvalidDecl();
2173 break;
2174 }
2175 }
2176
2177 // Instantiate any out-of-line variable template partial
2178 // specializations now.
2179 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2180 P = Instantiator.delayed_var_partial_spec_begin(),
2181 PEnd = Instantiator.delayed_var_partial_spec_end();
2182 P != PEnd; ++P) {
2183 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2184 P->first, P->second)) {
2185 Instantiation->setInvalidDecl();
2186 break;
2187 }
2188 }
2189 }
2190
2191 // Exit the scope of this instantiation.
2192 SavedContext.pop();
2193
2194 if (!Instantiation->isInvalidDecl()) {
2195 Consumer.HandleTagDeclDefinition(Instantiation);
2196
2197 // Always emit the vtable for an explicit instantiation definition
2198 // of a polymorphic class template specialization.
2199 if (TSK == TSK_ExplicitInstantiationDefinition)
2200 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2201 }
2202
2203 return Instantiation->isInvalidDecl();
2204}
2205
2206/// Instantiate the definition of an enum from a given pattern.
2207///
2208/// \param PointOfInstantiation The point of instantiation within the
2209/// source code.
2210/// \param Instantiation is the declaration whose definition is being
2211/// instantiated. This will be a member enumeration of a class
2212/// temploid specialization, or a local enumeration within a
2213/// function temploid specialization.
2214/// \param Pattern The templated declaration from which the instantiation
2215/// occurs.
2216/// \param TemplateArgs The template arguments to be substituted into
2217/// the pattern.
2218/// \param TSK The kind of implicit or explicit instantiation to perform.
2219///
2220/// \return \c true if an error occurred, \c false otherwise.
2221bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2222 EnumDecl *Instantiation, EnumDecl *Pattern,
2223 const MultiLevelTemplateArgumentList &TemplateArgs,
2224 TemplateSpecializationKind TSK) {
2225 EnumDecl *PatternDef = Pattern->getDefinition();
2226 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2227 Instantiation->getInstantiatedFromMemberEnum(),
2228 Pattern, PatternDef, TSK,/*Complain*/true))
2229 return true;
2230 Pattern = PatternDef;
2231
2232 // Record the point of instantiation.
2233 if (MemberSpecializationInfo *MSInfo
2234 = Instantiation->getMemberSpecializationInfo()) {
2235 MSInfo->setTemplateSpecializationKind(TSK);
2236 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2237 }
2238
2239 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2240 if (Inst.isInvalid())
2241 return true;
2242 if (Inst.isAlreadyInstantiating())
2243 return false;
2244 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2245 "instantiating enum definition");
2246
2247 // The instantiation is visible here, even if it was first declared in an
2248 // unimported module.
2249 Instantiation->setVisibleDespiteOwningModule();
2250
2251 // Enter the scope of this instantiation. We don't use
2252 // PushDeclContext because we don't have a scope.
2253 ContextRAII SavedContext(*this, Instantiation);
2254 EnterExpressionEvaluationContext EvalContext(
2255 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2256
2257 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2258
2259 // Pull attributes from the pattern onto the instantiation.
2260 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2261
2262 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2263 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2264
2265 // Exit the scope of this instantiation.
2266 SavedContext.pop();
2267
2268 return Instantiation->isInvalidDecl();
2269}
2270
2271
2272/// Instantiate the definition of a field from the given pattern.
2273///
2274/// \param PointOfInstantiation The point of instantiation within the
2275/// source code.
2276/// \param Instantiation is the declaration whose definition is being
2277/// instantiated. This will be a class of a class temploid
2278/// specialization, or a local enumeration within a function temploid
2279/// specialization.
2280/// \param Pattern The templated declaration from which the instantiation
2281/// occurs.
2282/// \param TemplateArgs The template arguments to be substituted into
2283/// the pattern.
2284///
2285/// \return \c true if an error occurred, \c false otherwise.
2286bool Sema::InstantiateInClassInitializer(
2287 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2288 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2289 // If there is no initializer, we don't need to do anything.
2290 if (!Pattern->hasInClassInitializer())
2291 return false;
2292
2293 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2295, __extension__ __PRETTY_FUNCTION__))
2294 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2295, __extension__ __PRETTY_FUNCTION__))
2295 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2295, __extension__ __PRETTY_FUNCTION__))
;
2296
2297 // Error out if we haven't parsed the initializer of the pattern yet because
2298 // we are waiting for the closing brace of the outer class.
2299 Expr *OldInit = Pattern->getInClassInitializer();
2300 if (!OldInit) {
2301 RecordDecl *PatternRD = Pattern->getParent();
2302 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2303 Diag(PointOfInstantiation,
2304 diag::err_in_class_initializer_not_yet_parsed)
2305 << OutermostClass << Pattern;
2306 Diag(Pattern->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
2307 Instantiation->setInvalidDecl();
2308 return true;
2309 }
2310
2311 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2312 if (Inst.isInvalid())
2313 return true;
2314 if (Inst.isAlreadyInstantiating()) {
2315 // Error out if we hit an instantiation cycle for this initializer.
2316 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2317 << Instantiation;
2318 return true;
2319 }
2320 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2321 "instantiating default member init");
2322
2323 // Enter the scope of this instantiation. We don't use PushDeclContext because
2324 // we don't have a scope.
2325 ContextRAII SavedContext(*this, Instantiation->getParent());
2326 EnterExpressionEvaluationContext EvalContext(
2327 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2328
2329 LocalInstantiationScope Scope(*this, true);
2330
2331 // Instantiate the initializer.
2332 ActOnStartCXXInClassMemberInitializer();
2333 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2334
2335 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2336 /*CXXDirectInit=*/false);
2337 Expr *Init = NewInit.get();
2338 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2338, __extension__ __PRETTY_FUNCTION__))
;
2339 ActOnFinishCXXInClassMemberInitializer(
2340 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2341
2342 if (auto *L = getASTMutationListener())
2343 L->DefaultMemberInitializerInstantiated(Instantiation);
2344
2345 // Return true if the in-class initializer is still missing.
2346 return !Instantiation->getInClassInitializer();
2347}
2348
2349namespace {
2350 /// A partial specialization whose template arguments have matched
2351 /// a given template-id.
2352 struct PartialSpecMatchResult {
2353 ClassTemplatePartialSpecializationDecl *Partial;
2354 TemplateArgumentList *Args;
2355 };
2356}
2357
2358bool Sema::usesPartialOrExplicitSpecialization(
2359 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
2360 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
2361 TSK_ExplicitSpecialization)
2362 return true;
2363
2364 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2365 ClassTemplateSpec->getSpecializedTemplate()
2366 ->getPartialSpecializations(PartialSpecs);
2367 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2368 TemplateDeductionInfo Info(Loc);
2369 if (!DeduceTemplateArguments(PartialSpecs[I],
2370 ClassTemplateSpec->getTemplateArgs(), Info))
2371 return true;
2372 }
2373
2374 return false;
2375}
2376
2377/// Get the instantiation pattern to use to instantiate the definition of a
2378/// given ClassTemplateSpecializationDecl (either the pattern of the primary
2379/// template or of a partial specialization).
2380static CXXRecordDecl *
2381getPatternForClassTemplateSpecialization(
2382 Sema &S, SourceLocation PointOfInstantiation,
2383 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2384 TemplateSpecializationKind TSK, bool Complain) {
2385 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2386 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2387 return nullptr;
2388
2389 llvm::PointerUnion<ClassTemplateDecl *,
2390 ClassTemplatePartialSpecializationDecl *>
2391 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2392 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
2393 // Find best matching specialization.
2394 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2395
2396 // C++ [temp.class.spec.match]p1:
2397 // When a class template is used in a context that requires an
2398 // instantiation of the class, it is necessary to determine
2399 // whether the instantiation is to be generated using the primary
2400 // template or one of the partial specializations. This is done by
2401 // matching the template arguments of the class template
2402 // specialization with the template argument lists of the partial
2403 // specializations.
2404 typedef PartialSpecMatchResult MatchResult;
2405 SmallVector<MatchResult, 4> Matched;
2406 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2407 Template->getPartialSpecializations(PartialSpecs);
2408 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2409 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2410 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2411 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2412 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
2413 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2414 // Store the failed-deduction information for use in diagnostics, later.
2415 // TODO: Actually use the failed-deduction info?
2416 FailedCandidates.addCandidate().set(
2417 DeclAccessPair::make(Template, AS_public), Partial,
2418 MakeDeductionFailureInfo(S.Context, Result, Info));
2419 (void)Result;
2420 } else {
2421 Matched.push_back(PartialSpecMatchResult());
2422 Matched.back().Partial = Partial;
2423 Matched.back().Args = Info.take();
2424 }
2425 }
2426
2427 // If we're dealing with a member template where the template parameters
2428 // have been instantiated, this provides the original template parameters
2429 // from which the member template's parameters were instantiated.
2430
2431 if (Matched.size() >= 1) {
2432 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2433 if (Matched.size() == 1) {
2434 // -- If exactly one matching specialization is found, the
2435 // instantiation is generated from that specialization.
2436 // We don't need to do anything for this.
2437 } else {
2438 // -- If more than one matching specialization is found, the
2439 // partial order rules (14.5.4.2) are used to determine
2440 // whether one of the specializations is more specialized
2441 // than the others. If none of the specializations is more
2442 // specialized than all of the other matching
2443 // specializations, then the use of the class template is
2444 // ambiguous and the program is ill-formed.
2445 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2446 PEnd = Matched.end();
2447 P != PEnd; ++P) {
2448 if (S.getMoreSpecializedPartialSpecialization(
2449 P->Partial, Best->Partial, PointOfInstantiation) ==
2450 P->Partial)
2451 Best = P;
2452 }
2453
2454 // Determine if the best partial specialization is more specialized than
2455 // the others.
2456 bool Ambiguous = false;
2457 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2458 PEnd = Matched.end();
2459 P != PEnd; ++P) {
2460 if (P != Best && S.getMoreSpecializedPartialSpecialization(
2461 P->Partial, Best->Partial,
2462 PointOfInstantiation) != Best->Partial) {
2463 Ambiguous = true;
2464 break;
2465 }
2466 }
2467
2468 if (Ambiguous) {
2469 // Partial ordering did not produce a clear winner. Complain.
2470 Inst.Clear();
2471 ClassTemplateSpec->setInvalidDecl();
2472 S.Diag(PointOfInstantiation,
2473 diag::err_partial_spec_ordering_ambiguous)
2474 << ClassTemplateSpec;
2475
2476 // Print the matching partial specializations.
2477 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2478 PEnd = Matched.end();
2479 P != PEnd; ++P)
2480 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2481 << S.getTemplateArgumentBindingsText(
2482 P->Partial->getTemplateParameters(), *P->Args);
2483
2484 return nullptr;
2485 }
2486 }
2487
2488 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
2489 } else {
2490 // -- If no matches are found, the instantiation is generated
2491 // from the primary template.
2492 }
2493 }
2494
2495 CXXRecordDecl *Pattern = nullptr;
2496 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2497 if (auto *PartialSpec =
2498 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
2499 // Instantiate using the best class template partial specialization.
2500 while (PartialSpec->getInstantiatedFromMember()) {
2501 // If we've found an explicit specialization of this class template,
2502 // stop here and use that as the pattern.
2503 if (PartialSpec->isMemberSpecialization())
2504 break;
2505
2506 PartialSpec = PartialSpec->getInstantiatedFromMember();
2507 }
2508 Pattern = PartialSpec;
2509 } else {
2510 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2511 while (Template->getInstantiatedFromMemberTemplate()) {
2512 // If we've found an explicit specialization of this class template,
2513 // stop here and use that as the pattern.
2514 if (Template->isMemberSpecialization())
2515 break;
2516
2517 Template = Template->getInstantiatedFromMemberTemplate();
2518 }
2519 Pattern = Template->getTemplatedDecl();
2520 }
2521
2522 return Pattern;
2523}
2524
2525bool Sema::InstantiateClassTemplateSpecialization(
2526 SourceLocation PointOfInstantiation,
2527 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2528 TemplateSpecializationKind TSK, bool Complain) {
2529 // Perform the actual instantiation on the canonical declaration.
2530 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2531 ClassTemplateSpec->getCanonicalDecl());
2532 if (ClassTemplateSpec->isInvalidDecl())
2533 return true;
2534
2535 CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
2536 *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2537 if (!Pattern)
2538 return true;
2539
2540 return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2541 getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2542 Complain);
2543}
2544
2545/// Instantiates the definitions of all of the member
2546/// of the given class, which is an instantiation of a class template
2547/// or a member class of a template.
2548void
2549Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
2550 CXXRecordDecl *Instantiation,
2551 const MultiLevelTemplateArgumentList &TemplateArgs,
2552 TemplateSpecializationKind TSK) {
2553 // FIXME: We need to notify the ASTMutationListener that we did all of these
2554 // things, in case we have an explicit instantiation definition in a PCM, a
2555 // module, or preamble, and the declaration is in an imported AST.
2556 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!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2560, __extension__ __PRETTY_FUNCTION__))
2557 (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!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2560, __extension__ __PRETTY_FUNCTION__))
2558 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!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2560, __extension__ __PRETTY_FUNCTION__))
2559 (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!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2560, __extension__ __PRETTY_FUNCTION__))
2560 "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!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2560, __extension__ __PRETTY_FUNCTION__))
;
2561 for (auto *D : Instantiation->decls()) {
2562 bool SuppressNew = false;
2563 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
2564 if (FunctionDecl *Pattern
2565 = Function->getInstantiatedFromMemberFunction()) {
2566 MemberSpecializationInfo *MSInfo
2567 = Function->getMemberSpecializationInfo();
2568 assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?"
) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2568, __extension__ __PRETTY_FUNCTION__))
;
2569 if (MSInfo->getTemplateSpecializationKind()
2570 == TSK_ExplicitSpecialization)
2571 continue;
2572
2573 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2574 Function,
2575 MSInfo->getTemplateSpecializationKind(),
2576 MSInfo->getPointOfInstantiation(),
2577 SuppressNew) ||
2578 SuppressNew)
2579 continue;
2580
2581 // C++11 [temp.explicit]p8:
2582 // An explicit instantiation definition that names a class template
2583 // specialization explicitly instantiates the class template
2584 // specialization and is only an explicit instantiation definition
2585 // of members whose definition is visible at the point of
2586 // instantiation.
2587 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
2588 continue;
2589
2590 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2591
2592 if (Function->isDefined()) {
2593 // Let the ASTConsumer know that this function has been explicitly
2594 // instantiated now, and its linkage might have changed.
2595 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2596 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
2597 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2598 } else if (TSK == TSK_ImplicitInstantiation) {
2599 PendingLocalImplicitInstantiations.push_back(
2600 std::make_pair(Function, PointOfInstantiation));
2601 }
2602 }
2603 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
2604 if (isa<VarTemplateSpecializationDecl>(Var))
2605 continue;
2606
2607 if (Var->isStaticDataMember()) {
2608 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2609 assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?"
) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2609, __extension__ __PRETTY_FUNCTION__))
;
2610 if (MSInfo->getTemplateSpecializationKind()
2611 == TSK_ExplicitSpecialization)
2612 continue;
2613
2614 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2615 Var,
2616 MSInfo->getTemplateSpecializationKind(),
2617 MSInfo->getPointOfInstantiation(),
2618 SuppressNew) ||
2619 SuppressNew)
2620 continue;
2621
2622 if (TSK == TSK_ExplicitInstantiationDefinition) {
2623 // C++0x [temp.explicit]p8:
2624 // An explicit instantiation definition that names a class template
2625 // specialization explicitly instantiates the class template
2626 // specialization and is only an explicit instantiation definition
2627 // of members whose definition is visible at the point of
2628 // instantiation.
2629 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
2630 continue;
2631
2632 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2633 InstantiateVariableDefinition(PointOfInstantiation, Var);
2634 } else {
2635 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2636 }
2637 }
2638 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
2639 // Always skip the injected-class-name, along with any
2640 // redeclarations of nested classes, since both would cause us
2641 // to try to instantiate the members of a class twice.
2642 // Skip closure types; they'll get instantiated when we instantiate
2643 // the corresponding lambda-expression.
2644 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2645 Record->isLambda())
2646 continue;
2647
2648 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2649 assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?"
) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2649, __extension__ __PRETTY_FUNCTION__))
;
2650
2651 if (MSInfo->getTemplateSpecializationKind()
2652 == TSK_ExplicitSpecialization)
2653 continue;
2654
2655 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2656 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) &&
2657 TSK == TSK_ExplicitInstantiationDeclaration) {
2658 // In MSVC and Windows Itanium mode, explicit instantiation decl of the
2659 // outer class doesn't affect the inner class.
2660 continue;
2661 }
2662
2663 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2664 Record,
2665 MSInfo->getTemplateSpecializationKind(),
2666 MSInfo->getPointOfInstantiation(),
2667 SuppressNew) ||
2668 SuppressNew)
2669 continue;
2670
2671 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2672 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2672, __extension__ __PRETTY_FUNCTION__))
;
2673
2674 if (!Record->getDefinition()) {
2675 if (!Pattern->getDefinition()) {
2676 // C++0x [temp.explicit]p8:
2677 // An explicit instantiation definition that names a class template
2678 // specialization explicitly instantiates the class template
2679 // specialization and is only an explicit instantiation definition
2680 // of members whose definition is visible at the point of
2681 // instantiation.
2682 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2683 MSInfo->setTemplateSpecializationKind(TSK);
2684 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2685 }
2686
2687 continue;
2688 }
2689
2690 InstantiateClass(PointOfInstantiation, Record, Pattern,
2691 TemplateArgs,
2692 TSK);
2693 } else {
2694 if (TSK == TSK_ExplicitInstantiationDefinition &&
2695 Record->getTemplateSpecializationKind() ==
2696 TSK_ExplicitInstantiationDeclaration) {
2697 Record->setTemplateSpecializationKind(TSK);
2698 MarkVTableUsed(PointOfInstantiation, Record, true);
2699 }
2700 }
2701
2702 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2703 if (Pattern)
2704 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2705 TSK);
2706 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
2707 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2708 assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?"
) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2708, __extension__ __PRETTY_FUNCTION__))
;
2709
2710 if (MSInfo->getTemplateSpecializationKind()
2711 == TSK_ExplicitSpecialization)
2712 continue;
2713
2714 if (CheckSpecializationInstantiationRedecl(
2715 PointOfInstantiation, TSK, Enum,
2716 MSInfo->getTemplateSpecializationKind(),
2717 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2718 SuppressNew)
2719 continue;
2720
2721 if (Enum->getDefinition())
2722 continue;
2723
2724 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
2725 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2725, __extension__ __PRETTY_FUNCTION__))
;
2726
2727 if (TSK == TSK_ExplicitInstantiationDefinition) {
2728 if (!Pattern->getDefinition())
2729 continue;
2730
2731 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2732 } else {
2733 MSInfo->setTemplateSpecializationKind(TSK);
2734 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2735 }
2736 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2737 // No need to instantiate in-class initializers during explicit
2738 // instantiation.
2739 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2740 CXXRecordDecl *ClassPattern =
2741 Instantiation->getTemplateInstantiationPattern();
2742 DeclContext::lookup_result Lookup =
2743 ClassPattern->lookup(Field->getDeclName());
2744 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
2745 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2746 TemplateArgs);
2747 }
2748 }
2749 }
2750}
2751
2752/// Instantiate the definitions of all of the members of the
2753/// given class template specialization, which was named as part of an
2754/// explicit instantiation.
2755void
2756Sema::InstantiateClassTemplateSpecializationMembers(
2757 SourceLocation PointOfInstantiation,
2758 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2759 TemplateSpecializationKind TSK) {
2760 // C++0x [temp.explicit]p7:
2761 // An explicit instantiation that names a class template
2762 // specialization is an explicit instantion of the same kind
2763 // (declaration or definition) of each of its members (not
2764 // including members inherited from base classes) that has not
2765 // been previously explicitly specialized in the translation unit
2766 // containing the explicit instantiation, except as described
2767 // below.
2768 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2769 getTemplateInstantiationArgs(ClassTemplateSpec),
2770 TSK);
2771}
2772
2773StmtResult
2774Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
2775 if (!S)
2776 return S;
2777
2778 TemplateInstantiator Instantiator(*this, TemplateArgs,
2779 SourceLocation(),
2780 DeclarationName());
2781 return Instantiator.TransformStmt(S);
2782}
2783
2784ExprResult
2785Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
2786 if (!E)
2787 return E;
2788
2789 TemplateInstantiator Instantiator(*this, TemplateArgs,
2790 SourceLocation(),
2791 DeclarationName());
2792 return Instantiator.TransformExpr(E);
2793}
2794
2795ExprResult Sema::SubstInitializer(Expr *Init,
2796 const MultiLevelTemplateArgumentList &TemplateArgs,
2797 bool CXXDirectInit) {
2798 TemplateInstantiator Instantiator(*this, TemplateArgs,
2799 SourceLocation(),
2800 DeclarationName());
2801 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2802}
2803
2804bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
2805 const MultiLevelTemplateArgumentList &TemplateArgs,
2806 SmallVectorImpl<Expr *> &Outputs) {
2807 if (Exprs.empty())
2808 return false;
2809
2810 TemplateInstantiator Instantiator(*this, TemplateArgs,
2811 SourceLocation(),
2812 DeclarationName());
2813 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2814 IsCall, Outputs);
2815}
2816
2817NestedNameSpecifierLoc
2818Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2819 const MultiLevelTemplateArgumentList &TemplateArgs) {
2820 if (!NNS)
2821 return NestedNameSpecifierLoc();
2822
2823 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2824 DeclarationName());
2825 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2826}
2827
2828/// Do template substitution on declaration name info.
2829DeclarationNameInfo
2830Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2831 const MultiLevelTemplateArgumentList &TemplateArgs) {
2832 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2833 NameInfo.getName());
2834 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2835}
2836
2837TemplateName
2838Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2839 TemplateName Name, SourceLocation Loc,
2840 const MultiLevelTemplateArgumentList &TemplateArgs) {
2841 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2842 DeclarationName());
2843 CXXScopeSpec SS;
2844 SS.Adopt(QualifierLoc);
2845 return Instantiator.TransformTemplateName(SS, Name, Loc);
2846}
2847
2848bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2849 TemplateArgumentListInfo &Result,
2850 const MultiLevelTemplateArgumentList &TemplateArgs) {
2851 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2852 DeclarationName());
2853
2854 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2855}
2856
2857static const Decl *getCanonicalParmVarDecl(const Decl *D) {
2858 // When storing ParmVarDecls in the local instantiation scope, we always
2859 // want to use the ParmVarDecl from the canonical function declaration,
2860 // since the map is then valid for any redeclaration or definition of that
2861 // function.
2862 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2863 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2864 unsigned i = PV->getFunctionScopeIndex();
2865 // This parameter might be from a freestanding function type within the
2866 // function and isn't necessarily referring to one of FD's parameters.
2867 if (FD->getParamDecl(i) == PV)
2868 return FD->getCanonicalDecl()->getParamDecl(i);
2869 }
2870 }
2871 return D;
2872}
2873
2874
2875llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2876LocalInstantiationScope::findInstantiationOf(const Decl *D) {
2877 D = getCanonicalParmVarDecl(D);
2878 for (LocalInstantiationScope *Current = this; Current;
2879 Current = Current->Outer) {
2880
2881 // Check if we found something within this scope.
2882 const Decl *CheckD = D;
2883 do {
2884 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
2885 if (Found != Current->LocalDecls.end())
2886 return &Found->second;
2887
2888 // If this is a tag declaration, it's possible that we need to look for
2889 // a previous declaration.
2890 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2891 CheckD = Tag->getPreviousDecl();
2892 else
2893 CheckD = nullptr;
2894 } while (CheckD);
2895
2896 // If we aren't combined with our outer scope, we're done.
2897 if (!Current->CombineWithOuterScope)
2898 break;
2899 }
2900
2901 // If we're performing a partial substitution during template argument
2902 // deduction, we may not have values for template parameters yet.
2903 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2904 isa<TemplateTemplateParmDecl>(D))
2905 return nullptr;
2906
2907 // Local types referenced prior to definition may require instantiation.
2908 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2909 if (RD->isLocalClass())
2910 return nullptr;
2911
2912 // Enumeration types referenced prior to definition may appear as a result of
2913 // error recovery.
2914 if (isa<EnumDecl>(D))
2915 return nullptr;
2916
2917 // If we didn't find the decl, then we either have a sema bug, or we have a
2918 // forward reference to a label declaration. Return null to indicate that
2919 // we have an uninstantiated label.
2920 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2920, __extension__ __PRETTY_FUNCTION__))
;
2921 return nullptr;
2922}
2923
2924void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
2925 D = getCanonicalParmVarDecl(D);
2926 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2927 if (Stored.isNull()) {
2928#ifndef NDEBUG
2929 // It should not be present in any surrounding scope either.
2930 LocalInstantiationScope *Current = this;
2931 while (Current->CombineWithOuterScope && Current->Outer) {
2932 Current = Current->Outer;
2933 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2934, __extension__ __PRETTY_FUNCTION__))
2934 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2934, __extension__ __PRETTY_FUNCTION__))
;
2935 }
2936#endif
2937 Stored = Inst;
2938 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
2939 Pack->push_back(cast<ParmVarDecl>(Inst));
2940 } else {
2941 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2941, __extension__ __PRETTY_FUNCTION__))
;
2942 }
2943}
2944
2945void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2946 ParmVarDecl *Inst) {
2947 D = getCanonicalParmVarDecl(D);
2948 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2949 Pack->push_back(Inst);
2950}
2951
2952void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2953#ifndef NDEBUG
2954 // This should be the first time we've been told about this decl.
2955 for (LocalInstantiationScope *Current = this;
2956 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2957 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2958, __extension__ __PRETTY_FUNCTION__))
2958 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2958, __extension__ __PRETTY_FUNCTION__))
;
2959#endif
2960
2961 D = getCanonicalParmVarDecl(D);
2962 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2963 DeclArgumentPack *Pack = new DeclArgumentPack;
2964 Stored = Pack;
2965 ArgumentPacks.push_back(Pack);
2966}
2967
2968void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2969 const TemplateArgument *ExplicitArgs,
2970 unsigned NumExplicitArgs) {
2971 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2972, __extension__ __PRETTY_FUNCTION__))
2972 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2972, __extension__ __PRETTY_FUNCTION__))
;
2973 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2975, __extension__ __PRETTY_FUNCTION__))
2974 || 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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2975, __extension__ __PRETTY_FUNCTION__))
2975 "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\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2975, __extension__ __PRETTY_FUNCTION__))
;
2976 PartiallySubstitutedPack = Pack;
2977 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2978 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2979}
2980
2981NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2982 const TemplateArgument **ExplicitArgs,
2983 unsigned *NumExplicitArgs) const {
2984 if (ExplicitArgs)
2985 *ExplicitArgs = nullptr;
2986 if (NumExplicitArgs)
2987 *NumExplicitArgs = 0;
2988
2989 for (const LocalInstantiationScope *Current = this; Current;
2990 Current = Current->Outer) {
2991 if (Current->PartiallySubstitutedPack) {
2992 if (ExplicitArgs)
2993 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2994 if (NumExplicitArgs)
2995 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2996
2997 return Current->PartiallySubstitutedPack;
2998 }
2999
3000 if (!Current->CombineWithOuterScope)
3001 break;
3002 }
3003
3004 return nullptr;
3005}

/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/TreeTransform.h

1//===------- TreeTransform.h - Semantic Tree Transformation -----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===//
8//
9// This file implements a semantic tree transformation that takes a given
10// AST and rebuilds it, possibly transforming some nodes in the process.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15#define LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
16
17#include "CoroutineStmtBuilder.h"
18#include "TypeLocBuilder.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExprOpenMP.h"
26#include "clang/AST/Stmt.h"
27#include "clang/AST/StmtCXX.h"
28#include "clang/AST/StmtObjC.h"
29#include "clang/AST/StmtOpenMP.h"
30#include "clang/Sema/Designator.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Ownership.h"
33#include "clang/Sema/ParsedTemplate.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/SemaDiagnostic.h"
36#include "clang/Sema/SemaInternal.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/Support/ErrorHandling.h"
39#include <algorithm>
40
41namespace clang {
42using namespace sema;
43
44/// A semantic tree transformation that allows one to transform one
45/// abstract syntax tree into another.
46///
47/// A new tree transformation is defined by creating a new subclass \c X of
48/// \c TreeTransform<X> and then overriding certain operations to provide
49/// behavior specific to that transformation. For example, template
50/// instantiation is implemented as a tree transformation where the
51/// transformation of TemplateTypeParmType nodes involves substituting the
52/// template arguments for their corresponding template parameters; a similar
53/// transformation is performed for non-type template parameters and
54/// template template parameters.
55///
56/// This tree-transformation template uses static polymorphism to allow
57/// subclasses to customize any of its operations. Thus, a subclass can
58/// override any of the transformation or rebuild operators by providing an
59/// operation with the same signature as the default implementation. The
60/// overriding function should not be virtual.
61///
62/// Semantic tree transformations are split into two stages, either of which
63/// can be replaced by a subclass. The "transform" step transforms an AST node
64/// or the parts of an AST node using the various transformation functions,
65/// then passes the pieces on to the "rebuild" step, which constructs a new AST
66/// node of the appropriate kind from the pieces. The default transformation
67/// routines recursively transform the operands to composite AST nodes (e.g.,
68/// the pointee type of a PointerType node) and, if any of those operand nodes
69/// were changed by the transformation, invokes the rebuild operation to create
70/// a new AST node.
71///
72/// Subclasses can customize the transformation at various levels. The
73/// most coarse-grained transformations involve replacing TransformType(),
74/// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
75/// TransformTemplateName(), or TransformTemplateArgument() with entirely
76/// new implementations.
77///
78/// For more fine-grained transformations, subclasses can replace any of the
79/// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
80/// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
81/// replacing TransformTemplateTypeParmType() allows template instantiation
82/// to substitute template arguments for their corresponding template
83/// parameters. Additionally, subclasses can override the \c RebuildXXX
84/// functions to control how AST nodes are rebuilt when their operands change.
85/// By default, \c TreeTransform will invoke semantic analysis to rebuild
86/// AST nodes. However, certain other tree transformations (e.g, cloning) may
87/// be able to use more efficient rebuild steps.
88///
89/// There are a handful of other functions that can be overridden, allowing one
90/// to avoid traversing nodes that don't need any transformation
91/// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
92/// operands have not changed (\c AlwaysRebuild()), and customize the
93/// default locations and entity names used for type-checking
94/// (\c getBaseLocation(), \c getBaseEntity()).
95template<typename Derived>
96class TreeTransform {
97 /// Private RAII object that helps us forget and then re-remember
98 /// the template argument corresponding to a partially-substituted parameter
99 /// pack.
100 class ForgetPartiallySubstitutedPackRAII {
101 Derived &Self;
102 TemplateArgument Old;
103
104 public:
105 ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
106 Old = Self.ForgetPartiallySubstitutedPack();
107 }
108
109 ~ForgetPartiallySubstitutedPackRAII() {
110 Self.RememberPartiallySubstitutedPack(Old);
111 }
112 };
113
114protected:
115 Sema &SemaRef;
116
117 /// The set of local declarations that have been transformed, for
118 /// cases where we are forced to build new declarations within the transformer
119 /// rather than in the subclass (e.g., lambda closure types).
120 llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
121
122public:
123 /// Initializes a new tree transformer.
124 TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
125
126 /// Retrieves a reference to the derived class.
127 Derived &getDerived() { return static_cast<Derived&>(*this); }
128
129 /// Retrieves a reference to the derived class.
130 const Derived &getDerived() const {
131 return static_cast<const Derived&>(*this);
132 }
133
134 static inline ExprResult Owned(Expr *E) { return E; }
135 static inline StmtResult Owned(Stmt *S) { return S; }
136
137 /// Retrieves a reference to the semantic analysis object used for
138 /// this tree transform.
139 Sema &getSema() const { return SemaRef; }
140
141 /// Whether the transformation should always rebuild AST nodes, even
142 /// if none of the children have changed.
143 ///
144 /// Subclasses may override this function to specify when the transformation
145 /// should rebuild all AST nodes.
146 ///
147 /// We must always rebuild all AST nodes when performing variadic template
148 /// pack expansion, in order to avoid violating the AST invariant that each
149 /// statement node appears at most once in its containing declaration.
150 bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
151
152 /// Returns the location of the entity being transformed, if that
153 /// information was not available elsewhere in the AST.
154 ///
155 /// By default, returns no source-location information. Subclasses can
156 /// provide an alternative implementation that provides better location
157 /// information.
158 SourceLocation getBaseLocation() { return SourceLocation(); }
159
160 /// Returns the name of the entity being transformed, if that
161 /// information was not available elsewhere in the AST.
162 ///
163 /// By default, returns an empty name. Subclasses can provide an alternative
164 /// implementation with a more precise name.
165 DeclarationName getBaseEntity() { return DeclarationName(); }
166
167 /// Sets the "base" location and entity when that
168 /// information is known based on another transformation.
169 ///
170 /// By default, the source location and entity are ignored. Subclasses can
171 /// override this function to provide a customized implementation.
172 void setBase(SourceLocation Loc, DeclarationName Entity) { }
173
174 /// RAII object that temporarily sets the base location and entity
175 /// used for reporting diagnostics in types.
176 class TemporaryBase {
177 TreeTransform &Self;
178 SourceLocation OldLocation;
179 DeclarationName OldEntity;
180
181 public:
182 TemporaryBase(TreeTransform &Self, SourceLocation Location,
183 DeclarationName Entity) : Self(Self) {
184 OldLocation = Self.getDerived().getBaseLocation();
185 OldEntity = Self.getDerived().getBaseEntity();
186
187 if (Location.isValid())
188 Self.getDerived().setBase(Location, Entity);
189 }
190
191 ~TemporaryBase() {
192 Self.getDerived().setBase(OldLocation, OldEntity);
193 }
194 };
195
196 /// Determine whether the given type \p T has already been
197 /// transformed.
198 ///
199 /// Subclasses can provide an alternative implementation of this routine
200 /// to short-circuit evaluation when it is known that a given type will
201 /// not change. For example, template instantiation need not traverse
202 /// non-dependent types.
203 bool AlreadyTransformed(QualType T) {
204 return T.isNull();
205 }
206
207 /// Determine whether the given call argument should be dropped, e.g.,
208 /// because it is a default argument.
209 ///
210 /// Subclasses can provide an alternative implementation of this routine to
211 /// determine which kinds of call arguments get dropped. By default,
212 /// CXXDefaultArgument nodes are dropped (prior to transformation).
213 bool DropCallArgument(Expr *E) {
214 return E->isDefaultArgument();
215 }
216
217 /// Determine whether we should expand a pack expansion with the
218 /// given set of parameter packs into separate arguments by repeatedly
219 /// transforming the pattern.
220 ///
221 /// By default, the transformer never tries to expand pack expansions.
222 /// Subclasses can override this routine to provide different behavior.
223 ///
224 /// \param EllipsisLoc The location of the ellipsis that identifies the
225 /// pack expansion.
226 ///
227 /// \param PatternRange The source range that covers the entire pattern of
228 /// the pack expansion.
229 ///
230 /// \param Unexpanded The set of unexpanded parameter packs within the
231 /// pattern.
232 ///
233 /// \param ShouldExpand Will be set to \c true if the transformer should
234 /// expand the corresponding pack expansions into separate arguments. When
235 /// set, \c NumExpansions must also be set.
236 ///
237 /// \param RetainExpansion Whether the caller should add an unexpanded
238 /// pack expansion after all of the expanded arguments. This is used
239 /// when extending explicitly-specified template argument packs per
240 /// C++0x [temp.arg.explicit]p9.
241 ///
242 /// \param NumExpansions The number of separate arguments that will be in
243 /// the expanded form of the corresponding pack expansion. This is both an
244 /// input and an output parameter, which can be set by the caller if the
245 /// number of expansions is known a priori (e.g., due to a prior substitution)
246 /// and will be set by the callee when the number of expansions is known.
247 /// The callee must set this value when \c ShouldExpand is \c true; it may
248 /// set this value in other cases.
249 ///
250 /// \returns true if an error occurred (e.g., because the parameter packs
251 /// are to be instantiated with arguments of different lengths), false
252 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
253 /// must be set.
254 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
255 SourceRange PatternRange,
256 ArrayRef<UnexpandedParameterPack> Unexpanded,
257 bool &ShouldExpand,
258 bool &RetainExpansion,
259 Optional<unsigned> &NumExpansions) {
260 ShouldExpand = false;
261 return false;
262 }
263
264 /// "Forget" about the partially-substituted pack template argument,
265 /// when performing an instantiation that must preserve the parameter pack
266 /// use.
267 ///
268 /// This routine is meant to be overridden by the template instantiator.
269 TemplateArgument ForgetPartiallySubstitutedPack() {
270 return TemplateArgument();
271 }
272
273 /// "Remember" the partially-substituted pack template argument
274 /// after performing an instantiation that must preserve the parameter pack
275 /// use.
276 ///
277 /// This routine is meant to be overridden by the template instantiator.
278 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
279
280 /// Note to the derived class when a function parameter pack is
281 /// being expanded.
282 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
283
284 /// Transforms the given type into another type.
285 ///
286 /// By default, this routine transforms a type by creating a
287 /// TypeSourceInfo for it and delegating to the appropriate
288 /// function. This is expensive, but we don't mind, because
289 /// this method is deprecated anyway; all users should be
290 /// switched to storing TypeSourceInfos.
291 ///
292 /// \returns the transformed type.
293 QualType TransformType(QualType T);
294
295 /// Transforms the given type-with-location into a new
296 /// type-with-location.
297 ///
298 /// By default, this routine transforms a type by delegating to the
299 /// appropriate TransformXXXType to build a new type. Subclasses
300 /// may override this function (to take over all type
301 /// transformations) or some set of the TransformXXXType functions
302 /// to alter the transformation.
303 TypeSourceInfo *TransformType(TypeSourceInfo *DI);
304
305 /// Transform the given type-with-location into a new
306 /// type, collecting location information in the given builder
307 /// as necessary.
308 ///
309 QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
310
311 /// Transform a type that is permitted to produce a
312 /// DeducedTemplateSpecializationType.
313 ///
314 /// This is used in the (relatively rare) contexts where it is acceptable
315 /// for transformation to produce a class template type with deduced
316 /// template arguments.
317 /// @{
318 QualType TransformTypeWithDeducedTST(QualType T);
319 TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
320 /// @}
321
322 /// Transform the given statement.
323 ///
324 /// By default, this routine transforms a statement by delegating to the
325 /// appropriate TransformXXXStmt function to transform a specific kind of
326 /// statement or the TransformExpr() function to transform an expression.
327 /// Subclasses may override this function to transform statements using some
328 /// other mechanism.
329 ///
330 /// \returns the transformed statement.
331 StmtResult TransformStmt(Stmt *S);
332
333 /// Transform the given statement.
334 ///
335 /// By default, this routine transforms a statement by delegating to the
336 /// appropriate TransformOMPXXXClause function to transform a specific kind
337 /// of clause. Subclasses may override this function to transform statements
338 /// using some other mechanism.
339 ///
340 /// \returns the transformed OpenMP clause.
341 OMPClause *TransformOMPClause(OMPClause *S);
342
343 /// Transform the given attribute.
344 ///
345 /// By default, this routine transforms a statement by delegating to the
346 /// appropriate TransformXXXAttr function to transform a specific kind
347 /// of attribute. Subclasses may override this function to transform
348 /// attributed statements using some other mechanism.
349 ///
350 /// \returns the transformed attribute
351 const Attr *TransformAttr(const Attr *S);
352
353/// Transform the specified attribute.
354///
355/// Subclasses should override the transformation of attributes with a pragma
356/// spelling to transform expressions stored within the attribute.
357///
358/// \returns the transformed attribute.
359#define ATTR(X)
360#define PRAGMA_SPELLING_ATTR(X) \
361 const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
362#include "clang/Basic/AttrList.inc"
363
364 /// Transform the given expression.
365 ///
366 /// By default, this routine transforms an expression by delegating to the
367 /// appropriate TransformXXXExpr function to build a new expression.
368 /// Subclasses may override this function to transform expressions using some
369 /// other mechanism.
370 ///
371 /// \returns the transformed expression.
372 ExprResult TransformExpr(Expr *E);
373
374 /// Transform the given initializer.
375 ///
376 /// By default, this routine transforms an initializer by stripping off the
377 /// semantic nodes added by initialization, then passing the result to
378 /// TransformExpr or TransformExprs.
379 ///
380 /// \returns the transformed initializer.
381 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
382
383 /// Transform the given list of expressions.
384 ///
385 /// This routine transforms a list of expressions by invoking
386 /// \c TransformExpr() for each subexpression. However, it also provides
387 /// support for variadic templates by expanding any pack expansions (if the
388 /// derived class permits such expansion) along the way. When pack expansions
389 /// are present, the number of outputs may not equal the number of inputs.
390 ///
391 /// \param Inputs The set of expressions to be transformed.
392 ///
393 /// \param NumInputs The number of expressions in \c Inputs.
394 ///
395 /// \param IsCall If \c true, then this transform is being performed on
396 /// function-call arguments, and any arguments that should be dropped, will
397 /// be.
398 ///
399 /// \param Outputs The transformed input expressions will be added to this
400 /// vector.
401 ///
402 /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
403 /// due to transformation.
404 ///
405 /// \returns true if an error occurred, false otherwise.
406 bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
407 SmallVectorImpl<Expr *> &Outputs,
408 bool *ArgChanged = nullptr);
409
410 /// Transform the given declaration, which is referenced from a type
411 /// or expression.
412 ///
413 /// By default, acts as the identity function on declarations, unless the
414 /// transformer has had to transform the declaration itself. Subclasses
415 /// may override this function to provide alternate behavior.
416 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
417 llvm::DenseMap<Decl *, Decl *>::iterator Known
418 = TransformedLocalDecls.find(D);
419 if (Known != TransformedLocalDecls.end())
420 return Known->second;
421
422 return D;
423 }
424
425 /// Transform the specified condition.
426 ///
427 /// By default, this transforms the variable and expression and rebuilds
428 /// the condition.
429 Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
430 Expr *Expr,
431 Sema::ConditionKind Kind);
432
433 /// Transform the attributes associated with the given declaration and
434 /// place them on the new declaration.
435 ///
436 /// By default, this operation does nothing. Subclasses may override this
437 /// behavior to transform attributes.
438 void transformAttrs(Decl *Old, Decl *New) { }
439
440 /// Note that a local declaration has been transformed by this
441 /// transformer.
442 ///
443 /// Local declarations are typically transformed via a call to
444 /// TransformDefinition. However, in some cases (e.g., lambda expressions),
445 /// the transformer itself has to transform the declarations. This routine
446 /// can be overridden by a subclass that keeps track of such mappings.
447 void transformedLocalDecl(Decl *Old, Decl *New) {
448 TransformedLocalDecls[Old] = New;
449 }
450
451 /// Transform the definition of the given declaration.
452 ///
453 /// By default, invokes TransformDecl() to transform the declaration.
454 /// Subclasses may override this function to provide alternate behavior.
455 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
456 return getDerived().TransformDecl(Loc, D);
457 }
458
459 /// Transform the given declaration, which was the first part of a
460 /// nested-name-specifier in a member access expression.
461 ///
462 /// This specific declaration transformation only applies to the first
463 /// identifier in a nested-name-specifier of a member access expression, e.g.,
464 /// the \c T in \c x->T::member
465 ///
466 /// By default, invokes TransformDecl() to transform the declaration.
467 /// Subclasses may override this function to provide alternate behavior.
468 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
469 return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
470 }
471
472 /// Transform the set of declarations in an OverloadExpr.
473 bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
474 LookupResult &R);
475
476 /// Transform the given nested-name-specifier with source-location
477 /// information.
478 ///
479 /// By default, transforms all of the types and declarations within the
480 /// nested-name-specifier. Subclasses may override this function to provide
481 /// alternate behavior.
482 NestedNameSpecifierLoc
483 TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
484 QualType ObjectType = QualType(),
485 NamedDecl *FirstQualifierInScope = nullptr);
486
487 /// Transform the given declaration name.
488 ///
489 /// By default, transforms the types of conversion function, constructor,
490 /// and destructor names and then (if needed) rebuilds the declaration name.
491 /// Identifiers and selectors are returned unmodified. Sublcasses may
492 /// override this function to provide alternate behavior.
493 DeclarationNameInfo
494 TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
495
496 /// Transform the given template name.
497 ///
498 /// \param SS The nested-name-specifier that qualifies the template
499 /// name. This nested-name-specifier must already have been transformed.
500 ///
501 /// \param Name The template name to transform.
502 ///
503 /// \param NameLoc The source location of the template name.
504 ///
505 /// \param ObjectType If we're translating a template name within a member
506 /// access expression, this is the type of the object whose member template
507 /// is being referenced.
508 ///
509 /// \param FirstQualifierInScope If the first part of a nested-name-specifier
510 /// also refers to a name within the current (lexical) scope, this is the
511 /// declaration it refers to.
512 ///
513 /// By default, transforms the template name by transforming the declarations
514 /// and nested-name-specifiers that occur within the template name.
515 /// Subclasses may override this function to provide alternate behavior.
516 TemplateName
517 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
518 SourceLocation NameLoc,
519 QualType ObjectType = QualType(),
520 NamedDecl *FirstQualifierInScope = nullptr,
521 bool AllowInjectedClassName = false);
522
523 /// Transform the given template argument.
524 ///
525 /// By default, this operation transforms the type, expression, or
526 /// declaration stored within the template argument and constructs a
527 /// new template argument from the transformed result. Subclasses may
528 /// override this function to provide alternate behavior.
529 ///
530 /// Returns true if there was an error.
531 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
532 TemplateArgumentLoc &Output,
533 bool Uneval = false);
534
535 /// Transform the given set of template arguments.
536 ///
537 /// By default, this operation transforms all of the template arguments
538 /// in the input set using \c TransformTemplateArgument(), and appends
539 /// the transformed arguments to the output list.
540 ///
541 /// Note that this overload of \c TransformTemplateArguments() is merely
542 /// a convenience function. Subclasses that wish to override this behavior
543 /// should override the iterator-based member template version.
544 ///
545 /// \param Inputs The set of template arguments to be transformed.
546 ///
547 /// \param NumInputs The number of template arguments in \p Inputs.
548 ///
549 /// \param Outputs The set of transformed template arguments output by this
550 /// routine.
551 ///
552 /// Returns true if an error occurred.
553 bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
554 unsigned NumInputs,
555 TemplateArgumentListInfo &Outputs,
556 bool Uneval = false) {
557 return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
558 Uneval);
559 }
560
561 /// Transform the given set of template arguments.
562 ///
563 /// By default, this operation transforms all of the template arguments
564 /// in the input set using \c TransformTemplateArgument(), and appends
565 /// the transformed arguments to the output list.
566 ///
567 /// \param First An iterator to the first template argument.
568 ///
569 /// \param Last An iterator one step past the last template argument.
570 ///
571 /// \param Outputs The set of transformed template arguments output by this
572 /// routine.
573 ///
574 /// Returns true if an error occurred.
575 template<typename InputIterator>
576 bool TransformTemplateArguments(InputIterator First,
577 InputIterator Last,
578 TemplateArgumentListInfo &Outputs,
579 bool Uneval = false);
580
581 /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
582 void InventTemplateArgumentLoc(const TemplateArgument &Arg,
583 TemplateArgumentLoc &ArgLoc);
584
585 /// Fakes up a TypeSourceInfo for a type.
586 TypeSourceInfo *InventTypeSourceInfo(QualType T) {
587 return SemaRef.Context.getTrivialTypeSourceInfo(T,
588 getDerived().getBaseLocation());
589 }
590
591#define ABSTRACT_TYPELOC(CLASS, PARENT)
592#define TYPELOC(CLASS, PARENT) \
593 QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
594#include "clang/AST/TypeLocNodes.def"
595
596 template<typename Fn>
597 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
598 FunctionProtoTypeLoc TL,
599 CXXRecordDecl *ThisContext,
600 unsigned ThisTypeQuals,
601 Fn TransformExceptionSpec);
602
603 bool TransformExceptionSpec(SourceLocation Loc,
604 FunctionProtoType::ExceptionSpecInfo &ESI,
605 SmallVectorImpl<QualType> &Exceptions,
606 bool &Changed);
607
608 StmtResult TransformSEHHandler(Stmt *Handler);
609
610 QualType
611 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
612 TemplateSpecializationTypeLoc TL,
613 TemplateName Template);
614
615 QualType
616 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
617 DependentTemplateSpecializationTypeLoc TL,
618 TemplateName Template,
619 CXXScopeSpec &SS);
620
621 QualType TransformDependentTemplateSpecializationType(
622 TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
623 NestedNameSpecifierLoc QualifierLoc);
624
625 /// Transforms the parameters of a function type into the
626 /// given vectors.
627 ///
628 /// The result vectors should be kept in sync; null entries in the
629 /// variables vector are acceptable.
630 ///
631 /// Return true on error.
632 bool TransformFunctionTypeParams(
633 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
634 const QualType *ParamTypes,
635 const FunctionProtoType::ExtParameterInfo *ParamInfos,
636 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
637 Sema::ExtParameterInfoBuilder &PInfos);
638
639 /// Transforms a single function-type parameter. Return null
640 /// on error.
641 ///
642 /// \param indexAdjustment - A number to add to the parameter's
643 /// scope index; can be negative
644 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
645 int indexAdjustment,
646 Optional<unsigned> NumExpansions,
647 bool ExpectParameterPack);
648
649 QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
650
651 StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
652 ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
653
654 TemplateParameterList *TransformTemplateParameterList(
655 TemplateParameterList *TPL) {
656 return TPL;
657 }
658
659 ExprResult TransformAddressOfOperand(Expr *E);
660
661 ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
662 bool IsAddressOfOperand,
663 TypeSourceInfo **RecoveryTSI);
664
665 ExprResult TransformParenDependentScopeDeclRefExpr(
666 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
667 TypeSourceInfo **RecoveryTSI);
668
669 StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
670
671// FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
672// amount of stack usage with clang.
673#define STMT(Node, Parent) \
674 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
675 StmtResult Transform##Node(Node *S);
676#define EXPR(Node, Parent) \
677 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
678 ExprResult Transform##Node(Node *E);
679#define ABSTRACT_STMT(Stmt)
680#include "clang/AST/StmtNodes.inc"
681
682#define OPENMP_CLAUSE(Name, Class) \
683 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
684 OMPClause *Transform ## Class(Class *S);
685#include "clang/Basic/OpenMPKinds.def"
686
687 /// Build a new qualified type given its unqualified type and type
688 /// qualifiers.
689 ///
690 /// By default, this routine adds type qualifiers only to types that can
691 /// have qualifiers, and silently suppresses those qualifiers that are not
692 /// permitted. Subclasses may override this routine to provide different
693 /// behavior.
694 QualType RebuildQualifiedType(QualType T, SourceLocation Loc,
695 Qualifiers Quals);
696
697 /// Build a new pointer type given its pointee type.
698 ///
699 /// By default, performs semantic analysis when building the pointer type.
700 /// Subclasses may override this routine to provide different behavior.
701 QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
702
703 /// Build a new block pointer type given its pointee type.
704 ///
705 /// By default, performs semantic analysis when building the block pointer
706 /// type. Subclasses may override this routine to provide different behavior.
707 QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
708
709 /// Build a new reference type given the type it references.
710 ///
711 /// By default, performs semantic analysis when building the
712 /// reference type. Subclasses may override this routine to provide
713 /// different behavior.
714 ///
715 /// \param LValue whether the type was written with an lvalue sigil
716 /// or an rvalue sigil.
717 QualType RebuildReferenceType(QualType ReferentType,
718 bool LValue,
719 SourceLocation Sigil);
720
721 /// Build a new member pointer type given the pointee type and the
722 /// class type it refers into.
723 ///
724 /// By default, performs semantic analysis when building the member pointer
725 /// type. Subclasses may override this routine to provide different behavior.
726 QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
727 SourceLocation Sigil);
728
729 QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
730 SourceLocation ProtocolLAngleLoc,
731 ArrayRef<ObjCProtocolDecl *> Protocols,
732 ArrayRef<SourceLocation> ProtocolLocs,
733 SourceLocation ProtocolRAngleLoc);
734
735 /// Build an Objective-C object type.
736 ///
737 /// By default, performs semantic analysis when building the object type.
738 /// Subclasses may override this routine to provide different behavior.
739 QualType RebuildObjCObjectType(QualType BaseType,
740 SourceLocation Loc,
741 SourceLocation TypeArgsLAngleLoc,
742 ArrayRef<TypeSourceInfo *> TypeArgs,
743 SourceLocation TypeArgsRAngleLoc,
744 SourceLocation ProtocolLAngleLoc,
745 ArrayRef<ObjCProtocolDecl *> Protocols,
746 ArrayRef<SourceLocation> ProtocolLocs,
747 SourceLocation ProtocolRAngleLoc);
748
749 /// Build a new Objective-C object pointer type given the pointee type.
750 ///
751 /// By default, directly builds the pointer type, with no additional semantic
752 /// analysis.
753 QualType RebuildObjCObjectPointerType(QualType PointeeType,
754 SourceLocation Star);
755
756 /// Build a new array type given the element type, size
757 /// modifier, size of the array (if known), size expression, and index type
758 /// qualifiers.
759 ///
760 /// By default, performs semantic analysis when building the array type.
761 /// Subclasses may override this routine to provide different behavior.
762 /// Also by default, all of the other Rebuild*Array
763 QualType RebuildArrayType(QualType ElementType,
764 ArrayType::ArraySizeModifier SizeMod,
765 const llvm::APInt *Size,
766 Expr *SizeExpr,
767 unsigned IndexTypeQuals,
768 SourceRange BracketsRange);
769
770 /// Build a new constant array type given the element type, size
771 /// modifier, (known) size of the array, and index type qualifiers.
772 ///
773 /// By default, performs semantic analysis when building the array type.
774 /// Subclasses may override this routine to provide different behavior.
775 QualType RebuildConstantArrayType(QualType ElementType,
776 ArrayType::ArraySizeModifier SizeMod,
777 const llvm::APInt &Size,
778 unsigned IndexTypeQuals,
779 SourceRange BracketsRange);
780
781 /// Build a new incomplete array type given the element type, size
782 /// modifier, and index type qualifiers.
783 ///
784 /// By default, performs semantic analysis when building the array type.
785 /// Subclasses may override this routine to provide different behavior.
786 QualType RebuildIncompleteArrayType(QualType ElementType,
787 ArrayType::ArraySizeModifier SizeMod,
788 unsigned IndexTypeQuals,
789 SourceRange BracketsRange);
790
791 /// Build a new variable-length array type given the element type,
792 /// size modifier, size expression, and index type qualifiers.
793 ///
794 /// By default, performs semantic analysis when building the array type.
795 /// Subclasses may override this routine to provide different behavior.
796 QualType RebuildVariableArrayType(QualType ElementType,
797 ArrayType::ArraySizeModifier SizeMod,
798 Expr *SizeExpr,
799 unsigned IndexTypeQuals,
800 SourceRange BracketsRange);
801
802 /// Build a new dependent-sized array type given the element type,
803 /// size modifier, size expression, and index type qualifiers.
804 ///
805 /// By default, performs semantic analysis when building the array type.
806 /// Subclasses may override this routine to provide different behavior.
807 QualType RebuildDependentSizedArrayType(QualType ElementType,
808 ArrayType::ArraySizeModifier SizeMod,
809 Expr *SizeExpr,
810 unsigned IndexTypeQuals,
811 SourceRange BracketsRange);
812
813 /// Build a new vector type given the element type and
814 /// number of elements.
815 ///
816 /// By default, performs semantic analysis when building the vector type.
817 /// Subclasses may override this routine to provide different behavior.
818 QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
819 VectorType::VectorKind VecKind);
820
821 /// Build a new potentially dependently-sized extended vector type
822 /// given the element type and number of elements.
823 ///
824 /// By default, performs semantic analysis when building the vector type.
825 /// Subclasses may override this routine to provide different behavior.
826 QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
827 SourceLocation AttributeLoc,
828 VectorType::VectorKind);
829
830 /// Build a new extended vector type given the element type and
831 /// number of elements.
832 ///
833 /// By default, performs semantic analysis when building the vector type.
834 /// Subclasses may override this routine to provide different behavior.
835 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
836 SourceLocation AttributeLoc);
837
838 /// Build a new potentially dependently-sized extended vector type
839 /// given the element type and number of elements.
840 ///
841 /// By default, performs semantic analysis when building the vector type.
842 /// Subclasses may override this routine to provide different behavior.
843 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
844 Expr *SizeExpr,
845 SourceLocation AttributeLoc);
846
847 /// Build a new DependentAddressSpaceType or return the pointee
848 /// type variable with the correct address space (retrieved from
849 /// AddrSpaceExpr) applied to it. The former will be returned in cases
850 /// where the address space remains dependent.
851 ///
852 /// By default, performs semantic analysis when building the type with address
853 /// space applied. Subclasses may override this routine to provide different
854 /// behavior.
855 QualType RebuildDependentAddressSpaceType(QualType PointeeType,
856 Expr *AddrSpaceExpr,
857 SourceLocation AttributeLoc);
858
859 /// Build a new function type.
860 ///
861 /// By default, performs semantic analysis when building the function type.
862 /// Subclasses may override this routine to provide different behavior.
863 QualType RebuildFunctionProtoType(QualType T,
864 MutableArrayRef<QualType> ParamTypes,
865 const FunctionProtoType::ExtProtoInfo &EPI);
866
867 /// Build a new unprototyped function type.
868 QualType RebuildFunctionNoProtoType(QualType ResultType);
869
870 /// Rebuild an unresolved typename type, given the decl that
871 /// the UnresolvedUsingTypenameDecl was transformed to.
872 QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
873
874 /// Build a new typedef type.
875 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
876 return SemaRef.Context.getTypeDeclType(Typedef);
877 }
878
879 /// Build a new class/struct/union type.
880 QualType RebuildRecordType(RecordDecl *Record) {
881 return SemaRef.Context.getTypeDeclType(Record);
882 }
883
884 /// Build a new Enum type.
885 QualType RebuildEnumType(EnumDecl *Enum) {
886 return SemaRef.Context.getTypeDeclType(Enum);
887 }
888
889 /// Build a new typeof(expr) type.
890 ///
891 /// By default, performs semantic analysis when building the typeof type.
892 /// Subclasses may override this routine to provide different behavior.
893 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
894
895 /// Build a new typeof(type) type.
896 ///
897 /// By default, builds a new TypeOfType with the given underlying type.
898 QualType RebuildTypeOfType(QualType Underlying);
899
900 /// Build a new unary transform type.
901 QualType RebuildUnaryTransformType(QualType BaseType,
902 UnaryTransformType::UTTKind UKind,
903 SourceLocation Loc);
904
905 /// Build a new C++11 decltype type.
906 ///
907 /// By default, performs semantic analysis when building the decltype type.
908 /// Subclasses may override this routine to provide different behavior.
909 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
910
911 /// Build a new C++11 auto type.
912 ///
913 /// By default, builds a new AutoType with the given deduced type.
914 QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword) {
915 // Note, IsDependent is always false here: we implicitly convert an 'auto'
916 // which has been deduced to a dependent type into an undeduced 'auto', so
917 // that we'll retry deduction after the transformation.
918 return SemaRef.Context.getAutoType(Deduced, Keyword,
919 /*IsDependent*/ false);
920 }
921
922 /// By default, builds a new DeducedTemplateSpecializationType with the given
923 /// deduced type.
924 QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
925 QualType Deduced) {
926 return SemaRef.Context.getDeducedTemplateSpecializationType(
927 Template, Deduced, /*IsDependent*/ false);
928 }
929
930 /// Build a new template specialization type.
931 ///
932 /// By default, performs semantic analysis when building the template
933 /// specialization type. Subclasses may override this routine to provide
934 /// different behavior.
935 QualType RebuildTemplateSpecializationType(TemplateName Template,
936 SourceLocation TemplateLoc,
937 TemplateArgumentListInfo &Args);
938
939 /// Build a new parenthesized type.
940 ///
941 /// By default, builds a new ParenType type from the inner type.
942 /// Subclasses may override this routine to provide different behavior.
943 QualType RebuildParenType(QualType InnerType) {
944 return SemaRef.BuildParenType(InnerType);
945 }
946
947 /// Build a new qualified name type.
948 ///
949 /// By default, builds a new ElaboratedType type from the keyword,
950 /// the nested-name-specifier and the named type.
951 /// Subclasses may override this routine to provide different behavior.
952 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
953 ElaboratedTypeKeyword Keyword,
954 NestedNameSpecifierLoc QualifierLoc,
955 QualType Named) {
956 return SemaRef.Context.getElaboratedType(Keyword,
957 QualifierLoc.getNestedNameSpecifier(),
958 Named);
959 }
960
961 /// Build a new typename type that refers to a template-id.
962 ///
963 /// By default, builds a new DependentNameType type from the
964 /// nested-name-specifier and the given type. Subclasses may override
965 /// this routine to provide different behavior.
966 QualType RebuildDependentTemplateSpecializationType(
967 ElaboratedTypeKeyword Keyword,
968 NestedNameSpecifierLoc QualifierLoc,
969 SourceLocation TemplateKWLoc,
970 const IdentifierInfo *Name,
971 SourceLocation NameLoc,
972 TemplateArgumentListInfo &Args,
973 bool AllowInjectedClassName) {
974 // Rebuild the template name.
975 // TODO: avoid TemplateName abstraction
976 CXXScopeSpec SS;
977 SS.Adopt(QualifierLoc);
978 TemplateName InstName = getDerived().RebuildTemplateName(
979 SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
980 AllowInjectedClassName);
981
982 if (InstName.isNull())
983 return QualType();
984
985 // If it's still dependent, make a dependent specialization.
986 if (InstName.getAsDependentTemplateName())
987 return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
988 QualifierLoc.getNestedNameSpecifier(),
989 Name,
990 Args);
991
992 // Otherwise, make an elaborated type wrapping a non-dependent
993 // specialization.
994 QualType T =
995 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
996 if (T.isNull()) return QualType();
997
998 if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
999 return T;
1000
1001 return SemaRef.Context.getElaboratedType(Keyword,
1002 QualifierLoc.getNestedNameSpecifier(),
1003 T);
1004 }
1005
1006 /// Build a new typename type that refers to an identifier.
1007 ///
1008 /// By default, performs semantic analysis when building the typename type
1009 /// (or elaborated type). Subclasses may override this routine to provide
1010 /// different behavior.
1011 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1012 SourceLocation KeywordLoc,
1013 NestedNameSpecifierLoc QualifierLoc,
1014 const IdentifierInfo *Id,
1015 SourceLocation IdLoc,
1016 bool DeducedTSTContext) {
1017 CXXScopeSpec SS;
1018 SS.Adopt(QualifierLoc);
1019
1020 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1021 // If the name is still dependent, just build a new dependent name type.
1022 if (!SemaRef.computeDeclContext(SS))
1023 return SemaRef.Context.getDependentNameType(Keyword,
1024 QualifierLoc.getNestedNameSpecifier(),
1025 Id);
1026 }
1027
1028 if (Keyword == ETK_None || Keyword == ETK_Typename) {
1029 QualType T = SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1030 *Id, IdLoc);
1031 // If a dependent name resolves to a deduced template specialization type,
1032 // check that we're in one of the syntactic contexts permitting it.
1033 if (!DeducedTSTContext) {
1034 if (auto *Deduced = dyn_cast_or_null<DeducedTemplateSpecializationType>(
1035 T.isNull() ? nullptr : T->getContainedDeducedType())) {
1036 SemaRef.Diag(IdLoc, diag::err_dependent_deduced_tst)
1037 << (int)SemaRef.getTemplateNameKindForDiagnostics(
1038 Deduced->getTemplateName())
1039 << QualType(QualifierLoc.getNestedNameSpecifier()->getAsType(), 0);
1040 if (auto *TD = Deduced->getTemplateName().getAsTemplateDecl())
1041 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
1042 return QualType();
1043 }
1044 }
1045 return T;
1046 }
1047
1048 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1049
1050 // We had a dependent elaborated-type-specifier that has been transformed
1051 // into a non-dependent elaborated-type-specifier. Find the tag we're
1052 // referring to.
1053 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1054 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1055 if (!DC)
1056 return QualType();
1057
1058 if (SemaRef.RequireCompleteDeclContext(SS, DC))
1059 return QualType();
1060
1061 TagDecl *Tag = nullptr;
1062 SemaRef.LookupQualifiedName(Result, DC);
1063 switch (Result.getResultKind()) {
1064 case LookupResult::NotFound:
1065 case LookupResult::NotFoundInCurrentInstantiation:
1066 break;
1067
1068 case LookupResult::Found:
1069 Tag = Result.getAsSingle<TagDecl>();
1070 break;
1071
1072 case LookupResult::FoundOverloaded:
1073 case LookupResult::FoundUnresolvedValue:
1074 llvm_unreachable("Tag lookup cannot find non-tags")::llvm::llvm_unreachable_internal("Tag lookup cannot find non-tags"
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/TreeTransform.h"
, 1074)
;
1075
1076 case LookupResult::Ambiguous:
1077 // Let the LookupResult structure handle ambiguities.
1078 return QualType();
1079 }
1080
1081 if (!Tag) {
1082 // Check where the name exists but isn't a tag type and use that to emit
1083 // better diagnostics.
1084 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1085 SemaRef.LookupQualifiedName(Result, DC);
1086 switch (Result.getResultKind()) {
1087 case LookupResult::Found:
1088 case LookupResult::FoundOverloaded:
1089 case LookupResult::FoundUnresolvedValue: {
1090 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1091 Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1092 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1093 << NTK << Kind;
1094 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1095 break;
1096 }
1097 default:
1098 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1099 << Kind << Id << DC << QualifierLoc.getSourceRange();
1100 break;
1101 }
1102 return QualType();
1103 }
1104
1105 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1106 IdLoc, Id)) {
1107 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1108 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1109 return QualType();
1110 }
1111
1112 // Build the elaborated-type-specifier type.
1113 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1114 return SemaRef.Context.getElaboratedType(Keyword,
1115 QualifierLoc.getNestedNameSpecifier(),
1116 T);
1117 }
1118
1119 /// Build a new pack expansion type.
1120 ///
1121 /// By default, builds a new PackExpansionType type from the given pattern.
1122 /// Subclasses may override this routine to provide different behavior.
1123 QualType RebuildPackExpansionType(QualType Pattern,
1124 SourceRange PatternRange,
1125 SourceLocation EllipsisLoc,
1126 Optional<unsigned> NumExpansions) {
1127 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1128 NumExpansions);
1129 }
1130
1131 /// Build a new atomic type given its value type.
1132 ///
1133 /// By default, performs semantic analysis when building the atomic type.
1134 /// Subclasses may override this routine to provide different behavior.
1135 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1136
1137 /// Build a new pipe type given its value type.
1138 QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1139 bool isReadPipe);
1140
1141 /// Build a new template name given a nested name specifier, a flag
1142 /// indicating whether the "template" keyword was provided, and the template
1143 /// that the template name refers to.
1144 ///
1145 /// By default, builds the new template name directly. Subclasses may override
1146 /// this routine to provide different behavior.
1147 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1148 bool TemplateKW,
1149 TemplateDecl *Template);
1150
1151 /// Build a new template name given a nested name specifier and the
1152 /// name that is referred to as a template.
1153 ///
1154 /// By default, performs semantic analysis to determine whether the name can
1155 /// be resolved to a specific template, then builds the appropriate kind of
1156 /// template name. Subclasses may override this routine to provide different
1157 /// behavior.
1158 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1159 SourceLocation TemplateKWLoc,
1160 const IdentifierInfo &Name,
1161 SourceLocation NameLoc, QualType ObjectType,
1162 NamedDecl *FirstQualifierInScope,
1163 bool AllowInjectedClassName);
1164
1165 /// Build a new template name given a nested name specifier and the
1166 /// overloaded operator name that is referred to as a template.
1167 ///
1168 /// By default, performs semantic analysis to determine whether the name can
1169 /// be resolved to a specific template, then builds the appropriate kind of
1170 /// template name. Subclasses may override this routine to provide different
1171 /// behavior.
1172 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1173 SourceLocation TemplateKWLoc,
1174 OverloadedOperatorKind Operator,
1175 SourceLocation NameLoc, QualType ObjectType,
1176 bool AllowInjectedClassName);
1177
1178 /// Build a new template name given a template template parameter pack
1179 /// and the
1180 ///
1181 /// By default, performs semantic analysis to determine whether the name can
1182 /// be resolved to a specific template, then builds the appropriate kind of
1183 /// template name. Subclasses may override this routine to provide different
1184 /// behavior.
1185 TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1186 const TemplateArgument &ArgPack) {
1187 return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1188 }
1189
1190 /// Build a new compound statement.
1191 ///
1192 /// By default, performs semantic analysis to build the new statement.
1193 /// Subclasses may override this routine to provide different behavior.
1194 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1195 MultiStmtArg Statements,
1196 SourceLocation RBraceLoc,
1197 bool IsStmtExpr) {
1198 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1199 IsStmtExpr);
1200 }
1201
1202 /// Build a new case statement.
1203 ///
1204 /// By default, performs semantic analysis to build the new statement.
1205 /// Subclasses may override this routine to provide different behavior.
1206 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1207 Expr *LHS,
1208 SourceLocation EllipsisLoc,
1209 Expr *RHS,
1210 SourceLocation ColonLoc) {
1211 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1212 ColonLoc);
1213 }
1214
1215 /// Attach the body to a new case statement.
1216 ///
1217 /// By default, performs semantic analysis to build the new statement.
1218 /// Subclasses may override this routine to provide different behavior.
1219 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1220 getSema().ActOnCaseStmtBody(S, Body);
1221 return S;
1222 }
1223
1224 /// Build a new default statement.
1225 ///
1226 /// By default, performs semantic analysis to build the new statement.
1227 /// Subclasses may override this routine to provide different behavior.
1228 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1229 SourceLocation ColonLoc,
1230 Stmt *SubStmt) {
1231 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1232 /*CurScope=*/nullptr);
1233 }
1234
1235 /// Build a new label statement.
1236 ///
1237 /// By default, performs semantic analysis to build the new statement.
1238 /// Subclasses may override this routine to provide different behavior.
1239 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1240 SourceLocation ColonLoc, Stmt *SubStmt) {
1241 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1242 }
1243
1244 /// Build a new label statement.
1245 ///
1246 /// By default, performs semantic analysis to build the new statement.
1247 /// Subclasses may override this routine to provide different behavior.
1248 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1249 ArrayRef<const Attr*> Attrs,
1250 Stmt *SubStmt) {
1251 return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1252 }
1253
1254 /// Build a new "if" statement.
1255 ///
1256 /// By default, performs semantic analysis to build the new statement.
1257 /// Subclasses may override this routine to provide different behavior.
1258 StmtResult RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1259 Sema::ConditionResult Cond, Stmt *Init, Stmt *Then,
1260 SourceLocation ElseLoc, Stmt *Else) {
1261 return getSema().ActOnIfStmt(IfLoc, IsConstexpr, Init, Cond, Then,
1262 ElseLoc, Else);
1263 }
1264
1265 /// Start building a new switch statement.
1266 ///
1267 /// By default, performs semantic analysis to build the new statement.
1268 /// Subclasses may override this routine to provide different behavior.
1269 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc, Stmt *Init,
1270 Sema::ConditionResult Cond) {
1271 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Init, Cond);
1272 }
1273
1274 /// Attach the body to the switch statement.
1275 ///
1276 /// By default, performs semantic analysis to build the new statement.
1277 /// Subclasses may override this routine to provide different behavior.
1278 StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1279 Stmt *Switch, Stmt *Body) {
1280 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1281 }
1282
1283 /// Build a new while statement.
1284 ///
1285 /// By default, performs semantic analysis to build the new statement.
1286 /// Subclasses may override this routine to provide different behavior.
1287 StmtResult RebuildWhileStmt(SourceLocation WhileLoc,
1288 Sema::ConditionResult Cond, Stmt *Body) {
1289 return getSema().ActOnWhileStmt(WhileLoc, Cond, Body);
1290 }
1291
1292 /// Build a new do-while statement.
1293 ///
1294 /// By default, performs semantic analysis to build the new statement.
1295 /// Subclasses may override this routine to provide different behavior.
1296 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1297 SourceLocation WhileLoc, SourceLocation LParenLoc,
1298 Expr *Cond, SourceLocation RParenLoc) {
1299 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1300 Cond, RParenLoc);
1301 }
1302
1303 /// Build a new for statement.
1304 ///
1305 /// By default, performs semantic analysis to build the new statement.
1306 /// Subclasses may override this routine to provide different behavior.
1307 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1308 Stmt *Init, Sema::ConditionResult Cond,
1309 Sema::FullExprArg Inc, SourceLocation RParenLoc,
1310 Stmt *Body) {
1311 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1312 Inc, RParenLoc, Body);
1313 }
1314
1315 /// Build a new goto statement.
1316 ///
1317 /// By default, performs semantic analysis to build the new statement.
1318 /// Subclasses may override this routine to provide different behavior.
1319 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1320 LabelDecl *Label) {
1321 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1322 }
1323
1324 /// Build a new indirect goto statement.
1325 ///
1326 /// By default, performs semantic analysis to build the new statement.
1327 /// Subclasses may override this routine to provide different behavior.
1328 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1329 SourceLocation StarLoc,
1330 Expr *Target) {
1331 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1332 }
1333
1334 /// Build a new return statement.
1335 ///
1336 /// By default, performs semantic analysis to build the new statement.
1337 /// Subclasses may override this routine to provide different behavior.
1338 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1339 return getSema().BuildReturnStmt(ReturnLoc, Result);
1340 }
1341
1342 /// Build a new declaration statement.
1343 ///
1344 /// By default, performs semantic analysis to build the new statement.
1345 /// Subclasses may override this routine to provide different behavior.
1346 StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1347 SourceLocation StartLoc, SourceLocation EndLoc) {
1348 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1349 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1350 }
1351
1352 /// Build a new inline asm statement.
1353 ///
1354 /// By default, performs semantic analysis to build the new statement.
1355 /// Subclasses may override this routine to provide different behavior.
1356 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1357 bool IsVolatile, unsigned NumOutputs,
1358 unsigned NumInputs, IdentifierInfo **Names,
1359 MultiExprArg Constraints, MultiExprArg Exprs,
1360 Expr *AsmString, MultiExprArg Clobbers,
1361 SourceLocation RParenLoc) {
1362 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1363 NumInputs, Names, Constraints, Exprs,
1364 AsmString, Clobbers, RParenLoc);
1365 }
1366
1367 /// Build a new MS style inline asm statement.
1368 ///
1369 /// By default, performs semantic analysis to build the new statement.
1370 /// Subclasses may override this routine to provide different behavior.
1371 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1372 ArrayRef<Token> AsmToks,
1373 StringRef AsmString,
1374 unsigned NumOutputs, unsigned NumInputs,
1375 ArrayRef<StringRef> Constraints,
1376 ArrayRef<StringRef> Clobbers,
1377 ArrayRef<Expr*> Exprs,
1378 SourceLocation EndLoc) {
1379 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1380 NumOutputs, NumInputs,
1381 Constraints, Clobbers, Exprs, EndLoc);
1382 }
1383
1384 /// Build a new co_return statement.
1385 ///
1386 /// By default, performs semantic analysis to build the new statement.
1387 /// Subclasses may override this routine to provide different behavior.
1388 StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1389 bool IsImplicit) {
1390 return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1391 }
1392
1393 /// Build a new co_await expression.
1394 ///
1395 /// By default, performs semantic analysis to build the new expression.
1396 /// Subclasses may override this routine to provide different behavior.
1397 ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1398 bool IsImplicit) {
1399 return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1400 }
1401
1402 /// Build a new co_await expression.
1403 ///
1404 /// By default, performs semantic analysis to build the new expression.
1405 /// Subclasses may override this routine to provide different behavior.
1406 ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1407 Expr *Result,
1408 UnresolvedLookupExpr *Lookup) {
1409 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1410 }
1411
1412 /// Build a new co_yield expression.
1413 ///
1414 /// By default, performs semantic analysis to build the new expression.
1415 /// Subclasses may override this routine to provide different behavior.
1416 ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1417 return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1418 }
1419
1420 StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1421 return getSema().BuildCoroutineBodyStmt(Args);
1422 }
1423
1424 /// Build a new Objective-C \@try statement.
1425 ///
1426 /// By default, performs semantic analysis to build the new statement.
1427 /// Subclasses may override this routine to provide different behavior.
1428 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1429 Stmt *TryBody,
1430 MultiStmtArg CatchStmts,
1431 Stmt *Finally) {
1432 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1433 Finally);
1434 }
1435
1436 /// Rebuild an Objective-C exception declaration.
1437 ///
1438 /// By default, performs semantic analysis to build the new declaration.
1439 /// Subclasses may override this routine to provide different behavior.
1440 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1441 TypeSourceInfo *TInfo, QualType T) {
1442 return getSema().BuildObjCExceptionDecl(TInfo, T,
1443 ExceptionDecl->getInnerLocStart(),
1444 ExceptionDecl->getLocation(),
1445 ExceptionDecl->getIdentifier());
1446 }
1447
1448 /// Build a new Objective-C \@catch statement.
1449 ///
1450 /// By default, performs semantic analysis to build the new statement.
1451 /// Subclasses may override this routine to provide different behavior.
1452 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1453 SourceLocation RParenLoc,
1454 VarDecl *Var,
1455 Stmt *Body) {
1456 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1457 Var, Body);
1458 }
1459
1460 /// Build a new Objective-C \@finally statement.
1461 ///
1462 /// By default, performs semantic analysis to build the new statement.
1463 /// Subclasses may override this routine to provide different behavior.
1464 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1465 Stmt *Body) {
1466 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1467 }
1468
1469 /// Build a new Objective-C \@throw statement.
1470 ///
1471 /// By default, performs semantic analysis to build the new statement.
1472 /// Subclasses may override this routine to provide different behavior.
1473 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1474 Expr *Operand) {
1475 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1476 }
1477
1478 /// Build a new OpenMP executable directive.
1479 ///
1480 /// By default, performs semantic analysis to build the new statement.
1481 /// Subclasses may override this routine to provide different behavior.
1482 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1483 DeclarationNameInfo DirName,
1484 OpenMPDirectiveKind CancelRegion,
1485 ArrayRef<OMPClause *> Clauses,
1486 Stmt *AStmt, SourceLocation StartLoc,
1487 SourceLocation EndLoc) {
1488 return getSema().ActOnOpenMPExecutableDirective(
1489 Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1490 }
1491
1492 /// Build a new OpenMP 'if' clause.
1493 ///
1494 /// By default, performs semantic analysis to build the new OpenMP clause.
1495 /// Subclasses may override this routine to provide different behavior.
1496 OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1497 Expr *Condition, SourceLocation StartLoc,
1498 SourceLocation LParenLoc,
1499 SourceLocation NameModifierLoc,
1500 SourceLocation ColonLoc,
1501 SourceLocation EndLoc) {
1502 return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1503 LParenLoc, NameModifierLoc, ColonLoc,
1504 EndLoc);
1505 }
1506
1507 /// Build a new OpenMP 'final' clause.
1508 ///
1509 /// By default, performs semantic analysis to build the new OpenMP clause.
1510 /// Subclasses may override this routine to provide different behavior.
1511 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1512 SourceLocation LParenLoc,
1513 SourceLocation EndLoc) {
1514 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1515 EndLoc);
1516 }
1517
1518 /// Build a new OpenMP 'num_threads' clause.
1519 ///
1520 /// By default, performs semantic analysis to build the new OpenMP clause.
1521 /// Subclasses may override this routine to provide different behavior.
1522 OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1523 SourceLocation StartLoc,
1524 SourceLocation LParenLoc,
1525 SourceLocation EndLoc) {
1526 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1527 LParenLoc, EndLoc);
1528 }
1529
1530 /// Build a new OpenMP 'safelen' clause.
1531 ///
1532 /// By default, performs semantic analysis to build the new OpenMP clause.
1533 /// Subclasses may override this routine to provide different behavior.
1534 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1535 SourceLocation LParenLoc,
1536 SourceLocation EndLoc) {
1537 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1538 }
1539
1540 /// Build a new OpenMP 'simdlen' clause.
1541 ///
1542 /// By default, performs semantic analysis to build the new OpenMP clause.
1543 /// Subclasses may override this routine to provide different behavior.
1544 OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1545 SourceLocation LParenLoc,
1546 SourceLocation EndLoc) {
1547 return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1548 }
1549
1550 /// Build a new OpenMP 'collapse' clause.
1551 ///
1552 /// By default, performs semantic analysis to build the new OpenMP clause.
1553 /// Subclasses may override this routine to provide different behavior.
1554 OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1555 SourceLocation LParenLoc,
1556 SourceLocation EndLoc) {
1557 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1558 EndLoc);
1559 }
1560
1561 /// Build a new OpenMP 'default' clause.
1562 ///
1563 /// By default, performs semantic analysis to build the new OpenMP clause.
1564 /// Subclasses may override this routine to provide different behavior.
1565 OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
1566 SourceLocation KindKwLoc,
1567 SourceLocation StartLoc,
1568 SourceLocation LParenLoc,
1569 SourceLocation EndLoc) {
1570 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1571 StartLoc, LParenLoc, EndLoc);
1572 }
1573
1574 /// Build a new OpenMP 'proc_bind' clause.
1575 ///
1576 /// By default, performs semantic analysis to build the new OpenMP clause.
1577 /// Subclasses may override this routine to provide different behavior.
1578 OMPClause *RebuildOMPProcBindClause(OpenMPProcBindClauseKind Kind,
1579 SourceLocation KindKwLoc,
1580 SourceLocation StartLoc,
1581 SourceLocation LParenLoc,
1582 SourceLocation EndLoc) {
1583 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1584 StartLoc, LParenLoc, EndLoc);
1585 }
1586
1587 /// Build a new OpenMP 'schedule' clause.
1588 ///
1589 /// By default, performs semantic analysis to build the new OpenMP clause.
1590 /// Subclasses may override this routine to provide different behavior.
1591 OMPClause *RebuildOMPScheduleClause(
1592 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1593 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1594 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1595 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1596 return getSema().ActOnOpenMPScheduleClause(
1597 M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1598 CommaLoc, EndLoc);
1599 }
1600
1601 /// Build a new OpenMP 'ordered' clause.
1602 ///
1603 /// By default, performs semantic analysis to build the new OpenMP clause.
1604 /// Subclasses may override this routine to provide different behavior.
1605 OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1606 SourceLocation EndLoc,
1607 SourceLocation LParenLoc, Expr *Num) {
1608 return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1609 }
1610
1611 /// Build a new OpenMP 'private' clause.
1612 ///
1613 /// By default, performs semantic analysis to build the new OpenMP clause.
1614 /// Subclasses may override this routine to provide different behavior.
1615 OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1616 SourceLocation StartLoc,
1617 SourceLocation LParenLoc,
1618 SourceLocation EndLoc) {
1619 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1620 EndLoc);
1621 }
1622
1623 /// Build a new OpenMP 'firstprivate' clause.
1624 ///
1625 /// By default, performs semantic analysis to build the new OpenMP clause.
1626 /// Subclasses may override this routine to provide different behavior.
1627 OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1628 SourceLocation StartLoc,
1629 SourceLocation LParenLoc,
1630 SourceLocation EndLoc) {
1631 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1632 EndLoc);
1633 }
1634
1635 /// Build a new OpenMP 'lastprivate' clause.
1636 ///
1637 /// By default, performs semantic analysis to build the new OpenMP clause.
1638 /// Subclasses may override this routine to provide different behavior.
1639 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1640 SourceLocation StartLoc,
1641 SourceLocation LParenLoc,
1642 SourceLocation EndLoc) {
1643 return getSema().ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc,
1644 EndLoc);
1645 }
1646
1647 /// Build a new OpenMP 'shared' clause.
1648 ///
1649 /// By default, performs semantic analysis to build the new OpenMP clause.
1650 /// Subclasses may override this routine to provide different behavior.
1651 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1652 SourceLocation StartLoc,
1653 SourceLocation LParenLoc,
1654 SourceLocation EndLoc) {
1655 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1656 EndLoc);
1657 }
1658
1659 /// Build a new OpenMP 'reduction' clause.
1660 ///
1661 /// By default, performs semantic analysis to build the new statement.
1662 /// Subclasses may override this routine to provide different behavior.
1663 OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
1664 SourceLocation StartLoc,
1665 SourceLocation LParenLoc,
1666 SourceLocation ColonLoc,
1667 SourceLocation EndLoc,
1668 CXXScopeSpec &ReductionIdScopeSpec,
1669 const DeclarationNameInfo &ReductionId,
1670 ArrayRef<Expr *> UnresolvedReductions) {
1671 return getSema().ActOnOpenMPReductionClause(
1672 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1673 ReductionId, UnresolvedReductions);
1674 }
1675
1676 /// Build a new OpenMP 'task_reduction' clause.
1677 ///
1678 /// By default, performs semantic analysis to build the new statement.
1679 /// Subclasses may override this routine to provide different behavior.
1680 OMPClause *RebuildOMPTaskReductionClause(
1681 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1682 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1683 CXXScopeSpec &ReductionIdScopeSpec,
1684 const DeclarationNameInfo &ReductionId,
1685 ArrayRef<Expr *> UnresolvedReductions) {
1686 return getSema().ActOnOpenMPTaskReductionClause(
1687 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1688 ReductionId, UnresolvedReductions);
1689 }
1690
1691 /// Build a new OpenMP 'in_reduction' clause.
1692 ///
1693 /// By default, performs semantic analysis to build the new statement.
1694 /// Subclasses may override this routine to provide different behavior.
1695 OMPClause *
1696 RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1697 SourceLocation LParenLoc, SourceLocation ColonLoc,
1698 SourceLocation EndLoc,
1699 CXXScopeSpec &ReductionIdScopeSpec,
1700 const DeclarationNameInfo &ReductionId,
1701 ArrayRef<Expr *> UnresolvedReductions) {
1702 return getSema().ActOnOpenMPInReductionClause(
1703 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1704 ReductionId, UnresolvedReductions);
1705 }
1706
1707 /// Build a new OpenMP 'linear' clause.
1708 ///
1709 /// By default, performs semantic analysis to build the new OpenMP clause.
1710 /// Subclasses may override this routine to provide different behavior.
1711 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1712 SourceLocation StartLoc,
1713 SourceLocation LParenLoc,
1714 OpenMPLinearClauseKind Modifier,
1715 SourceLocation ModifierLoc,
1716 SourceLocation ColonLoc,
1717 SourceLocation EndLoc) {
1718 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1719 Modifier, ModifierLoc, ColonLoc,
1720 EndLoc);
1721 }
1722
1723 /// Build a new OpenMP 'aligned' clause.
1724 ///
1725 /// By default, performs semantic analysis to build the new OpenMP clause.
1726 /// Subclasses may override this routine to provide different behavior.
1727 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1728 SourceLocation StartLoc,
1729 SourceLocation LParenLoc,
1730 SourceLocation ColonLoc,
1731 SourceLocation EndLoc) {
1732 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1733 LParenLoc, ColonLoc, EndLoc);
1734 }
1735
1736 /// Build a new OpenMP 'copyin' clause.
1737 ///
1738 /// By default, performs semantic analysis to build the new OpenMP clause.
1739 /// Subclasses may override this routine to provide different behavior.
1740 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1741 SourceLocation StartLoc,
1742 SourceLocation LParenLoc,
1743 SourceLocation EndLoc) {
1744 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1745 EndLoc);
1746 }
1747
1748 /// Build a new OpenMP 'copyprivate' clause.
1749 ///
1750 /// By default, performs semantic analysis to build the new OpenMP clause.
1751 /// Subclasses may override this routine to provide different behavior.
1752 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1753 SourceLocation StartLoc,
1754 SourceLocation LParenLoc,
1755 SourceLocation EndLoc) {
1756 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1757 EndLoc);
1758 }
1759
1760 /// Build a new OpenMP 'flush' pseudo clause.
1761 ///
1762 /// By default, performs semantic analysis to build the new OpenMP clause.
1763 /// Subclasses may override this routine to provide different behavior.
1764 OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1765 SourceLocation StartLoc,
1766 SourceLocation LParenLoc,
1767 SourceLocation EndLoc) {
1768 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1769 EndLoc);
1770 }
1771
1772 /// Build a new OpenMP 'depend' pseudo clause.
1773 ///
1774 /// By default, performs semantic analysis to build the new OpenMP clause.
1775 /// Subclasses may override this routine to provide different behavior.
1776 OMPClause *
1777 RebuildOMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
1778 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1779 SourceLocation StartLoc, SourceLocation LParenLoc,
1780 SourceLocation EndLoc) {
1781 return getSema().ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList,
1782 StartLoc, LParenLoc, EndLoc);
1783 }
1784
1785 /// Build a new OpenMP 'device' clause.
1786 ///
1787 /// By default, performs semantic analysis to build the new statement.
1788 /// Subclasses may override this routine to provide different behavior.
1789 OMPClause *RebuildOMPDeviceClause(Expr *Device, SourceLocation StartLoc,
1790 SourceLocation LParenLoc,
1791 SourceLocation EndLoc) {
1792 return getSema().ActOnOpenMPDeviceClause(Device, StartLoc, LParenLoc,
1793 EndLoc);
1794 }
1795
1796 /// Build a new OpenMP 'map' clause.
1797 ///
1798 /// By default, performs semantic analysis to build the new OpenMP clause.
1799 /// Subclasses may override this routine to provide different behavior.
1800 OMPClause *
1801 RebuildOMPMapClause(OpenMPMapClauseKind MapTypeModifier,
1802 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1803 SourceLocation MapLoc, SourceLocation ColonLoc,
1804 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1805 SourceLocation LParenLoc, SourceLocation EndLoc) {
1806 return getSema().ActOnOpenMPMapClause(MapTypeModifier, MapType,
1807 IsMapTypeImplicit, MapLoc, ColonLoc,
1808 VarList, StartLoc, LParenLoc, EndLoc);
1809 }
1810
1811 /// Build a new OpenMP 'num_teams' clause.
1812 ///
1813 /// By default, performs semantic analysis to build the new statement.
1814 /// Subclasses may override this routine to provide different behavior.
1815 OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1816 SourceLocation LParenLoc,
1817 SourceLocation EndLoc) {
1818 return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1819 EndLoc);
1820 }
1821
1822 /// Build a new OpenMP 'thread_limit' clause.
1823 ///
1824 /// By default, performs semantic analysis to build the new statement.
1825 /// Subclasses may override this routine to provide different behavior.
1826 OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1827 SourceLocation StartLoc,
1828 SourceLocation LParenLoc,
1829 SourceLocation EndLoc) {
1830 return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1831 LParenLoc, EndLoc);
1832 }
1833
1834 /// Build a new OpenMP 'priority' clause.
1835 ///
1836 /// By default, performs semantic analysis to build the new statement.
1837 /// Subclasses may override this routine to provide different behavior.
1838 OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1839 SourceLocation LParenLoc,
1840 SourceLocation EndLoc) {
1841 return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1842 EndLoc);
1843 }
1844
1845 /// Build a new OpenMP 'grainsize' clause.
1846 ///
1847 /// By default, performs semantic analysis to build the new statement.
1848 /// Subclasses may override this routine to provide different behavior.
1849 OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1850 SourceLocation LParenLoc,
1851 SourceLocation EndLoc) {
1852 return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1853 EndLoc);
1854 }
1855
1856 /// Build a new OpenMP 'num_tasks' clause.
1857 ///
1858 /// By default, performs semantic analysis to build the new statement.
1859 /// Subclasses may override this routine to provide different behavior.
1860 OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
1861 SourceLocation LParenLoc,
1862 SourceLocation EndLoc) {
1863 return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
1864 EndLoc);
1865 }
1866
1867 /// Build a new OpenMP 'hint' clause.
1868 ///
1869 /// By default, performs semantic analysis to build the new statement.
1870 /// Subclasses may override this routine to provide different behavior.
1871 OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
1872 SourceLocation LParenLoc,
1873 SourceLocation EndLoc) {
1874 return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
1875 }
1876
1877 /// Build a new OpenMP 'dist_schedule' clause.
1878 ///
1879 /// By default, performs semantic analysis to build the new OpenMP clause.
1880 /// Subclasses may override this routine to provide different behavior.
1881 OMPClause *
1882 RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
1883 Expr *ChunkSize, SourceLocation StartLoc,
1884 SourceLocation LParenLoc, SourceLocation KindLoc,
1885 SourceLocation CommaLoc, SourceLocation EndLoc) {
1886 return getSema().ActOnOpenMPDistScheduleClause(
1887 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
1888 }
1889
1890 /// Build a new OpenMP 'to' clause.
1891 ///
1892 /// By default, performs semantic analysis to build the new statement.
1893 /// Subclasses may override this routine to provide different behavior.
1894 OMPClause *RebuildOMPToClause(ArrayRef<Expr *> VarList,
1895 SourceLocation StartLoc,
1896 SourceLocation LParenLoc,
1897 SourceLocation EndLoc) {
1898 return getSema().ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
1899 }
1900
1901 /// Build a new OpenMP 'from' clause.
1902 ///
1903 /// By default, performs semantic analysis to build the new statement.
1904 /// Subclasses may override this routine to provide different behavior.
1905 OMPClause *RebuildOMPFromClause(ArrayRef<Expr *> VarList,
1906 SourceLocation StartLoc,
1907 SourceLocation LParenLoc,
1908 SourceLocation EndLoc) {
1909 return getSema().ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc,
1910 EndLoc);
1911 }
1912
1913 /// Build a new OpenMP 'use_device_ptr' clause.
1914 ///
1915 /// By default, performs semantic analysis to build the new OpenMP clause.
1916 /// Subclasses may override this routine to provide different behavior.
1917 OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
1918 SourceLocation StartLoc,
1919 SourceLocation LParenLoc,
1920 SourceLocation EndLoc) {
1921 return getSema().ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc,
1922 EndLoc);
1923 }
1924
1925 /// Build a new OpenMP 'is_device_ptr' clause.
1926 ///
1927 /// By default, performs semantic analysis to build the new OpenMP clause.
1928 /// Subclasses may override this routine to provide different behavior.
1929 OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
1930 SourceLocation StartLoc,
1931 SourceLocation LParenLoc,
1932 SourceLocation EndLoc) {
1933 return getSema().ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc,
1934 EndLoc);
1935 }
1936
1937 /// Rebuild the operand to an Objective-C \@synchronized statement.
1938 ///
1939 /// By default, performs semantic analysis to build the new statement.
1940 /// Subclasses may override this routine to provide different behavior.
1941 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
1942 Expr *object) {
1943 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
1944 }
1945
1946 /// Build a new Objective-C \@synchronized statement.
1947 ///
1948 /// By default, performs semantic analysis to build the new statement.
1949 /// Subclasses may override this routine to provide different behavior.
1950 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
1951 Expr *Object, Stmt *Body) {
1952 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
1953 }
1954
1955 /// Build a new Objective-C \@autoreleasepool statement.
1956 ///
1957 /// By default, performs semantic analysis to build the new statement.
1958 /// Subclasses may override this routine to provide different behavior.
1959 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
1960 Stmt *Body) {
1961 return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
1962 }
1963
1964 /// Build a new Objective-C fast enumeration statement.
1965 ///
1966 /// By default, performs semantic analysis to build the new statement.
1967 /// Subclasses may override this routine to provide different behavior.
1968 StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
1969 Stmt *Element,
1970 Expr *Collection,
1971 SourceLocation RParenLoc,
1972 Stmt *Body) {
1973 StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
1974 Element,
1975 Collection,
1976 RParenLoc);
1977 if (ForEachStmt.isInvalid())
1978 return StmtError();
1979
1980 return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
1981 }
1982
1983 /// Build a new C++ exception declaration.
1984 ///
1985 /// By default, performs semantic analysis to build the new decaration.
1986 /// Subclasses may override this routine to provide different behavior.
1987 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1988 TypeSourceInfo *Declarator,
1989 SourceLocation StartLoc,
1990 SourceLocation IdLoc,
1991 IdentifierInfo *Id) {
1992 VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
1993 StartLoc, IdLoc, Id);
1994 if (Var)
1995 getSema().CurContext->addDecl(Var);
1996 return Var;
1997 }
1998
1999 /// Build a new C++ catch statement.
2000 ///
2001 /// By default, performs semantic analysis to build the new statement.
2002 /// Subclasses may override this routine to provide different behavior.
2003 StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2004 VarDecl *ExceptionDecl,
2005 Stmt *Handler) {
2006 return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2007 Handler));
2008 }
2009
2010 /// Build a new C++ try statement.
2011 ///
2012 /// By default, performs semantic analysis to build the new statement.
2013 /// Subclasses may override this routine to provide different behavior.
2014 StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2015 ArrayRef<Stmt *> Handlers) {
2016 return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2017 }
2018
2019 /// Build a new C++0x range-based for statement.
2020 ///
2021 /// By default, performs semantic analysis to build the new statement.
2022 /// Subclasses may override this routine to provide different behavior.
2023 StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2024 SourceLocation CoawaitLoc,
2025 SourceLocation ColonLoc,
2026 Stmt *Range, Stmt *Begin, Stmt *End,
2027 Expr *Cond, Expr *Inc,
2028 Stmt *LoopVar,
2029 SourceLocation RParenLoc) {
2030 // If we've just learned that the range is actually an Objective-C
2031 // collection, treat this as an Objective-C fast enumeration loop.
2032 if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2033 if (RangeStmt->isSingleDecl()) {
2034 if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2035 if (RangeVar->isInvalidDecl())
2036 return StmtError();
2037
2038 Expr *RangeExpr = RangeVar->getInit();
2039 if (!RangeExpr->isTypeDependent() &&
2040 RangeExpr->getType()->isObjCObjectPointerType())
2041 return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar, RangeExpr,
2042 RParenLoc);
2043 }
2044 }
2045 }
2046
2047 return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc,
2048 Range, Begin, End,
2049 Cond, Inc, LoopVar, RParenLoc,
2050 Sema::BFRK_Rebuild);
2051 }
2052
2053 /// Build a new C++0x range-based for statement.
2054 ///
2055 /// By default, performs semantic analysis to build the new statement.
2056 /// Subclasses may override this routine to provide different behavior.
2057 StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2058 bool IsIfExists,
2059 NestedNameSpecifierLoc QualifierLoc,
2060 DeclarationNameInfo NameInfo,
2061 Stmt *Nested) {
2062 return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2063 QualifierLoc, NameInfo, Nested);
2064 }
2065
2066 /// Attach body to a C++0x range-based for statement.
2067 ///
2068 /// By default, performs semantic analysis to finish the new statement.
2069 /// Subclasses may override this routine to provide different behavior.
2070 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2071 return getSema().FinishCXXForRangeStmt(ForRange, Body);
2072 }
2073
2074 StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2075 Stmt *TryBlock, Stmt *Handler) {
2076 return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2077 }
2078
2079 StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2080 Stmt *Block) {
2081 return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2082 }
2083
2084 StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2085 return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2086 }
2087
2088 /// Build a new predefined expression.
2089 ///
2090 /// By default, performs semantic analysis to build the new expression.
2091 /// Subclasses may override this routine to provide different behavior.
2092 ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2093 PredefinedExpr::IdentType IT) {
2094 return getSema().BuildPredefinedExpr(Loc, IT);
2095 }
2096
2097 /// Build a new expression that references a declaration.
2098 ///
2099 /// By default, performs semantic analysis to build the new expression.
2100 /// Subclasses may override this routine to provide different behavior.
2101 ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2102 LookupResult &R,
2103 bool RequiresADL) {
2104 return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2105 }
2106
2107
2108 /// Build a new expression that references a declaration.
2109 ///
2110 /// By default, performs semantic analysis to build the new expression.
2111 /// Subclasses may override this routine to provide different behavior.
2112 ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2113 ValueDecl *VD,
2114 const DeclarationNameInfo &NameInfo,
2115 TemplateArgumentListInfo *TemplateArgs) {
2116 CXXScopeSpec SS;
2117 SS.Adopt(QualifierLoc);
2118
2119 // FIXME: loses template args.
2120
2121 return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
2122 }
2123
2124 /// Build a new expression in parentheses.
2125 ///
2126 /// By default, performs semantic analysis to build the new expression.
2127 /// Subclasses may override this routine to provide different behavior.
2128 ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2129 SourceLocation RParen) {
2130 return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2131 }
2132
2133 /// Build a new pseudo-destructor expression.
2134 ///
2135 /// By default, performs semantic analysis to build the new expression.
2136 /// Subclasses may override this routine to provide different behavior.
2137 ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2138 SourceLocation OperatorLoc,
2139 bool isArrow,
2140 CXXScopeSpec &SS,
2141 TypeSourceInfo *ScopeType,
2142 SourceLocation CCLoc,
2143 SourceLocation TildeLoc,
2144 PseudoDestructorTypeStorage Destroyed);
2145
2146 /// Build a new unary operator expression.
2147 ///
2148 /// By default, performs semantic analysis to build the new expression.
2149 /// Subclasses may override this routine to provide different behavior.
2150 ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2151 UnaryOperatorKind Opc,
2152 Expr *SubExpr) {
2153 return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2154 }
2155
2156 /// Build a new builtin offsetof expression.
2157 ///
2158 /// By default, performs semantic analysis to build the new expression.
2159 /// Subclasses may override this routine to provide different behavior.
2160 ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2161 TypeSourceInfo *Type,
2162 ArrayRef<Sema::OffsetOfComponent> Components,
2163 SourceLocation RParenLoc) {
2164 return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2165 RParenLoc);
2166 }
2167
2168 /// Build a new sizeof, alignof or vec_step expression with a
2169 /// type argument.
2170 ///
2171 /// By default, performs semantic analysis to build the new expression.
2172 /// Subclasses may override this routine to provide different behavior.
2173 ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2174 SourceLocation OpLoc,
2175 UnaryExprOrTypeTrait ExprKind,
2176 SourceRange R) {
2177 return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2178 }
2179
2180 /// Build a new sizeof, alignof or vec step expression with an
2181 /// expression argument.
2182 ///
2183 /// By default, performs semantic analysis to build the new expression.
2184 /// Subclasses may override this routine to provide different behavior.
2185 ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2186 UnaryExprOrTypeTrait ExprKind,
2187 SourceRange R) {
2188 ExprResult Result
2189 = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2190 if (Result.isInvalid())
2191 return ExprError();
2192
2193 return Result;
2194 }
2195
2196 /// Build a new array subscript expression.
2197 ///
2198 /// By default, performs semantic analysis to build the new expression.
2199 /// Subclasses may override this routine to provide different behavior.
2200 ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2201 SourceLocation LBracketLoc,
2202 Expr *RHS,
2203 SourceLocation RBracketLoc) {
2204 return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2205 LBracketLoc, RHS,
2206 RBracketLoc);
2207 }
2208
2209 /// Build a new array section expression.
2210 ///
2211 /// By default, performs semantic analysis to build the new expression.
2212 /// Subclasses may override this routine to provide different behavior.
2213 ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2214 Expr *LowerBound,
2215 SourceLocation ColonLoc, Expr *Length,
2216 SourceLocation RBracketLoc) {
2217 return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2218 ColonLoc, Length, RBracketLoc);
2219 }
2220
2221 /// Build a new call expression.
2222 ///
2223 /// By default, performs semantic analysis to build the new expression.
2224 /// Subclasses may override this routine to provide different behavior.
2225 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2226 MultiExprArg Args,
2227 SourceLocation RParenLoc,
2228 Expr *ExecConfig = nullptr) {
2229 return getSema().ActOnCallExpr(/*Scope=*/nullptr, Callee, LParenLoc,
2230 Args, RParenLoc, ExecConfig);
2231 }
2232
2233 /// Build a new member access expression.
2234 ///
2235 /// By default, performs semantic analysis to build the new expression.
2236 /// Subclasses may override this routine to provide different behavior.
2237 ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2238 bool isArrow,
2239 NestedNameSpecifierLoc QualifierLoc,
2240 SourceLocation TemplateKWLoc,
2241 const DeclarationNameInfo &MemberNameInfo,
2242 ValueDecl *Member,
2243 NamedDecl *FoundDecl,
2244 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2245 NamedDecl *FirstQualifierInScope) {
2246 ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2247 isArrow);
2248 if (!Member->getDeclName()) {
2249 // We have a reference to an unnamed field. This is always the
2250 // base of an anonymous struct/union member access, i.e. the
2251 // field is always of record type.
2252 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?\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/TreeTransform.h"
, 2253, __extension__ __PRETTY_FUNCTION__))
2253 "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?\""
, "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/TreeTransform.h"
, 2253, __extension__ __PRETTY_FUNCTION__))
;
2254
2255 BaseResult =
2256 getSema().PerformObjectMemberConversion(BaseResult.get(),
2257 QualifierLoc.getNestedNameSpecifier(),
2258 FoundDecl, Member);
2259 if (BaseResult.isInvalid())
2260 return ExprError();
2261 Base = BaseResult.get();
2262
2263 CXXScopeSpec EmptySS;
2264 return getSema().BuildFieldReferenceExpr(
2265 Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2266 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2267 }
2268
2269 CXXScopeSpec SS;
2270 SS.Adopt(QualifierLoc);
2271
2272 Base = BaseResult.get();
2273 QualType BaseType = Base->getType();
2274
2275 if (isArrow && !BaseType->isPointerType())
2276 return ExprError();
2277
2278 // FIXME: this involves duplicating earlier analysis in a lot of
2279 // cases; we should avoid this when possible.
2280 LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2281 R.addDecl(FoundDecl);
2282 R.resolveKind();
2283
2284 return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2285 SS, TemplateKWLoc,
2286 FirstQualifierInScope,
2287 R, ExplicitTemplateArgs,
2288 /*S*/nullptr);
2289 }
2290
2291 /// Build a new binary operator expression.
2292 ///
2293 /// By default, performs semantic analysis to build the new expression.
2294 /// Subclasses may override this routine to provide different behavior.
2295 ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2296 BinaryOperatorKind Opc,
2297 Expr *LHS, Expr *RHS) {
2298 return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2299 }
2300
2301 /// Build a new conditional operator expression.
2302 ///
2303 /// By default, performs semantic analysis to build the new expression.
2304 /// Subclasses may override this routine to provide different behavior.
2305 ExprResult RebuildConditionalOperator(Expr *Cond,
2306 SourceLocation QuestionLoc,
2307 Expr *LHS,
2308 SourceLocation ColonLoc,
2309 Expr *RHS) {
2310 return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2311 LHS, RHS);
2312 }
2313
2314 /// Build a new C-style cast expression.
2315 ///
2316 /// By default, performs semantic analysis to build the new expression.
2317 /// Subclasses may override this routine to provide different behavior.
2318 ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2319 TypeSourceInfo *TInfo,
2320 SourceLocation RParenLoc,
2321 Expr *SubExpr) {
2322 return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2323 SubExpr);
2324 }
2325
2326 /// Build a new compound literal expression.
2327 ///
2328 /// By default, performs semantic analysis to build the new expression.
2329 /// Subclasses may override this routine to provide different behavior.
2330 ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2331 TypeSourceInfo *TInfo,
2332 SourceLocation RParenLoc,
2333 Expr *Init) {
2334 return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2335 Init);
2336 }
2337
2338 /// Build a new extended vector element access expression.
2339 ///
2340 /// By default, performs semantic analysis to build the new expression.
2341 /// Subclasses may override this routine to provide different behavior.
2342 ExprResult RebuildExtVectorElementExpr(Expr *Base,
2343 SourceLocation OpLoc,
2344 SourceLocation AccessorLoc,
2345 IdentifierInfo &Accessor) {
2346
2347 CXXScopeSpec SS;
2348 DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2349 return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2350 OpLoc, /*IsArrow*/ false,
2351 SS, SourceLocation(),
2352 /*FirstQualifierInScope*/ nullptr,
2353 NameInfo,
2354 /* TemplateArgs */ nullptr,
2355 /*S*/ nullptr);
2356 }
2357
2358 /// Build a new initializer list expression.
2359 ///
2360 /// By default, performs semantic analysis to build the new expression.
2361 /// Subclasses may override this routine to provide different behavior.
2362 ExprResult RebuildInitList(SourceLocation LBraceLoc,
2363 MultiExprArg Inits,
2364 SourceLocation RBraceLoc) {
2365 return SemaRef.ActOnInitList(LBraceLoc, Inits, RBraceLoc);
2366 }
2367
2368 /// Build a new designated initializer expression.
2369 ///
2370 /// By default, performs semantic analysis to build the new expression.
2371 /// Subclasses may override this routine to provide different behavior.
2372 ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2373 MultiExprArg ArrayExprs,
2374 SourceLocation EqualOrColonLoc,
2375 bool GNUSyntax,
2376 Expr *Init) {
2377 ExprResult Result
2378 = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2379 Init);
2380 if (Result.isInvalid())
2381 return ExprError();
2382
2383 return Result;
2384 }
2385
2386 /// Build a new value-initialized expression.
2387 ///
2388 /// By default, builds the implicit value initialization without performing
2389 /// any semantic analysis. Subclasses may override this routine to provide
2390 /// different behavior.
2391 ExprResult RebuildImplicitValueInitExpr(QualType T) {
2392 return new (SemaRef.Context) ImplicitValueInitExpr(T);
2393 }
2394
2395 /// Build a new \c va_arg expression.
2396 ///
2397 /// By default, performs semantic analysis to build the new expression.
2398 /// Subclasses may override this routine to provide different behavior.
2399 ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2400 Expr *SubExpr, TypeSourceInfo *TInfo,
2401 SourceLocation RParenLoc) {
2402 return getSema().BuildVAArgExpr(BuiltinLoc,
2403 SubExpr, TInfo,
2404 RParenLoc);
2405 }
2406
2407 /// Build a new expression list in parentheses.
2408 ///
2409 /// By default, performs semantic analysis to build the new expression.
2410 /// Subclasses may override this routine to provide different behavior.
2411 ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2412 MultiExprArg SubExprs,
2413 SourceLocation RParenLoc) {
2414 return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2415 }
2416
2417 /// Build a new address-of-label expression.
2418 ///
2419 /// By default, performs semantic analysis, using the name of the label
2420 /// rather than attempting to map the label statement itself.
2421 /// Subclasses may override this routine to provide different behavior.
2422 ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2423 SourceLocation LabelLoc, LabelDecl *Label) {
2424 return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2425 }
2426
2427 /// Build a new GNU statement expression.
2428 ///
2429 /// By default, performs semantic analysis to build the new expression.
2430 /// Subclasses may override this routine to provide different behavior.
2431 ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
2432 Stmt *SubStmt,
2433 SourceLocation RParenLoc) {
2434 return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
2435 }
2436
2437 /// Build a new __builtin_choose_expr expression.
2438 ///
2439 /// By default, performs semantic analysis to build the new expression.
2440 /// Subclasses may override this routine to provide different behavior.
2441 ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2442 Expr *Cond, Expr *LHS, Expr *RHS,
2443 SourceLocation RParenLoc) {
2444 return SemaRef.ActOnChooseExpr(BuiltinLoc,
2445 Cond, LHS, RHS,
2446 RParenLoc);
2447 }
2448
2449 /// Build a new generic selection expression.
2450 ///
2451 /// By default, performs semantic analysis to build the new expression.
2452 /// Subclasses may override this routine to provide different behavior.
2453 ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2454 SourceLocation DefaultLoc,
2455 SourceLocation RParenLoc,
2456 Expr *ControllingExpr,
2457 ArrayRef<TypeSourceInfo *> Types,
2458 ArrayRef<Expr *> Exprs) {
2459 return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2460 ControllingExpr, Types, Exprs);
2461 }
2462
2463 /// Build a new overloaded operator call expression.
2464 ///
2465 /// By default, performs semantic analysis to build the new expression.
2466 /// The semantic analysis provides the behavior of template instantiation,
2467 /// copying with transformations that turn what looks like an overloaded
2468 /// operator call into a use of a builtin operator, performing
2469 /// argument-dependent lookup, etc. Subclasses may override this routine to
2470 /// provide different behavior.
2471 ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2472 SourceLocation OpLoc,
2473 Expr *Callee,
2474 Expr *First,
2475 Expr *Second);
2476
2477 /// Build a new C++ "named" cast expression, such as static_cast or
2478 /// reinterpret_cast.
2479 ///
2480 /// By default, this routine dispatches to one of the more-specific routines
2481 /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2482 /// Subclasses may override this routine to provide different behavior.
2483 ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2484 Stmt::StmtClass Class,
2485 SourceLocation LAngleLoc,
2486 TypeSourceInfo *TInfo,
2487 SourceLocation RAngleLoc,
2488 SourceLocation LParenLoc,
2489 Expr *SubExpr,
2490 SourceLocation RParenLoc) {
2491 switch (Class) {
2492 case Stmt::CXXStaticCastExprClass:
2493 return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2494 RAngleLoc, LParenLoc,
2495 SubExpr, RParenLoc);
2496
2497 case Stmt::CXXDynamicCastExprClass:
2498 return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2499 RAngleLoc, LParenLoc,
2500 SubExpr, RParenLoc);
2501
2502 case Stmt::CXXReinterpretCastExprClass:
2503 return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2504 RAngleLoc, LParenLoc,
2505 SubExpr,
2506 RParenLoc);
2507
2508 case Stmt::CXXConstCastExprClass:
2509 return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2510 RAngleLoc, LParenLoc,
2511 SubExpr, RParenLoc);
2512
2513 default:
2514 llvm_unreachable("Invalid C++ named cast")::llvm::llvm_unreachable_internal("Invalid C++ named cast", "/build/llvm-toolchain-snapshot-7~svn338205/tools/clang/lib/Sema/TreeTransform.h"
, 2514)
;
2515 }
2516 }
2517
2518 /// Build a new C++ static_cast expression.
2519 ///
2520 /// By default, performs semantic analysis to build the new expression.
2521 /// Subclasses may override this routine to provide different behavior.
2522 ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2523 SourceLocation LAngleLoc,
2524 TypeSourceInfo *TInfo,
2525 SourceLocation RAngleLoc,
2526 SourceLocation LParenLoc,
2527 Expr *SubExpr,
2528 SourceLocation RParenLoc) {
2529 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2530 TInfo, SubExpr,
2531 SourceRange(LAngleLoc, RAngleLoc),
2532 SourceRange(LParenLoc, RParenLoc));
2533 }
2534
2535 /// Build a new C++ dynamic_cast expression.
2536 ///
2537 /// By default, performs semantic analysis to build the new expression.
2538 /// Subclasses may override this routine to provide different behavior.
2539 ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2540 SourceLocation LAngleLoc,
2541 TypeSourceInfo *TInfo,
2542 SourceLocation RAngleLoc,
2543 SourceLocation LParenLoc,
2544 Expr *SubExpr,
2545 SourceLocation RParenLoc) {
2546 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2547 TInfo, SubExpr,
2548 SourceRange(LAngleLoc, RAngleLoc),
2549 SourceRange(LParenLoc, RParenLoc));
2550 }
2551
2552 /// Build a new C++ reinterpret_cast expression.
2553 ///
2554 /// By default, performs semantic analysis to build the new expression.
2555 /// Subclasses may override this routine to provide different behavior.
2556 ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2557 SourceLocation LAngleLoc,
2558 TypeSourceInfo *TInfo,
2559 SourceLocation RAngleLoc,
2560 SourceLocation LParenLoc,
2561 Expr *SubExpr,
2562 SourceLocation RParenLoc) {
2563 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2564 TInfo, SubExpr,
2565 SourceRange(LAngleLoc, RAngleLoc),
2566 SourceRange(LParenLoc, RParenLoc));
2567 }
2568
2569 /// Build a new C++ const_cast expression.
2570 ///
2571 /// By default, performs semantic analysis to build the new expression.
2572 /// Subclasses may override this routine to provide different behavior.
2573 ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2574 SourceLocation LAngleLoc,
2575 TypeSourceInfo *TInfo,
2576 SourceLocation RAngleLoc,
2577 SourceLocation LParenLoc,
2578 Expr *SubExpr,
2579 SourceLocation RParenLoc) {
2580 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2581 TInfo, SubExpr,
2582 SourceRange(LAngleLoc, RAngleLoc),
2583 SourceRange(LParenLoc, RParenLoc));
2584 }
2585
2586 /// Build a new C++ functional-style cast expression.
2587 ///
2588 /// By default, performs semantic analysis to build the new expression.
2589 /// Subclasses may override this routine to provide different behavior.
2590 ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2591 SourceLocation LParenLoc,
2592 Expr *Sub,
2593 SourceLocation RParenLoc,
2594 bool ListInitialization) {
2595 return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2596 MultiExprArg(&Sub, 1), RParenLoc,
2597 ListInitialization);
2598 }
2599
2600 /// Build a new C++ typeid(type) expression.
2601 ///
2602 /// By default, performs semantic analysis to build the new expression.
2603 /// Subclasses may override this routine to provide different behavior.
2604 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2605 SourceLocation TypeidLoc,
2606 TypeSourceInfo *Operand,
2607 SourceLocation RParenLoc) {
2608 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2609 RParenLoc);
2610 }
2611
2612
2613 /// Build a new C++ typeid(expr) expression.
2614 ///
2615 /// By default, performs semantic analysis to build the new expression.
2616 /// Subclasses may override this routine to provide different behavior.
2617 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2618 SourceLocation TypeidLoc,
2619 Expr *Operand,
2620 SourceLocation RParenLoc) {
2621 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2622 RParenLoc);
2623 }
2624
2625 /// Build a new C++ __uuidof(type) expression.
2626 ///
2627 /// By default, performs semantic analysis to build the new expression.
2628 /// Subclasses may override this routine to provide different behavior.
2629 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2630 SourceLocation TypeidLoc,
2631 TypeSourceInfo *Operand,
2632 SourceLocation RParenLoc) {
2633 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2634 RParenLoc);
2635 }
2636
2637 /// Build a new C++ __uuidof(expr) expression.
2638 ///
2639 /// By default, performs semantic analysis to build the new expression.
2640 /// Subclasses may override this routine to provide different behavior.
2641 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2642 SourceLocation TypeidLoc,
2643 Expr *Operand,
2644 SourceLocation RParenLoc) {
2645 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2646 RParenLoc);
2647 }
2648
2649 /// Build a new C++ "this" expression.
2650 ///
2651 /// By default, builds a new "this" expression without performing any
2652 /// semantic analysis. Subclasses may override this routine to provide
2653 /// different behavior.
2654 ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
2655 QualType ThisType,
2656 bool isImplicit) {
2657 getSema().CheckCXXThisCapture(ThisLoc);
2658 return new (getSema().Context) CXXThisExpr(ThisLoc, ThisType, isImplicit);
2659 }
2660
2661 /// Build a new C++ throw expression.
2662 ///
2663 /// By default, performs semantic analysis to build the new expression.
2664 /// Subclasses may override this routine to provide different behavior.
2665 ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
2666 bool IsThrownVariableInScope) {
2667 return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
2668 }
2669
2670 /// Build a new C++ default-argument expression.
2671 ///
2672 /// By default, builds a new default-argument expression, which does not
2673 /// require any semantic analysis. Subclasses may override this routine to
2674 /// provide different behavior.
2675 ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc,
2676 ParmVarDecl *Param) {
2677 return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param);
2678 }
2679
2680 /// Build a new C++11 default-initialization expression.
2681 ///
2682 /// By default, builds a new default field initialization expression, which
2683 /// does not require any semantic analysis. Subclasses may override this
2684 /// routine to provide different behavior.
2685 ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2686 FieldDecl *Field) {
2687 return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field);
2688 }
2689
2690 /// Build a new C++ zero-initialization expression.
2691 ///
2692 /// By default, performs semantic analysis to build the new expression.
2693 /// Subclasses may override this routine to provide different behavior.
2694 ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2695 SourceLocation LParenLoc,
2696 SourceLocation RParenLoc) {
2697 return getSema().BuildCXXTypeConstructExpr(
2698 TSInfo, LParenLoc, None, RParenLoc, /*ListInitialization=*/false);
2699 }
2700
2701 /// Build a new C++ "new" expression.
2702 ///
2703 /// By default, performs semantic analysis to build the new expression.
2704 /// Subclasses may override this routine to provide different behavior.
2705 ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2706 bool UseGlobal,
2707 SourceLocation PlacementLParen,
2708 MultiExprArg PlacementArgs,
2709 SourceLocation PlacementRParen,
2710 SourceRange TypeIdParens,
2711 QualType AllocatedType,
2712 TypeSourceInfo *AllocatedTypeInfo,
2713 Expr *ArraySize,
2714 SourceRange DirectInitRange,
2715 Expr *Initializer) {
2716 return getSema().BuildCXXNew(StartLoc, UseGlobal,
2717 PlacementLParen,
2718 PlacementArgs,
2719 PlacementRParen,
2720 TypeIdParens,
2721 AllocatedType,
2722 AllocatedTypeInfo,
2723 ArraySize,
2724 DirectInitRange,
2725 Initializer);
2726 }
2727
2728 /// Build a new C++ "delete" expression.
2729 ///
2730 /// By default, performs semantic analysis to build the new expression.
2731 /// Subclasses may override this routine to provide different behavior.
2732 ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
2733 bool IsGlobalDelete,
2734 bool IsArrayForm,
2735 Expr *Operand) {
2736 return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
2737 Operand);
2738 }
2739
2740 /// Build a new type trait expression.
2741 ///
2742 /// By default, performs semantic analysis to build the new expression.
2743 /// Subclasses may override this routine to provide different behavior.
2744 ExprResult RebuildTypeTrait(TypeTrait Trait,
2745 SourceLocation StartLoc,
2746 ArrayRef<TypeSourceInfo *> Args,
2747 SourceLocation RParenLoc) {
2748 return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
2749 }
2750
2751 /// Build a new array type trait expression.
2752 ///
2753 /// By default, performs semantic analysis to build the new expression.
2754 /// Subclasses may override this routine to provide different behavior.
2755 ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
2756 SourceLocation StartLoc,
2757 TypeSourceInfo *TSInfo,
2758 Expr *DimExpr,
2759 SourceLocation RParenLoc) {
2760 return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
2761 }
2762
2763 /// Build a new expression trait expression.
2764 ///
2765 /// By default, performs semantic analysis to build the new expression.
2766 /// Subclasses may override this routine to provide different behavior.
2767 ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
2768 SourceLocation StartLoc,
2769 Expr *Queried,
2770 SourceLocation RParenLoc) {
2771 return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
2772 }
2773
2774 /// Build a new (previously unresolved) declaration reference
2775 /// expression.
2776 ///
2777 /// By default, performs semantic analysis to build the new expression.
2778 /// Subclasses may override this routine to provide different behavior.
2779 ExprResult RebuildDependentScopeDeclRefExpr(
2780 NestedNameSpecifierLoc QualifierLoc,
2781 SourceLocation TemplateKWLoc,
2782 const DeclarationNameInfo &NameInfo,
2783 const TemplateArgumentListInfo *TemplateArgs,
2784 bool IsAddressOfOperand,
2785 TypeSourceInfo **RecoveryTSI) {
2786 CXXScopeSpec SS;
2787 SS.Adopt(QualifierLoc);
2788
2789 if (TemplateArgs || TemplateKWLoc.isValid())
2790 return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
2791 TemplateArgs);
2792
2793 return getSema().BuildQualifiedDeclarationNameExpr(
2794 SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
2795 }
2796
2797 /// Build a new template-id expression.
2798 ///
2799 /// By default, performs semantic analysis to build the new expression.
2800 /// Subclasses may override this routine to provide different behavior.
2801 ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
2802 SourceLocation TemplateKWLoc,
2803 LookupResult &R,
2804 bool RequiresADL,
2805 const TemplateArgumentListInfo *TemplateArgs) {
2806 return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
2807 TemplateArgs);
2808 }
2809
2810 /// Build a new object-construction expression.
2811 ///
2812 /// By default, performs semantic analysis to build the new expression.
2813 /// Subclasses may override this routine to provide different behavior.
2814 ExprResult RebuildCXXConstructExpr(QualType T,
2815 SourceLocation Loc,
2816 CXXConstructorDecl *Constructor,
2817 bool IsElidable,
2818 MultiExprArg Args,
2819 bool HadMultipleCandidates,
2820 bool ListInitialization,
2821 bool StdInitListInitialization,
2822 bool RequiresZeroInit,
2823 CXXConstructExpr::ConstructionKind ConstructKind,
2824 SourceRange ParenRange) {
2825 SmallVector<Expr*, 8> ConvertedArgs;
2826 if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
2827 ConvertedArgs))
2828 return ExprError();
2829
2830 return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
2831 IsElidable,
2832 ConvertedArgs,
2833 HadMultipleCandidates,
2834 ListInitialization,
2835 StdInitListInitialization,
2836 RequiresZeroInit, ConstructKind,
2837 ParenRange);
2838 }
2839
2840 /// Build a new implicit construction via inherited constructor
2841 /// expression.
2842 ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
2843 CXXConstructorDecl *Constructor,
2844 bool ConstructsVBase,
2845 bool InheritedFromVBase) {
2846 return new (getSema().Context) CXXInheritedCtorInitExpr(
2847 Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
2848 }
2849
2850 /// Build a new object-construction 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 RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
2855 SourceLocation LParenOrBraceLoc,
2856 MultiExprArg Args,
2857 SourceLocation RParenOrBraceLoc,
2858 bool ListInitialization) {
2859 return getSema().BuildCXXTypeConstructExpr(
2860 TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
2861 }
2862
2863 /// Build a new object-construction expression.
2864 ///
2865 /// By default, performs semantic analysis to build the new expression.
2866 /// Subclasses may override this routine to provide different behavior.
2867 ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2868 SourceLocation LParenLoc,
2869 MultiExprArg Args,
2870 SourceLocation RParenLoc,
2871 bool ListInitialization) {
2872 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
2873 RParenLoc, ListInitialization);
2874 }
2875
2876 /// Build a new member reference expression.
2877 ///
2878 /// By default, performs semantic analysis to build the new expression.
2879 /// Subclasses may override this routine to provide different behavior.
2880 ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2881 QualType BaseType,
2882 bool IsArrow,
2883 SourceLocation OperatorLoc,
2884 NestedNameSpecifierLoc QualifierLoc,
2885 SourceLocation TemplateKWLoc,
2886 NamedDecl *FirstQualifierInScope,
2887 const DeclarationNameInfo &MemberNameInfo,
2888 const TemplateArgumentListInfo *TemplateArgs) {
2889 CXXScopeSpec SS;
2890 SS.Adopt(QualifierLoc);
2891
2892 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2893 OperatorLoc, IsArrow,
2894 SS, TemplateKWLoc,
2895 FirstQualifierInScope,
2896 MemberNameInfo,
2897 TemplateArgs, /*S*/nullptr);
2898 }
2899
2900 /// Build a new member reference expression.
2901 ///
2902 /// By default, performs semantic analysis to build the new expression.
2903 /// Subclasses may override this routine to provide different behavior.
2904 ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
2905 SourceLocation OperatorLoc,
2906 bool IsArrow,
2907 NestedNameSpecifierLoc QualifierLoc,
2908 SourceLocation TemplateKWLoc,
2909 NamedDecl *FirstQualifierInScope,
2910