Bug Summary

File:tools/clang/lib/Sema/SemaTemplateInstantiate.cpp
Warning:line 5065, column 24
Forming reference to null pointer

Annotated Source Code

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

/build/llvm-toolchain-snapshot-6.0~svn318693/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/// \brief 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/// overridding 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 /// \brief 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 /// \brief 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 /// \brief Initializes a new tree transformer.
124 TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
125
126 /// \brief Retrieves a reference to the derived class.
127 Derived &getDerived() { return static_cast<Derived&>(*this); }
128
129 /// \brief 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 /// \brief Retrieves a reference to the semantic analysis object used for
138 /// this tree transform.
139 Sema &getSema() const { return SemaRef; }
140
141 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief "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 /// \brief "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 /// \brief Note to the derived class when a function parameter pack is
281 /// being expanded.
282 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
283
284 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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/// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief Fakes up a TemplateArgumentLoc for a given TemplateArgument.
582 void InventTemplateArgumentLoc(const TemplateArgument &Arg,
583 TemplateArgumentLoc &ArgLoc);
584
585 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief Build a new extended vector type given the element type and
822 /// 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 RebuildExtVectorType(QualType ElementType, unsigned NumElements,
827 SourceLocation AttributeLoc);
828
829 /// \brief Build a new potentially dependently-sized extended vector type
830 /// given the element type and number of elements.
831 ///
832 /// By default, performs semantic analysis when building the vector type.
833 /// Subclasses may override this routine to provide different behavior.
834 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
835 Expr *SizeExpr,
836 SourceLocation AttributeLoc);
837
838 /// \brief Build a new DependentAddressSpaceType or return the pointee
839 /// type variable with the correct address space (retrieved from
840 /// AddrSpaceExpr) applied to it. The former will be returned in cases
841 /// where the address space remains dependent.
842 ///
843 /// By default, performs semantic analysis when building the type with address
844 /// space applied. Subclasses may override this routine to provide different
845 /// behavior.
846 QualType RebuildDependentAddressSpaceType(QualType PointeeType,
847 Expr *AddrSpaceExpr,
848 SourceLocation AttributeLoc);
849
850 /// \brief Build a new function type.
851 ///
852 /// By default, performs semantic analysis when building the function type.
853 /// Subclasses may override this routine to provide different behavior.
854 QualType RebuildFunctionProtoType(QualType T,
855 MutableArrayRef<QualType> ParamTypes,
856 const FunctionProtoType::ExtProtoInfo &EPI);
857
858 /// \brief Build a new unprototyped function type.
859 QualType RebuildFunctionNoProtoType(QualType ResultType);
860
861 /// \brief Rebuild an unresolved typename type, given the decl that
862 /// the UnresolvedUsingTypenameDecl was transformed to.
863 QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
864
865 /// \brief Build a new typedef type.
866 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
867 return SemaRef.Context.getTypeDeclType(Typedef);
868 }
869
870 /// \brief Build a new class/struct/union type.
871 QualType RebuildRecordType(RecordDecl *Record) {
872 return SemaRef.Context.getTypeDeclType(Record);
873 }
874
875 /// \brief Build a new Enum type.
876 QualType RebuildEnumType(EnumDecl *Enum) {
877 return SemaRef.Context.getTypeDeclType(Enum);
878 }
879
880 /// \brief Build a new typeof(expr) type.
881 ///
882 /// By default, performs semantic analysis when building the typeof type.
883 /// Subclasses may override this routine to provide different behavior.
884 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
885
886 /// \brief Build a new typeof(type) type.
887 ///
888 /// By default, builds a new TypeOfType with the given underlying type.
889 QualType RebuildTypeOfType(QualType Underlying);
890
891 /// \brief Build a new unary transform type.
892 QualType RebuildUnaryTransformType(QualType BaseType,
893 UnaryTransformType::UTTKind UKind,
894 SourceLocation Loc);
895
896 /// \brief Build a new C++11 decltype type.
897 ///
898 /// By default, performs semantic analysis when building the decltype type.
899 /// Subclasses may override this routine to provide different behavior.
900 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
901
902 /// \brief Build a new C++11 auto type.
903 ///
904 /// By default, builds a new AutoType with the given deduced type.
905 QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword) {
906 // Note, IsDependent is always false here: we implicitly convert an 'auto'
907 // which has been deduced to a dependent type into an undeduced 'auto', so
908 // that we'll retry deduction after the transformation.
909 return SemaRef.Context.getAutoType(Deduced, Keyword,
910 /*IsDependent*/ false);
911 }
912
913 /// By default, builds a new DeducedTemplateSpecializationType with the given
914 /// deduced type.
915 QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
916 QualType Deduced) {
917 return SemaRef.Context.getDeducedTemplateSpecializationType(
918 Template, Deduced, /*IsDependent*/ false);
919 }
920
921 /// \brief Build a new template specialization type.
922 ///
923 /// By default, performs semantic analysis when building the template
924 /// specialization type. Subclasses may override this routine to provide
925 /// different behavior.
926 QualType RebuildTemplateSpecializationType(TemplateName Template,
927 SourceLocation TemplateLoc,
928 TemplateArgumentListInfo &Args);
929
930 /// \brief Build a new parenthesized type.
931 ///
932 /// By default, builds a new ParenType type from the inner type.
933 /// Subclasses may override this routine to provide different behavior.
934 QualType RebuildParenType(QualType InnerType) {
935 return SemaRef.BuildParenType(InnerType);
936 }
937
938 /// \brief Build a new qualified name type.
939 ///
940 /// By default, builds a new ElaboratedType type from the keyword,
941 /// the nested-name-specifier and the named type.
942 /// Subclasses may override this routine to provide different behavior.
943 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
944 ElaboratedTypeKeyword Keyword,
945 NestedNameSpecifierLoc QualifierLoc,
946 QualType Named) {
947 return SemaRef.Context.getElaboratedType(Keyword,
948 QualifierLoc.getNestedNameSpecifier(),
949 Named);
950 }
951
952 /// \brief Build a new typename type that refers to a template-id.
953 ///
954 /// By default, builds a new DependentNameType type from the
955 /// nested-name-specifier and the given type. Subclasses may override
956 /// this routine to provide different behavior.
957 QualType RebuildDependentTemplateSpecializationType(
958 ElaboratedTypeKeyword Keyword,
959 NestedNameSpecifierLoc QualifierLoc,
960 const IdentifierInfo *Name,
961 SourceLocation NameLoc,
962 TemplateArgumentListInfo &Args,
963 bool AllowInjectedClassName) {
964 // Rebuild the template name.
965 // TODO: avoid TemplateName abstraction
966 CXXScopeSpec SS;
967 SS.Adopt(QualifierLoc);
968 TemplateName InstName
969 = getDerived().RebuildTemplateName(SS, *Name, NameLoc, QualType(),
970 nullptr, AllowInjectedClassName);
971
972 if (InstName.isNull())
973 return QualType();
974
975 // If it's still dependent, make a dependent specialization.
976 if (InstName.getAsDependentTemplateName())
977 return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
978 QualifierLoc.getNestedNameSpecifier(),
979 Name,
980 Args);
981
982 // Otherwise, make an elaborated type wrapping a non-dependent
983 // specialization.
984 QualType T =
985 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
986 if (T.isNull()) return QualType();
987
988 if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
989 return T;
990
991 return SemaRef.Context.getElaboratedType(Keyword,
992 QualifierLoc.getNestedNameSpecifier(),
993 T);
994 }
995
996 /// \brief Build a new typename type that refers to an identifier.
997 ///
998 /// By default, performs semantic analysis when building the typename type
999 /// (or elaborated type). Subclasses may override this routine to provide
1000 /// different behavior.
1001 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1002 SourceLocation KeywordLoc,
1003 NestedNameSpecifierLoc QualifierLoc,
1004 const IdentifierInfo *Id,
1005 SourceLocation IdLoc,
1006 bool DeducedTSTContext) {
1007 CXXScopeSpec SS;
1008 SS.Adopt(QualifierLoc);
1009
1010 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1011 // If the name is still dependent, just build a new dependent name type.
1012 if (!SemaRef.computeDeclContext(SS))
1013 return SemaRef.Context.getDependentNameType(Keyword,
1014 QualifierLoc.getNestedNameSpecifier(),
1015 Id);
1016 }
1017
1018 if (Keyword == ETK_None || Keyword == ETK_Typename) {
1019 QualType T = SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1020 *Id, IdLoc);
1021 // If a dependent name resolves to a deduced template specialization type,
1022 // check that we're in one of the syntactic contexts permitting it.
1023 if (!DeducedTSTContext) {
1024 if (auto *Deduced = dyn_cast_or_null<DeducedTemplateSpecializationType>(
1025 T.isNull() ? nullptr : T->getContainedDeducedType())) {
1026 SemaRef.Diag(IdLoc, diag::err_dependent_deduced_tst)
1027 << (int)SemaRef.getTemplateNameKindForDiagnostics(
1028 Deduced->getTemplateName())
1029 << QualType(QualifierLoc.getNestedNameSpecifier()->getAsType(), 0);
1030 if (auto *TD = Deduced->getTemplateName().getAsTemplateDecl())
1031 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
1032 return QualType();
1033 }
1034 }
1035 return T;
1036 }
1037
1038 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1039
1040 // We had a dependent elaborated-type-specifier that has been transformed
1041 // into a non-dependent elaborated-type-specifier. Find the tag we're
1042 // referring to.
1043 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1044 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1045 if (!DC)
1046 return QualType();
1047
1048 if (SemaRef.RequireCompleteDeclContext(SS, DC))
1049 return QualType();
1050
1051 TagDecl *Tag = nullptr;
1052 SemaRef.LookupQualifiedName(Result, DC);
1053 switch (Result.getResultKind()) {
1054 case LookupResult::NotFound:
1055 case LookupResult::NotFoundInCurrentInstantiation:
1056 break;
1057
1058 case LookupResult::Found:
1059 Tag = Result.getAsSingle<TagDecl>();
1060 break;
1061
1062 case LookupResult::FoundOverloaded:
1063 case LookupResult::FoundUnresolvedValue:
1064 llvm_unreachable("Tag lookup cannot find non-tags")::llvm::llvm_unreachable_internal("Tag lookup cannot find non-tags"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 1064)
;
1065
1066 case LookupResult::Ambiguous:
1067 // Let the LookupResult structure handle ambiguities.
1068 return QualType();
1069 }
1070
1071 if (!Tag) {
1072 // Check where the name exists but isn't a tag type and use that to emit
1073 // better diagnostics.
1074 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1075 SemaRef.LookupQualifiedName(Result, DC);
1076 switch (Result.getResultKind()) {
1077 case LookupResult::Found:
1078 case LookupResult::FoundOverloaded:
1079 case LookupResult::FoundUnresolvedValue: {
1080 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1081 Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1082 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1083 << NTK << Kind;
1084 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1085 break;
1086 }
1087 default:
1088 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1089 << Kind << Id << DC << QualifierLoc.getSourceRange();
1090 break;
1091 }
1092 return QualType();
1093 }
1094
1095 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1096 IdLoc, Id)) {
1097 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1098 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1099 return QualType();
1100 }
1101
1102 // Build the elaborated-type-specifier type.
1103 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1104 return SemaRef.Context.getElaboratedType(Keyword,
1105 QualifierLoc.getNestedNameSpecifier(),
1106 T);
1107 }
1108
1109 /// \brief Build a new pack expansion type.
1110 ///
1111 /// By default, builds a new PackExpansionType type from the given pattern.
1112 /// Subclasses may override this routine to provide different behavior.
1113 QualType RebuildPackExpansionType(QualType Pattern,
1114 SourceRange PatternRange,
1115 SourceLocation EllipsisLoc,
1116 Optional<unsigned> NumExpansions) {
1117 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1118 NumExpansions);
1119 }
1120
1121 /// \brief Build a new atomic type given its value type.
1122 ///
1123 /// By default, performs semantic analysis when building the atomic type.
1124 /// Subclasses may override this routine to provide different behavior.
1125 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1126
1127 /// \brief Build a new pipe type given its value type.
1128 QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1129 bool isReadPipe);
1130
1131 /// \brief Build a new template name given a nested name specifier, a flag
1132 /// indicating whether the "template" keyword was provided, and the template
1133 /// that the template name refers to.
1134 ///
1135 /// By default, builds the new template name directly. Subclasses may override
1136 /// this routine to provide different behavior.
1137 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1138 bool TemplateKW,
1139 TemplateDecl *Template);
1140
1141 /// \brief Build a new template name given a nested name specifier and the
1142 /// name that is referred to as a template.
1143 ///
1144 /// By default, performs semantic analysis to determine whether the name can
1145 /// be resolved to a specific template, then builds the appropriate kind of
1146 /// template name. Subclasses may override this routine to provide different
1147 /// behavior.
1148 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1149 const IdentifierInfo &Name,
1150 SourceLocation NameLoc,
1151 QualType ObjectType,
1152 NamedDecl *FirstQualifierInScope,
1153 bool AllowInjectedClassName);
1154
1155 /// \brief Build a new template name given a nested name specifier and the
1156 /// overloaded operator name that is referred to as a template.
1157 ///
1158 /// By default, performs semantic analysis to determine whether the name can
1159 /// be resolved to a specific template, then builds the appropriate kind of
1160 /// template name. Subclasses may override this routine to provide different
1161 /// behavior.
1162 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1163 OverloadedOperatorKind Operator,
1164 SourceLocation NameLoc,
1165 QualType ObjectType,
1166 bool AllowInjectedClassName);
1167
1168 /// \brief Build a new template name given a template template parameter pack
1169 /// and the
1170 ///
1171 /// By default, performs semantic analysis to determine whether the name can
1172 /// be resolved to a specific template, then builds the appropriate kind of
1173 /// template name. Subclasses may override this routine to provide different
1174 /// behavior.
1175 TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1176 const TemplateArgument &ArgPack) {
1177 return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1178 }
1179
1180 /// \brief Build a new compound statement.
1181 ///
1182 /// By default, performs semantic analysis to build the new statement.
1183 /// Subclasses may override this routine to provide different behavior.
1184 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1185 MultiStmtArg Statements,
1186 SourceLocation RBraceLoc,
1187 bool IsStmtExpr) {
1188 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1189 IsStmtExpr);
1190 }
1191
1192 /// \brief Build a new case statement.
1193 ///
1194 /// By default, performs semantic analysis to build the new statement.
1195 /// Subclasses may override this routine to provide different behavior.
1196 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1197 Expr *LHS,
1198 SourceLocation EllipsisLoc,
1199 Expr *RHS,
1200 SourceLocation ColonLoc) {
1201 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1202 ColonLoc);
1203 }
1204
1205 /// \brief Attach the body to a new case statement.
1206 ///
1207 /// By default, performs semantic analysis to build the new statement.
1208 /// Subclasses may override this routine to provide different behavior.
1209 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1210 getSema().ActOnCaseStmtBody(S, Body);
1211 return S;
1212 }
1213
1214 /// \brief Build a new default statement.
1215 ///
1216 /// By default, performs semantic analysis to build the new statement.
1217 /// Subclasses may override this routine to provide different behavior.
1218 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1219 SourceLocation ColonLoc,
1220 Stmt *SubStmt) {
1221 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1222 /*CurScope=*/nullptr);
1223 }
1224
1225 /// \brief Build a new label statement.
1226 ///
1227 /// By default, performs semantic analysis to build the new statement.
1228 /// Subclasses may override this routine to provide different behavior.
1229 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1230 SourceLocation ColonLoc, Stmt *SubStmt) {
1231 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1232 }
1233
1234 /// \brief Build a new label statement.
1235 ///
1236 /// By default, performs semantic analysis to build the new statement.
1237 /// Subclasses may override this routine to provide different behavior.
1238 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1239 ArrayRef<const Attr*> Attrs,
1240 Stmt *SubStmt) {
1241 return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1242 }
1243
1244 /// \brief Build a new "if" 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 RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1249 Sema::ConditionResult Cond, Stmt *Init, Stmt *Then,
1250 SourceLocation ElseLoc, Stmt *Else) {
1251 return getSema().ActOnIfStmt(IfLoc, IsConstexpr, Init, Cond, Then,
1252 ElseLoc, Else);
1253 }
1254
1255 /// \brief Start building a new switch statement.
1256 ///
1257 /// By default, performs semantic analysis to build the new statement.
1258 /// Subclasses may override this routine to provide different behavior.
1259 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc, Stmt *Init,
1260 Sema::ConditionResult Cond) {
1261 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Init, Cond);
1262 }
1263
1264 /// \brief Attach the body to the switch statement.
1265 ///
1266 /// By default, performs semantic analysis to build the new statement.
1267 /// Subclasses may override this routine to provide different behavior.
1268 StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1269 Stmt *Switch, Stmt *Body) {
1270 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1271 }
1272
1273 /// \brief Build a new while statement.
1274 ///
1275 /// By default, performs semantic analysis to build the new statement.
1276 /// Subclasses may override this routine to provide different behavior.
1277 StmtResult RebuildWhileStmt(SourceLocation WhileLoc,
1278 Sema::ConditionResult Cond, Stmt *Body) {
1279 return getSema().ActOnWhileStmt(WhileLoc, Cond, Body);
1280 }
1281
1282 /// \brief Build a new do-while statement.
1283 ///
1284 /// By default, performs semantic analysis to build the new statement.
1285 /// Subclasses may override this routine to provide different behavior.
1286 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1287 SourceLocation WhileLoc, SourceLocation LParenLoc,
1288 Expr *Cond, SourceLocation RParenLoc) {
1289 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1290 Cond, RParenLoc);
1291 }
1292
1293 /// \brief Build a new for statement.
1294 ///
1295 /// By default, performs semantic analysis to build the new statement.
1296 /// Subclasses may override this routine to provide different behavior.
1297 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1298 Stmt *Init, Sema::ConditionResult Cond,
1299 Sema::FullExprArg Inc, SourceLocation RParenLoc,
1300 Stmt *Body) {
1301 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1302 Inc, RParenLoc, Body);
1303 }
1304
1305 /// \brief Build a new goto statement.
1306 ///
1307 /// By default, performs semantic analysis to build the new statement.
1308 /// Subclasses may override this routine to provide different behavior.
1309 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1310 LabelDecl *Label) {
1311 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1312 }
1313
1314 /// \brief Build a new indirect goto statement.
1315 ///
1316 /// By default, performs semantic analysis to build the new statement.
1317 /// Subclasses may override this routine to provide different behavior.
1318 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1319 SourceLocation StarLoc,
1320 Expr *Target) {
1321 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1322 }
1323
1324 /// \brief Build a new return 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 RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1329 return getSema().BuildReturnStmt(ReturnLoc, Result);
1330 }
1331
1332 /// \brief Build a new declaration statement.
1333 ///
1334 /// By default, performs semantic analysis to build the new statement.
1335 /// Subclasses may override this routine to provide different behavior.
1336 StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1337 SourceLocation StartLoc, SourceLocation EndLoc) {
1338 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1339 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1340 }
1341
1342 /// \brief Build a new inline asm 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 RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1347 bool IsVolatile, unsigned NumOutputs,
1348 unsigned NumInputs, IdentifierInfo **Names,
1349 MultiExprArg Constraints, MultiExprArg Exprs,
1350 Expr *AsmString, MultiExprArg Clobbers,
1351 SourceLocation RParenLoc) {
1352 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1353 NumInputs, Names, Constraints, Exprs,
1354 AsmString, Clobbers, RParenLoc);
1355 }
1356
1357 /// \brief Build a new MS style inline asm statement.
1358 ///
1359 /// By default, performs semantic analysis to build the new statement.
1360 /// Subclasses may override this routine to provide different behavior.
1361 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1362 ArrayRef<Token> AsmToks,
1363 StringRef AsmString,
1364 unsigned NumOutputs, unsigned NumInputs,
1365 ArrayRef<StringRef> Constraints,
1366 ArrayRef<StringRef> Clobbers,
1367 ArrayRef<Expr*> Exprs,
1368 SourceLocation EndLoc) {
1369 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1370 NumOutputs, NumInputs,
1371 Constraints, Clobbers, Exprs, EndLoc);
1372 }
1373
1374 /// \brief Build a new co_return statement.
1375 ///
1376 /// By default, performs semantic analysis to build the new statement.
1377 /// Subclasses may override this routine to provide different behavior.
1378 StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1379 bool IsImplicit) {
1380 return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1381 }
1382
1383 /// \brief Build a new co_await expression.
1384 ///
1385 /// By default, performs semantic analysis to build the new expression.
1386 /// Subclasses may override this routine to provide different behavior.
1387 ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1388 bool IsImplicit) {
1389 return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1390 }
1391
1392 /// \brief Build a new co_await expression.
1393 ///
1394 /// By default, performs semantic analysis to build the new expression.
1395 /// Subclasses may override this routine to provide different behavior.
1396 ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1397 Expr *Result,
1398 UnresolvedLookupExpr *Lookup) {
1399 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1400 }
1401
1402 /// \brief Build a new co_yield 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 RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1407 return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1408 }
1409
1410 StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1411 return getSema().BuildCoroutineBodyStmt(Args);
1412 }
1413
1414 /// \brief Build a new Objective-C \@try statement.
1415 ///
1416 /// By default, performs semantic analysis to build the new statement.
1417 /// Subclasses may override this routine to provide different behavior.
1418 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1419 Stmt *TryBody,
1420 MultiStmtArg CatchStmts,
1421 Stmt *Finally) {
1422 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1423 Finally);
1424 }
1425
1426 /// \brief Rebuild an Objective-C exception declaration.
1427 ///
1428 /// By default, performs semantic analysis to build the new declaration.
1429 /// Subclasses may override this routine to provide different behavior.
1430 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1431 TypeSourceInfo *TInfo, QualType T) {
1432 return getSema().BuildObjCExceptionDecl(TInfo, T,
1433 ExceptionDecl->getInnerLocStart(),
1434 ExceptionDecl->getLocation(),
1435 ExceptionDecl->getIdentifier());
1436 }
1437
1438 /// \brief Build a new Objective-C \@catch statement.
1439 ///
1440 /// By default, performs semantic analysis to build the new statement.
1441 /// Subclasses may override this routine to provide different behavior.
1442 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1443 SourceLocation RParenLoc,
1444 VarDecl *Var,
1445 Stmt *Body) {
1446 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1447 Var, Body);
1448 }
1449
1450 /// \brief Build a new Objective-C \@finally statement.
1451 ///
1452 /// By default, performs semantic analysis to build the new statement.
1453 /// Subclasses may override this routine to provide different behavior.
1454 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1455 Stmt *Body) {
1456 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1457 }
1458
1459 /// \brief Build a new Objective-C \@throw statement.
1460 ///
1461 /// By default, performs semantic analysis to build the new statement.
1462 /// Subclasses may override this routine to provide different behavior.
1463 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1464 Expr *Operand) {
1465 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1466 }
1467
1468 /// \brief Build a new OpenMP executable directive.
1469 ///
1470 /// By default, performs semantic analysis to build the new statement.
1471 /// Subclasses may override this routine to provide different behavior.
1472 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1473 DeclarationNameInfo DirName,
1474 OpenMPDirectiveKind CancelRegion,
1475 ArrayRef<OMPClause *> Clauses,
1476 Stmt *AStmt, SourceLocation StartLoc,
1477 SourceLocation EndLoc) {
1478 return getSema().ActOnOpenMPExecutableDirective(
1479 Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1480 }
1481
1482 /// \brief Build a new OpenMP 'if' clause.
1483 ///
1484 /// By default, performs semantic analysis to build the new OpenMP clause.
1485 /// Subclasses may override this routine to provide different behavior.
1486 OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1487 Expr *Condition, SourceLocation StartLoc,
1488 SourceLocation LParenLoc,
1489 SourceLocation NameModifierLoc,
1490 SourceLocation ColonLoc,
1491 SourceLocation EndLoc) {
1492 return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1493 LParenLoc, NameModifierLoc, ColonLoc,
1494 EndLoc);
1495 }
1496
1497 /// \brief Build a new OpenMP 'final' clause.
1498 ///
1499 /// By default, performs semantic analysis to build the new OpenMP clause.
1500 /// Subclasses may override this routine to provide different behavior.
1501 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1502 SourceLocation LParenLoc,
1503 SourceLocation EndLoc) {
1504 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1505 EndLoc);
1506 }
1507
1508 /// \brief Build a new OpenMP 'num_threads' clause.
1509 ///
1510 /// By default, performs semantic analysis to build the new OpenMP clause.
1511 /// Subclasses may override this routine to provide different behavior.
1512 OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1513 SourceLocation StartLoc,
1514 SourceLocation LParenLoc,
1515 SourceLocation EndLoc) {
1516 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1517 LParenLoc, EndLoc);
1518 }
1519
1520 /// \brief Build a new OpenMP 'safelen' clause.
1521 ///
1522 /// By default, performs semantic analysis to build the new OpenMP clause.
1523 /// Subclasses may override this routine to provide different behavior.
1524 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1525 SourceLocation LParenLoc,
1526 SourceLocation EndLoc) {
1527 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1528 }
1529
1530 /// \brief Build a new OpenMP 'simdlen' 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 *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1535 SourceLocation LParenLoc,
1536 SourceLocation EndLoc) {
1537 return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1538 }
1539
1540 /// \brief Build a new OpenMP 'collapse' 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 *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1545 SourceLocation LParenLoc,
1546 SourceLocation EndLoc) {
1547 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1548 EndLoc);
1549 }
1550
1551 /// \brief Build a new OpenMP 'default' clause.
1552 ///
1553 /// By default, performs semantic analysis to build the new OpenMP clause.
1554 /// Subclasses may override this routine to provide different behavior.
1555 OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
1556 SourceLocation KindKwLoc,
1557 SourceLocation StartLoc,
1558 SourceLocation LParenLoc,
1559 SourceLocation EndLoc) {
1560 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1561 StartLoc, LParenLoc, EndLoc);
1562 }
1563
1564 /// \brief Build a new OpenMP 'proc_bind' clause.
1565 ///
1566 /// By default, performs semantic analysis to build the new OpenMP clause.
1567 /// Subclasses may override this routine to provide different behavior.
1568 OMPClause *RebuildOMPProcBindClause(OpenMPProcBindClauseKind Kind,
1569 SourceLocation KindKwLoc,
1570 SourceLocation StartLoc,
1571 SourceLocation LParenLoc,
1572 SourceLocation EndLoc) {
1573 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1574 StartLoc, LParenLoc, EndLoc);
1575 }
1576
1577 /// \brief Build a new OpenMP 'schedule' clause.
1578 ///
1579 /// By default, performs semantic analysis to build the new OpenMP clause.
1580 /// Subclasses may override this routine to provide different behavior.
1581 OMPClause *RebuildOMPScheduleClause(
1582 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1583 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1584 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1585 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1586 return getSema().ActOnOpenMPScheduleClause(
1587 M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1588 CommaLoc, EndLoc);
1589 }
1590
1591 /// \brief Build a new OpenMP 'ordered' clause.
1592 ///
1593 /// By default, performs semantic analysis to build the new OpenMP clause.
1594 /// Subclasses may override this routine to provide different behavior.
1595 OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1596 SourceLocation EndLoc,
1597 SourceLocation LParenLoc, Expr *Num) {
1598 return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1599 }
1600
1601 /// \brief Build a new OpenMP 'private' 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 *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1606 SourceLocation StartLoc,
1607 SourceLocation LParenLoc,
1608 SourceLocation EndLoc) {
1609 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1610 EndLoc);
1611 }
1612
1613 /// \brief Build a new OpenMP 'firstprivate' clause.
1614 ///
1615 /// By default, performs semantic analysis to build the new OpenMP clause.
1616 /// Subclasses may override this routine to provide different behavior.
1617 OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1618 SourceLocation StartLoc,
1619 SourceLocation LParenLoc,
1620 SourceLocation EndLoc) {
1621 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1622 EndLoc);
1623 }
1624
1625 /// \brief Build a new OpenMP 'lastprivate' clause.
1626 ///
1627 /// By default, performs semantic analysis to build the new OpenMP clause.
1628 /// Subclasses may override this routine to provide different behavior.
1629 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1630 SourceLocation StartLoc,
1631 SourceLocation LParenLoc,
1632 SourceLocation EndLoc) {
1633 return getSema().ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc,
1634 EndLoc);
1635 }
1636
1637 /// \brief Build a new OpenMP 'shared' clause.
1638 ///
1639 /// By default, performs semantic analysis to build the new OpenMP clause.
1640 /// Subclasses may override this routine to provide different behavior.
1641 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1642 SourceLocation StartLoc,
1643 SourceLocation LParenLoc,
1644 SourceLocation EndLoc) {
1645 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1646 EndLoc);
1647 }
1648
1649 /// \brief Build a new OpenMP 'reduction' clause.
1650 ///
1651 /// By default, performs semantic analysis to build the new statement.
1652 /// Subclasses may override this routine to provide different behavior.
1653 OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
1654 SourceLocation StartLoc,
1655 SourceLocation LParenLoc,
1656 SourceLocation ColonLoc,
1657 SourceLocation EndLoc,
1658 CXXScopeSpec &ReductionIdScopeSpec,
1659 const DeclarationNameInfo &ReductionId,
1660 ArrayRef<Expr *> UnresolvedReductions) {
1661 return getSema().ActOnOpenMPReductionClause(
1662 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1663 ReductionId, UnresolvedReductions);
1664 }
1665
1666 /// Build a new OpenMP 'task_reduction' clause.
1667 ///
1668 /// By default, performs semantic analysis to build the new statement.
1669 /// Subclasses may override this routine to provide different behavior.
1670 OMPClause *RebuildOMPTaskReductionClause(
1671 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1672 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1673 CXXScopeSpec &ReductionIdScopeSpec,
1674 const DeclarationNameInfo &ReductionId,
1675 ArrayRef<Expr *> UnresolvedReductions) {
1676 return getSema().ActOnOpenMPTaskReductionClause(
1677 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1678 ReductionId, UnresolvedReductions);
1679 }
1680
1681 /// Build a new OpenMP 'in_reduction' clause.
1682 ///
1683 /// By default, performs semantic analysis to build the new statement.
1684 /// Subclasses may override this routine to provide different behavior.
1685 OMPClause *
1686 RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1687 SourceLocation LParenLoc, SourceLocation ColonLoc,
1688 SourceLocation EndLoc,
1689 CXXScopeSpec &ReductionIdScopeSpec,
1690 const DeclarationNameInfo &ReductionId,
1691 ArrayRef<Expr *> UnresolvedReductions) {
1692 return getSema().ActOnOpenMPInReductionClause(
1693 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1694 ReductionId, UnresolvedReductions);
1695 }
1696
1697 /// \brief Build a new OpenMP 'linear' clause.
1698 ///
1699 /// By default, performs semantic analysis to build the new OpenMP clause.
1700 /// Subclasses may override this routine to provide different behavior.
1701 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1702 SourceLocation StartLoc,
1703 SourceLocation LParenLoc,
1704 OpenMPLinearClauseKind Modifier,
1705 SourceLocation ModifierLoc,
1706 SourceLocation ColonLoc,
1707 SourceLocation EndLoc) {
1708 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1709 Modifier, ModifierLoc, ColonLoc,
1710 EndLoc);
1711 }
1712
1713 /// \brief Build a new OpenMP 'aligned' clause.
1714 ///
1715 /// By default, performs semantic analysis to build the new OpenMP clause.
1716 /// Subclasses may override this routine to provide different behavior.
1717 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1718 SourceLocation StartLoc,
1719 SourceLocation LParenLoc,
1720 SourceLocation ColonLoc,
1721 SourceLocation EndLoc) {
1722 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1723 LParenLoc, ColonLoc, EndLoc);
1724 }
1725
1726 /// \brief Build a new OpenMP 'copyin' clause.
1727 ///
1728 /// By default, performs semantic analysis to build the new OpenMP clause.
1729 /// Subclasses may override this routine to provide different behavior.
1730 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1731 SourceLocation StartLoc,
1732 SourceLocation LParenLoc,
1733 SourceLocation EndLoc) {
1734 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1735 EndLoc);
1736 }
1737
1738 /// \brief Build a new OpenMP 'copyprivate' clause.
1739 ///
1740 /// By default, performs semantic analysis to build the new OpenMP clause.
1741 /// Subclasses may override this routine to provide different behavior.
1742 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1743 SourceLocation StartLoc,
1744 SourceLocation LParenLoc,
1745 SourceLocation EndLoc) {
1746 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1747 EndLoc);
1748 }
1749
1750 /// \brief Build a new OpenMP 'flush' pseudo clause.
1751 ///
1752 /// By default, performs semantic analysis to build the new OpenMP clause.
1753 /// Subclasses may override this routine to provide different behavior.
1754 OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1755 SourceLocation StartLoc,
1756 SourceLocation LParenLoc,
1757 SourceLocation EndLoc) {
1758 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1759 EndLoc);
1760 }
1761
1762 /// \brief Build a new OpenMP 'depend' pseudo clause.
1763 ///
1764 /// By default, performs semantic analysis to build the new OpenMP clause.
1765 /// Subclasses may override this routine to provide different behavior.
1766 OMPClause *
1767 RebuildOMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
1768 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1769 SourceLocation StartLoc, SourceLocation LParenLoc,
1770 SourceLocation EndLoc) {
1771 return getSema().ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList,
1772 StartLoc, LParenLoc, EndLoc);
1773 }
1774
1775 /// \brief Build a new OpenMP 'device' clause.
1776 ///
1777 /// By default, performs semantic analysis to build the new statement.
1778 /// Subclasses may override this routine to provide different behavior.
1779 OMPClause *RebuildOMPDeviceClause(Expr *Device, SourceLocation StartLoc,
1780 SourceLocation LParenLoc,
1781 SourceLocation EndLoc) {
1782 return getSema().ActOnOpenMPDeviceClause(Device, StartLoc, LParenLoc,
1783 EndLoc);
1784 }
1785
1786 /// \brief Build a new OpenMP 'map' clause.
1787 ///
1788 /// By default, performs semantic analysis to build the new OpenMP clause.
1789 /// Subclasses may override this routine to provide different behavior.
1790 OMPClause *
1791 RebuildOMPMapClause(OpenMPMapClauseKind MapTypeModifier,
1792 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1793 SourceLocation MapLoc, SourceLocation ColonLoc,
1794 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1795 SourceLocation LParenLoc, SourceLocation EndLoc) {
1796 return getSema().ActOnOpenMPMapClause(MapTypeModifier, MapType,
1797 IsMapTypeImplicit, MapLoc, ColonLoc,
1798 VarList, StartLoc, LParenLoc, EndLoc);
1799 }
1800
1801 /// \brief Build a new OpenMP 'num_teams' clause.
1802 ///
1803 /// By default, performs semantic analysis to build the new statement.
1804 /// Subclasses may override this routine to provide different behavior.
1805 OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1806 SourceLocation LParenLoc,
1807 SourceLocation EndLoc) {
1808 return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1809 EndLoc);
1810 }
1811
1812 /// \brief Build a new OpenMP 'thread_limit' clause.
1813 ///
1814 /// By default, performs semantic analysis to build the new statement.
1815 /// Subclasses may override this routine to provide different behavior.
1816 OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1817 SourceLocation StartLoc,
1818 SourceLocation LParenLoc,
1819 SourceLocation EndLoc) {
1820 return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1821 LParenLoc, EndLoc);
1822 }
1823
1824 /// \brief Build a new OpenMP 'priority' clause.
1825 ///
1826 /// By default, performs semantic analysis to build the new statement.
1827 /// Subclasses may override this routine to provide different behavior.
1828 OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1829 SourceLocation LParenLoc,
1830 SourceLocation EndLoc) {
1831 return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1832 EndLoc);
1833 }
1834
1835 /// \brief Build a new OpenMP 'grainsize' clause.
1836 ///
1837 /// By default, performs semantic analysis to build the new statement.
1838 /// Subclasses may override this routine to provide different behavior.
1839 OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1840 SourceLocation LParenLoc,
1841 SourceLocation EndLoc) {
1842 return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1843 EndLoc);
1844 }
1845
1846 /// \brief Build a new OpenMP 'num_tasks' clause.
1847 ///
1848 /// By default, performs semantic analysis to build the new statement.
1849 /// Subclasses may override this routine to provide different behavior.
1850 OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
1851 SourceLocation LParenLoc,
1852 SourceLocation EndLoc) {
1853 return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
1854 EndLoc);
1855 }
1856
1857 /// \brief Build a new OpenMP 'hint' clause.
1858 ///
1859 /// By default, performs semantic analysis to build the new statement.
1860 /// Subclasses may override this routine to provide different behavior.
1861 OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
1862 SourceLocation LParenLoc,
1863 SourceLocation EndLoc) {
1864 return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
1865 }
1866
1867 /// \brief Build a new OpenMP 'dist_schedule' clause.
1868 ///
1869 /// By default, performs semantic analysis to build the new OpenMP clause.
1870 /// Subclasses may override this routine to provide different behavior.
1871 OMPClause *
1872 RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
1873 Expr *ChunkSize, SourceLocation StartLoc,
1874 SourceLocation LParenLoc, SourceLocation KindLoc,
1875 SourceLocation CommaLoc, SourceLocation EndLoc) {
1876 return getSema().ActOnOpenMPDistScheduleClause(
1877 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
1878 }
1879
1880 /// \brief Build a new OpenMP 'to' clause.
1881 ///
1882 /// By default, performs semantic analysis to build the new statement.
1883 /// Subclasses may override this routine to provide different behavior.
1884 OMPClause *RebuildOMPToClause(ArrayRef<Expr *> VarList,
1885 SourceLocation StartLoc,
1886 SourceLocation LParenLoc,
1887 SourceLocation EndLoc) {
1888 return getSema().ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
1889 }
1890
1891 /// \brief Build a new OpenMP 'from' clause.
1892 ///
1893 /// By default, performs semantic analysis to build the new statement.
1894 /// Subclasses may override this routine to provide different behavior.
1895 OMPClause *RebuildOMPFromClause(ArrayRef<Expr *> VarList,
1896 SourceLocation StartLoc,
1897 SourceLocation LParenLoc,
1898 SourceLocation EndLoc) {
1899 return getSema().ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc,
1900 EndLoc);
1901 }
1902
1903 /// Build a new OpenMP 'use_device_ptr' clause.
1904 ///
1905 /// By default, performs semantic analysis to build the new OpenMP clause.
1906 /// Subclasses may override this routine to provide different behavior.
1907 OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
1908 SourceLocation StartLoc,
1909 SourceLocation LParenLoc,
1910 SourceLocation EndLoc) {
1911 return getSema().ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc,
1912 EndLoc);
1913 }
1914
1915 /// Build a new OpenMP 'is_device_ptr' clause.
1916 ///
1917 /// By default, performs semantic analysis to build the new OpenMP clause.
1918 /// Subclasses may override this routine to provide different behavior.
1919 OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
1920 SourceLocation StartLoc,
1921 SourceLocation LParenLoc,
1922 SourceLocation EndLoc) {
1923 return getSema().ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc,
1924 EndLoc);
1925 }
1926
1927 /// \brief Rebuild the operand to an Objective-C \@synchronized statement.
1928 ///
1929 /// By default, performs semantic analysis to build the new statement.
1930 /// Subclasses may override this routine to provide different behavior.
1931 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
1932 Expr *object) {
1933 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
1934 }
1935
1936 /// \brief Build a new Objective-C \@synchronized statement.
1937 ///
1938 /// By default, performs semantic analysis to build the new statement.
1939 /// Subclasses may override this routine to provide different behavior.
1940 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
1941 Expr *Object, Stmt *Body) {
1942 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
1943 }
1944
1945 /// \brief Build a new Objective-C \@autoreleasepool statement.
1946 ///
1947 /// By default, performs semantic analysis to build the new statement.
1948 /// Subclasses may override this routine to provide different behavior.
1949 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
1950 Stmt *Body) {
1951 return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
1952 }
1953
1954 /// \brief Build a new Objective-C fast enumeration statement.
1955 ///
1956 /// By default, performs semantic analysis to build the new statement.
1957 /// Subclasses may override this routine to provide different behavior.
1958 StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
1959 Stmt *Element,
1960 Expr *Collection,
1961 SourceLocation RParenLoc,
1962 Stmt *Body) {
1963 StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
1964 Element,
1965 Collection,
1966 RParenLoc);
1967 if (ForEachStmt.isInvalid())
1968 return StmtError();
1969
1970 return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
1971 }
1972
1973 /// \brief Build a new C++ exception declaration.
1974 ///
1975 /// By default, performs semantic analysis to build the new decaration.
1976 /// Subclasses may override this routine to provide different behavior.
1977 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1978 TypeSourceInfo *Declarator,
1979 SourceLocation StartLoc,
1980 SourceLocation IdLoc,
1981 IdentifierInfo *Id) {
1982 VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
1983 StartLoc, IdLoc, Id);
1984 if (Var)
1985 getSema().CurContext->addDecl(Var);
1986 return Var;
1987 }
1988
1989 /// \brief Build a new C++ catch statement.
1990 ///
1991 /// By default, performs semantic analysis to build the new statement.
1992 /// Subclasses may override this routine to provide different behavior.
1993 StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
1994 VarDecl *ExceptionDecl,
1995 Stmt *Handler) {
1996 return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
1997 Handler));
1998 }
1999
2000 /// \brief Build a new C++ try statement.
2001 ///
2002 /// By default, performs semantic analysis to build the new statement.
2003 /// Subclasses may override this routine to provide different behavior.
2004 StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2005 ArrayRef<Stmt *> Handlers) {
2006 return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2007 }
2008
2009 /// \brief Build a new C++0x range-based for statement.
2010 ///
2011 /// By default, performs semantic analysis to build the new statement.
2012 /// Subclasses may override this routine to provide different behavior.
2013 StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2014 SourceLocation CoawaitLoc,
2015 SourceLocation ColonLoc,
2016 Stmt *Range, Stmt *Begin, Stmt *End,
2017 Expr *Cond, Expr *Inc,
2018 Stmt *LoopVar,
2019 SourceLocation RParenLoc) {
2020 // If we've just learned that the range is actually an Objective-C
2021 // collection, treat this as an Objective-C fast enumeration loop.
2022 if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2023 if (RangeStmt->isSingleDecl()) {
2024 if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2025 if (RangeVar->isInvalidDecl())
2026 return StmtError();
2027
2028 Expr *RangeExpr = RangeVar->getInit();
2029 if (!RangeExpr->isTypeDependent() &&
2030 RangeExpr->getType()->isObjCObjectPointerType())
2031 return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar, RangeExpr,
2032 RParenLoc);
2033 }
2034 }
2035 }
2036
2037 return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc,
2038 Range, Begin, End,
2039 Cond, Inc, LoopVar, RParenLoc,
2040 Sema::BFRK_Rebuild);
2041 }
2042
2043 /// \brief Build a new C++0x range-based for statement.
2044 ///
2045 /// By default, performs semantic analysis to build the new statement.
2046 /// Subclasses may override this routine to provide different behavior.
2047 StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2048 bool IsIfExists,
2049 NestedNameSpecifierLoc QualifierLoc,
2050 DeclarationNameInfo NameInfo,
2051 Stmt *Nested) {
2052 return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2053 QualifierLoc, NameInfo, Nested);
2054 }
2055
2056 /// \brief Attach body to a C++0x range-based for statement.
2057 ///
2058 /// By default, performs semantic analysis to finish the new statement.
2059 /// Subclasses may override this routine to provide different behavior.
2060 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2061 return getSema().FinishCXXForRangeStmt(ForRange, Body);
2062 }
2063
2064 StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2065 Stmt *TryBlock, Stmt *Handler) {
2066 return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2067 }
2068
2069 StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2070 Stmt *Block) {
2071 return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2072 }
2073
2074 StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2075 return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2076 }
2077
2078 /// \brief Build a new predefined expression.
2079 ///
2080 /// By default, performs semantic analysis to build the new expression.
2081 /// Subclasses may override this routine to provide different behavior.
2082 ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2083 PredefinedExpr::IdentType IT) {
2084 return getSema().BuildPredefinedExpr(Loc, IT);
2085 }
2086
2087 /// \brief Build a new expression that references a declaration.
2088 ///
2089 /// By default, performs semantic analysis to build the new expression.
2090 /// Subclasses may override this routine to provide different behavior.
2091 ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2092 LookupResult &R,
2093 bool RequiresADL) {
2094 return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2095 }
2096
2097
2098 /// \brief Build a new expression that references a declaration.
2099 ///
2100 /// By default, performs semantic analysis to build the new expression.
2101 /// Subclasses may override this routine to provide different behavior.
2102 ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2103 ValueDecl *VD,
2104 const DeclarationNameInfo &NameInfo,
2105 TemplateArgumentListInfo *TemplateArgs) {
2106 CXXScopeSpec SS;
2107 SS.Adopt(QualifierLoc);
2108
2109 // FIXME: loses template args.
2110
2111 return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
2112 }
2113
2114 /// \brief Build a new expression in parentheses.
2115 ///
2116 /// By default, performs semantic analysis to build the new expression.
2117 /// Subclasses may override this routine to provide different behavior.
2118 ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2119 SourceLocation RParen) {
2120 return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2121 }
2122
2123 /// \brief Build a new pseudo-destructor expression.
2124 ///
2125 /// By default, performs semantic analysis to build the new expression.
2126 /// Subclasses may override this routine to provide different behavior.
2127 ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2128 SourceLocation OperatorLoc,
2129 bool isArrow,
2130 CXXScopeSpec &SS,
2131 TypeSourceInfo *ScopeType,
2132 SourceLocation CCLoc,
2133 SourceLocation TildeLoc,
2134 PseudoDestructorTypeStorage Destroyed);
2135
2136 /// \brief Build a new unary operator expression.
2137 ///
2138 /// By default, performs semantic analysis to build the new expression.
2139 /// Subclasses may override this routine to provide different behavior.
2140 ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2141 UnaryOperatorKind Opc,
2142 Expr *SubExpr) {
2143 return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2144 }
2145
2146 /// \brief Build a new builtin offsetof 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 RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2151 TypeSourceInfo *Type,
2152 ArrayRef<Sema::OffsetOfComponent> Components,
2153 SourceLocation RParenLoc) {
2154 return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2155 RParenLoc);
2156 }
2157
2158 /// \brief Build a new sizeof, alignof or vec_step expression with a
2159 /// type argument.
2160 ///
2161 /// By default, performs semantic analysis to build the new expression.
2162 /// Subclasses may override this routine to provide different behavior.
2163 ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2164 SourceLocation OpLoc,
2165 UnaryExprOrTypeTrait ExprKind,
2166 SourceRange R) {
2167 return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2168 }
2169
2170 /// \brief Build a new sizeof, alignof or vec step expression with an
2171 /// expression argument.
2172 ///
2173 /// By default, performs semantic analysis to build the new expression.
2174 /// Subclasses may override this routine to provide different behavior.
2175 ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2176 UnaryExprOrTypeTrait ExprKind,
2177 SourceRange R) {
2178 ExprResult Result
2179 = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2180 if (Result.isInvalid())
2181 return ExprError();
2182
2183 return Result;
2184 }
2185
2186 /// \brief Build a new array subscript expression.
2187 ///
2188 /// By default, performs semantic analysis to build the new expression.
2189 /// Subclasses may override this routine to provide different behavior.
2190 ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2191 SourceLocation LBracketLoc,
2192 Expr *RHS,
2193 SourceLocation RBracketLoc) {
2194 return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2195 LBracketLoc, RHS,
2196 RBracketLoc);
2197 }
2198
2199 /// \brief Build a new array section expression.
2200 ///
2201 /// By default, performs semantic analysis to build the new expression.
2202 /// Subclasses may override this routine to provide different behavior.
2203 ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2204 Expr *LowerBound,
2205 SourceLocation ColonLoc, Expr *Length,
2206 SourceLocation RBracketLoc) {
2207 return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2208 ColonLoc, Length, RBracketLoc);
2209 }
2210
2211 /// \brief Build a new call expression.
2212 ///
2213 /// By default, performs semantic analysis to build the new expression.
2214 /// Subclasses may override this routine to provide different behavior.
2215 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2216 MultiExprArg Args,
2217 SourceLocation RParenLoc,
2218 Expr *ExecConfig = nullptr) {
2219 return getSema().ActOnCallExpr(/*Scope=*/nullptr, Callee, LParenLoc,
2220 Args, RParenLoc, ExecConfig);
2221 }
2222
2223 /// \brief Build a new member access expression.
2224 ///
2225 /// By default, performs semantic analysis to build the new expression.
2226 /// Subclasses may override this routine to provide different behavior.
2227 ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2228 bool isArrow,
2229 NestedNameSpecifierLoc QualifierLoc,
2230 SourceLocation TemplateKWLoc,
2231 const DeclarationNameInfo &MemberNameInfo,
2232 ValueDecl *Member,
2233 NamedDecl *FoundDecl,
2234 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2235 NamedDecl *FirstQualifierInScope) {
2236 ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2237 isArrow);
2238 if (!Member->getDeclName()) {
2239 // We have a reference to an unnamed field. This is always the
2240 // base of an anonymous struct/union member access, i.e. the
2241 // field is always of record type.
2242 assert(!QualifierLoc && "Can't have an unnamed field with a qualifier!")(static_cast <bool> (!QualifierLoc && "Can't have an unnamed field with a qualifier!"
) ? void (0) : __assert_fail ("!QualifierLoc && \"Can't have an unnamed field with a qualifier!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 2242, __extension__ __PRETTY_FUNCTION__))
;
2243 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-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 2244, __extension__ __PRETTY_FUNCTION__))
2244 "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-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 2244, __extension__ __PRETTY_FUNCTION__))
;
2245
2246 BaseResult =
2247 getSema().PerformObjectMemberConversion(BaseResult.get(),
2248 QualifierLoc.getNestedNameSpecifier(),
2249 FoundDecl, Member);
2250 if (BaseResult.isInvalid())
2251 return ExprError();
2252 Base = BaseResult.get();
2253 ExprValueKind VK = isArrow ? VK_LValue : Base->getValueKind();
2254 MemberExpr *ME = new (getSema().Context)
2255 MemberExpr(Base, isArrow, OpLoc, Member, MemberNameInfo,
2256 cast<FieldDecl>(Member)->getType(), VK, OK_Ordinary);
2257 return ME;
2258 }
2259
2260 CXXScopeSpec SS;
2261 SS.Adopt(QualifierLoc);
2262
2263 Base = BaseResult.get();
2264 QualType BaseType = Base->getType();
2265
2266 if (isArrow && !BaseType->isPointerType())
2267 return ExprError();
2268
2269 // FIXME: this involves duplicating earlier analysis in a lot of
2270 // cases; we should avoid this when possible.
2271 LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2272 R.addDecl(FoundDecl);
2273 R.resolveKind();
2274
2275 return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2276 SS, TemplateKWLoc,
2277 FirstQualifierInScope,
2278 R, ExplicitTemplateArgs,
2279 /*S*/nullptr);
2280 }
2281
2282 /// \brief Build a new binary operator expression.
2283 ///
2284 /// By default, performs semantic analysis to build the new expression.
2285 /// Subclasses may override this routine to provide different behavior.
2286 ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2287 BinaryOperatorKind Opc,
2288 Expr *LHS, Expr *RHS) {
2289 return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2290 }
2291
2292 /// \brief Build a new conditional operator expression.
2293 ///
2294 /// By default, performs semantic analysis to build the new expression.
2295 /// Subclasses may override this routine to provide different behavior.
2296 ExprResult RebuildConditionalOperator(Expr *Cond,
2297 SourceLocation QuestionLoc,
2298 Expr *LHS,
2299 SourceLocation ColonLoc,
2300 Expr *RHS) {
2301 return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2302 LHS, RHS);
2303 }
2304
2305 /// \brief Build a new C-style cast expression.
2306 ///
2307 /// By default, performs semantic analysis to build the new expression.
2308 /// Subclasses may override this routine to provide different behavior.
2309 ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2310 TypeSourceInfo *TInfo,
2311 SourceLocation RParenLoc,
2312 Expr *SubExpr) {
2313 return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2314 SubExpr);
2315 }
2316
2317 /// \brief Build a new compound literal expression.
2318 ///
2319 /// By default, performs semantic analysis to build the new expression.
2320 /// Subclasses may override this routine to provide different behavior.
2321 ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2322 TypeSourceInfo *TInfo,
2323 SourceLocation RParenLoc,
2324 Expr *Init) {
2325 return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2326 Init);
2327 }
2328
2329 /// \brief Build a new extended vector element access expression.
2330 ///
2331 /// By default, performs semantic analysis to build the new expression.
2332 /// Subclasses may override this routine to provide different behavior.
2333 ExprResult RebuildExtVectorElementExpr(Expr *Base,
2334 SourceLocation OpLoc,
2335 SourceLocation AccessorLoc,
2336 IdentifierInfo &Accessor) {
2337
2338 CXXScopeSpec SS;
2339 DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2340 return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2341 OpLoc, /*IsArrow*/ false,
2342 SS, SourceLocation(),
2343 /*FirstQualifierInScope*/ nullptr,
2344 NameInfo,
2345 /* TemplateArgs */ nullptr,
2346 /*S*/ nullptr);
2347 }
2348
2349 /// \brief Build a new initializer list expression.
2350 ///
2351 /// By default, performs semantic analysis to build the new expression.
2352 /// Subclasses may override this routine to provide different behavior.
2353 ExprResult RebuildInitList(SourceLocation LBraceLoc,
2354 MultiExprArg Inits,
2355 SourceLocation RBraceLoc,
2356 QualType ResultTy) {
2357 ExprResult Result
2358 = SemaRef.ActOnInitList(LBraceLoc, Inits, RBraceLoc);
2359 if (Result.isInvalid() || ResultTy->isDependentType())
2360 return Result;
2361
2362 // Patch in the result type we were given, which may have been computed
2363 // when the initial InitListExpr was built.
2364 InitListExpr *ILE = cast<InitListExpr>((Expr *)Result.get());
2365 ILE->setType(ResultTy);
2366 return Result;
2367 }
2368
2369 /// \brief Build a new designated initializer expression.
2370 ///
2371 /// By default, performs semantic analysis to build the new expression.
2372 /// Subclasses may override this routine to provide different behavior.
2373 ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2374 MultiExprArg ArrayExprs,
2375 SourceLocation EqualOrColonLoc,
2376 bool GNUSyntax,
2377 Expr *Init) {
2378 ExprResult Result
2379 = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2380 Init);
2381 if (Result.isInvalid())
2382 return ExprError();
2383
2384 return Result;
2385 }
2386
2387 /// \brief Build a new value-initialized expression.
2388 ///
2389 /// By default, builds the implicit value initialization without performing
2390 /// any semantic analysis. Subclasses may override this routine to provide
2391 /// different behavior.
2392 ExprResult RebuildImplicitValueInitExpr(QualType T) {
2393 return new (SemaRef.Context) ImplicitValueInitExpr(T);
2394 }
2395
2396 /// \brief Build a new \c va_arg expression.
2397 ///
2398 /// By default, performs semantic analysis to build the new expression.
2399 /// Subclasses may override this routine to provide different behavior.
2400 ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2401 Expr *SubExpr, TypeSourceInfo *TInfo,
2402 SourceLocation RParenLoc) {
2403 return getSema().BuildVAArgExpr(BuiltinLoc,
2404 SubExpr, TInfo,
2405 RParenLoc);
2406 }
2407
2408 /// \brief Build a new expression list in parentheses.
2409 ///
2410 /// By default, performs semantic analysis to build the new expression.
2411 /// Subclasses may override this routine to provide different behavior.
2412 ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2413 MultiExprArg SubExprs,
2414 SourceLocation RParenLoc) {
2415 return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2416 }
2417
2418 /// \brief Build a new address-of-label expression.
2419 ///
2420 /// By default, performs semantic analysis, using the name of the label
2421 /// rather than attempting to map the label statement itself.
2422 /// Subclasses may override this routine to provide different behavior.
2423 ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2424 SourceLocation LabelLoc, LabelDecl *Label) {
2425 return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2426 }
2427
2428 /// \brief Build a new GNU statement expression.
2429 ///
2430 /// By default, performs semantic analysis to build the new expression.
2431 /// Subclasses may override this routine to provide different behavior.
2432 ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
2433 Stmt *SubStmt,
2434 SourceLocation RParenLoc) {
2435 return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
2436 }
2437
2438 /// \brief Build a new __builtin_choose_expr expression.
2439 ///
2440 /// By default, performs semantic analysis to build the new expression.
2441 /// Subclasses may override this routine to provide different behavior.
2442 ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2443 Expr *Cond, Expr *LHS, Expr *RHS,
2444 SourceLocation RParenLoc) {
2445 return SemaRef.ActOnChooseExpr(BuiltinLoc,
2446 Cond, LHS, RHS,
2447 RParenLoc);
2448 }
2449
2450 /// \brief Build a new generic selection expression.
2451 ///
2452 /// By default, performs semantic analysis to build the new expression.
2453 /// Subclasses may override this routine to provide different behavior.
2454 ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2455 SourceLocation DefaultLoc,
2456 SourceLocation RParenLoc,
2457 Expr *ControllingExpr,
2458 ArrayRef<TypeSourceInfo *> Types,
2459 ArrayRef<Expr *> Exprs) {
2460 return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2461 ControllingExpr, Types, Exprs);
2462 }
2463
2464 /// \brief Build a new overloaded operator call expression.
2465 ///
2466 /// By default, performs semantic analysis to build the new expression.
2467 /// The semantic analysis provides the behavior of template instantiation,
2468 /// copying with transformations that turn what looks like an overloaded
2469 /// operator call into a use of a builtin operator, performing
2470 /// argument-dependent lookup, etc. Subclasses may override this routine to
2471 /// provide different behavior.
2472 ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2473 SourceLocation OpLoc,
2474 Expr *Callee,
2475 Expr *First,
2476 Expr *Second);
2477
2478 /// \brief Build a new C++ "named" cast expression, such as static_cast or
2479 /// reinterpret_cast.
2480 ///
2481 /// By default, this routine dispatches to one of the more-specific routines
2482 /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2483 /// Subclasses may override this routine to provide different behavior.
2484 ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2485 Stmt::StmtClass Class,
2486 SourceLocation LAngleLoc,
2487 TypeSourceInfo *TInfo,
2488 SourceLocation RAngleLoc,
2489 SourceLocation LParenLoc,
2490 Expr *SubExpr,
2491 SourceLocation RParenLoc) {
2492 switch (Class) {
2493 case Stmt::CXXStaticCastExprClass:
2494 return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2495 RAngleLoc, LParenLoc,
2496 SubExpr, RParenLoc);
2497
2498 case Stmt::CXXDynamicCastExprClass:
2499 return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2500 RAngleLoc, LParenLoc,
2501 SubExpr, RParenLoc);
2502
2503 case Stmt::CXXReinterpretCastExprClass:
2504 return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2505 RAngleLoc, LParenLoc,
2506 SubExpr,
2507 RParenLoc);
2508
2509 case Stmt::CXXConstCastExprClass:
2510 return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2511 RAngleLoc, LParenLoc,
2512 SubExpr, RParenLoc);
2513
2514 default:
2515 llvm_unreachable("Invalid C++ named cast")::llvm::llvm_unreachable_internal("Invalid C++ named cast", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 2515)
;
2516 }
2517 }
2518
2519 /// \brief Build a new C++ static_cast expression.
2520 ///
2521 /// By default, performs semantic analysis to build the new expression.
2522 /// Subclasses may override this routine to provide different behavior.
2523 ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2524 SourceLocation LAngleLoc,
2525 TypeSourceInfo *TInfo,
2526 SourceLocation RAngleLoc,
2527 SourceLocation LParenLoc,
2528 Expr *SubExpr,
2529 SourceLocation RParenLoc) {
2530 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2531 TInfo, SubExpr,
2532 SourceRange(LAngleLoc, RAngleLoc),
2533 SourceRange(LParenLoc, RParenLoc));
2534 }
2535
2536 /// \brief Build a new C++ dynamic_cast expression.
2537 ///
2538 /// By default, performs semantic analysis to build the new expression.
2539 /// Subclasses may override this routine to provide different behavior.
2540 ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2541 SourceLocation LAngleLoc,
2542 TypeSourceInfo *TInfo,
2543 SourceLocation RAngleLoc,
2544 SourceLocation LParenLoc,
2545 Expr *SubExpr,
2546 SourceLocation RParenLoc) {
2547 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2548 TInfo, SubExpr,
2549 SourceRange(LAngleLoc, RAngleLoc),
2550 SourceRange(LParenLoc, RParenLoc));
2551 }
2552
2553 /// \brief Build a new C++ reinterpret_cast expression.
2554 ///
2555 /// By default, performs semantic analysis to build the new expression.
2556 /// Subclasses may override this routine to provide different behavior.
2557 ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2558 SourceLocation LAngleLoc,
2559 TypeSourceInfo *TInfo,
2560 SourceLocation RAngleLoc,
2561 SourceLocation LParenLoc,
2562 Expr *SubExpr,
2563 SourceLocation RParenLoc) {
2564 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2565 TInfo, SubExpr,
2566 SourceRange(LAngleLoc, RAngleLoc),
2567 SourceRange(LParenLoc, RParenLoc));
2568 }
2569
2570 /// \brief Build a new C++ const_cast expression.
2571 ///
2572 /// By default, performs semantic analysis to build the new expression.
2573 /// Subclasses may override this routine to provide different behavior.
2574 ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2575 SourceLocation LAngleLoc,
2576 TypeSourceInfo *TInfo,
2577 SourceLocation RAngleLoc,
2578 SourceLocation LParenLoc,
2579 Expr *SubExpr,
2580 SourceLocation RParenLoc) {
2581 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2582 TInfo, SubExpr,
2583 SourceRange(LAngleLoc, RAngleLoc),
2584 SourceRange(LParenLoc, RParenLoc));
2585 }
2586
2587 /// \brief Build a new C++ functional-style cast expression.
2588 ///
2589 /// By default, performs semantic analysis to build the new expression.
2590 /// Subclasses may override this routine to provide different behavior.
2591 ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2592 SourceLocation LParenLoc,
2593 Expr *Sub,
2594 SourceLocation RParenLoc) {
2595 return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2596 MultiExprArg(&Sub, 1),
2597 RParenLoc);
2598 }
2599
2600 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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(TSInfo, LParenLoc,
2698 None, RParenLoc);
2699 }
2700
2701 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 LParenLoc,
2856 MultiExprArg Args,
2857 SourceLocation RParenLoc) {
2858 return getSema().BuildCXXTypeConstructExpr(TSInfo,
2859 LParenLoc,
2860 Args,
2861 RParenLoc);
2862 }
2863
2864 /// \brief Build a new object-construction expression.
2865 ///
2866 /// By default, performs semantic analysis to build the new expression.
2867 /// Subclasses may override this routine to provide different behavior.
2868 ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2869 SourceLocation LParenLoc,
2870 MultiExprArg Args,
2871 SourceLocation RParenLoc) {
2872 return getSema().BuildCXXTypeConstructExpr(TSInfo,
2873 LParenLoc,
2874 Args,
2875 RParenLoc);
2876 }
2877
2878 /// \brief Build a new member reference expression.
2879 ///
2880 /// By default, performs semantic analysis to build the new expression.
2881 /// Subclasses may override this routine to provide different behavior.
2882 ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2883 QualType BaseType,
2884 bool IsArrow,
2885 SourceLocation OperatorLoc,
2886 NestedNameSpecifierLoc QualifierLoc,
2887 SourceLocation TemplateKWLoc,
2888 NamedDecl *FirstQualifierInScope,
2889 const DeclarationNameInfo &MemberNameInfo,
2890 const TemplateArgumentListInfo *TemplateArgs) {
2891 CXXScopeSpec SS;
2892 SS.Adopt(QualifierLoc);
2893
2894 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2895 OperatorLoc, IsArrow,
2896 SS, TemplateKWLoc,
2897 FirstQualifierInScope,
2898 MemberNameInfo,
2899 TemplateArgs, /*S*/nullptr);
2900 }
2901
2902 /// \brief Build a new member reference expression.
2903 ///
2904 /// By default, performs semantic analysis to build the new expression.
2905 /// Subclasses may override this routine to provide different behavior.
2906 ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
2907 SourceLocation OperatorLoc,
2908 bool IsArrow,
2909 NestedNameSpecifierLoc QualifierLoc,
2910 SourceLocation TemplateKWLoc,
2911 NamedDecl *FirstQualifierInScope,
2912 LookupResult &R,
2913 const TemplateArgumentListInfo *TemplateArgs) {
2914 CXXScopeSpec SS;
2915 SS.Adopt(QualifierLoc);
2916
2917 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2918 OperatorLoc, IsArrow,
2919 SS, TemplateKWLoc,
2920 FirstQualifierInScope,
2921 R, TemplateArgs, /*S*/nullptr);
2922 }
2923
2924 /// \brief Build a new noexcept expression.
2925 ///
2926 /// By default, performs semantic analysis to build the new expression.
2927 /// Subclasses may override this routine to provide different behavior.
2928 ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
2929 return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
2930 }
2931
2932 /// \brief Build a new expression to compute the length of a parameter pack.
2933 ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
2934 NamedDecl *Pack,
2935 SourceLocation PackLoc,
2936 SourceLocation RParenLoc,
2937 Optional<unsigned> Length,
2938 ArrayRef<TemplateArgument> PartialArgs) {
2939 return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
2940 RParenLoc, Length, PartialArgs);
2941 }
2942
2943 /// \brief Build a new Objective-C boxed expression.
2944 ///
2945 /// By default, performs semantic analysis to build the new expression.
2946 /// Subclasses may override this routine to provide different behavior.
2947 ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
2948 return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
2949 }
2950
2951 /// \brief Build a new Objective-C array literal.
2952 ///
2953 /// By default, performs semantic analysis to build the new expression.
2954 /// Subclasses may override this routine to provide different behavior.
2955 ExprResult RebuildObjCArrayLiteral(SourceRange Range,
2956 Expr **Elements, unsigned NumElements) {
2957 return getSema().BuildObjCArrayLiteral(Range,
2958 MultiExprArg(Elements, NumElements));
2959 }
2960
2961 ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
2962 Expr *Base, Expr *Key,
2963 ObjCMethodDecl *getterMethod,
2964 ObjCMethodDecl *setterMethod) {
2965 return getSema().BuildObjCSubscriptExpression(RB, Base, Key,
2966 getterMethod, setterMethod);
2967 }
2968
2969 /// \brief Build a new Objective-C dictionary literal.
2970 ///
2971 /// By default, performs semantic analysis to build the new expression.
2972 /// Subclasses may override this routine to provide different behavior.
2973 ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
2974 MutableArrayRef<ObjCDictionaryElement> Elements) {
2975 return getSema().BuildObjCDictionaryLiteral(Range, Elements);
2976 }
2977
2978 /// \brief Build a new Objective-C \@encode expression.
2979 ///
2980 /// By default, performs semantic analysis to build the new expression.
2981 /// Subclasses may override this routine to provide different behavior.
2982 ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
2983 TypeSourceInfo *EncodeTypeInfo,
2984 SourceLocation RParenLoc) {
2985 return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
2986 }
2987
2988 /// \brief Build a new Objective-C class message.
2989 ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
2990 Selector Sel,
2991 ArrayRef<SourceLocation> SelectorLocs,
2992 ObjCMethodDecl *Method,
2993 SourceLocation LBracLoc,
2994 MultiExprArg Args,
2995 SourceLocation RBracLoc) {
2996 return SemaRef.BuildClassMessage(ReceiverTypeInfo,
2997 ReceiverTypeInfo->getType(),
2998 /*SuperLoc=*/SourceLocation(),
2999 Sel, Method, LBracLoc, SelectorLocs,
3000 RBracLoc, Args);
3001 }
3002
3003 /// \brief Build a new Objective-C instance message.
3004 ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3005 Selector Sel,
3006 ArrayRef<SourceLocation> SelectorLocs,
3007 ObjCMethodDecl *Method,
3008 SourceLocation LBracLoc,
3009 MultiExprArg Args,
3010 SourceLocation RBracLoc) {
3011 return SemaRef.BuildInstanceMessage(Receiver,
3012 Receiver->getType(),
3013 /*SuperLoc=*/SourceLocation(),
3014 Sel, Method, LBracLoc, SelectorLocs,
3015 RBracLoc, Args);
3016 }
3017
3018 /// \brief Build a new Objective-C instance/class message to 'super'.
3019 ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3020 Selector Sel,
3021 ArrayRef<SourceLocation> SelectorLocs,
3022 QualType SuperType,
3023 ObjCMethodDecl *Method,
3024 SourceLocation LBracLoc,
3025 MultiExprArg Args,
3026 SourceLocation RBracLoc) {
3027 return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3028 SuperType,
3029 SuperLoc,
3030 Sel, Method, LBracLoc, SelectorLocs,
3031 RBracLoc, Args)
3032 : SemaRef.BuildClassMessage(nullptr,
3033 SuperType,
3034 SuperLoc,
3035 Sel, Method, LBracLoc, SelectorLocs,
3036 RBracLoc, Args);
3037
3038
3039 }
3040
3041 /// \brief Build a new Objective-C ivar reference expression.
3042 ///
3043 /// By default, performs semantic analysis to build the new expression.
3044 /// Subclasses may override this routine to provide different behavior.
3045 ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3046 SourceLocation IvarLoc,
3047 bool IsArrow, bool IsFreeIvar) {
3048 CXXScopeSpec SS;
3049 DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3050 ExprResult Result = getSema().BuildMemberReferenceExpr(
3051 BaseArg, BaseArg->getType(),
3052 /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3053 /*FirstQualifierInScope=*/nullptr, NameInfo,
3054 /*TemplateArgs=*/nullptr,
3055 /*S=*/nullptr);
3056 if (IsFreeIvar && Result.isUsable())
3057 cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3058 return Result;
3059 }
3060
3061 /// \brief Build a new Objective-C property reference expression.
3062 ///
3063 /// By default, performs semantic analysis to build the new expression.
3064 /// Subclasses may override this routine to provide different behavior.
3065 ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3066 ObjCPropertyDecl *Property,
3067 SourceLocation PropertyLoc) {
3068 CXXScopeSpec SS;
3069 DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3070 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3071 /*FIXME:*/PropertyLoc,
3072 /*IsArrow=*/false,
3073 SS, SourceLocation(),
3074 /*FirstQualifierInScope=*/nullptr,
3075 NameInfo,
3076 /*TemplateArgs=*/nullptr,
3077 /*S=*/nullptr);
3078 }
3079
3080 /// \brief Build a new Objective-C property reference expression.
3081 ///
3082 /// By default, performs semantic analysis to build the new expression.
3083 /// Subclasses may override this routine to provide different behavior.
3084 ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3085 ObjCMethodDecl *Getter,
3086 ObjCMethodDecl *Setter,
3087 SourceLocation PropertyLoc) {
3088 // Since these expressions can only be value-dependent, we do not
3089 // need to perform semantic analysis again.
3090 return Owned(
3091 new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3092 VK_LValue, OK_ObjCProperty,
3093 PropertyLoc, Base));
3094 }
3095
3096 /// \brief Build a new Objective-C "isa" expression.
3097 ///
3098 /// By default, performs semantic analysis to build the new expression.
3099 /// Subclasses may override this routine to provide different behavior.
3100 ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3101 SourceLocation OpLoc, bool IsArrow) {
3102 CXXScopeSpec SS;
3103 DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3104 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3105 OpLoc, IsArrow,
3106 SS, SourceLocation(),
3107 /*FirstQualifierInScope=*/nullptr,
3108 NameInfo,
3109 /*TemplateArgs=*/nullptr,
3110 /*S=*/nullptr);
3111 }
3112
3113 /// \brief Build a new shuffle vector expression.
3114 ///
3115 /// By default, performs semantic analysis to build the new expression.
3116 /// Subclasses may override this routine to provide different behavior.
3117 ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3118 MultiExprArg SubExprs,
3119 SourceLocation RParenLoc) {
3120 // Find the declaration for __builtin_shufflevector
3121 const IdentifierInfo &Name
3122 = SemaRef.Context.Idents.get("__builtin_shufflevector");
3123 TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3124 DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3125 assert(!Lookup.empty() && "No __builtin_shufflevector?")(static_cast <bool> (!Lookup.empty() && "No __builtin_shufflevector?"
) ? void (0) : __assert_fail ("!Lookup.empty() && \"No __builtin_shufflevector?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 3125, __extension__ __PRETTY_FUNCTION__))
;
3126
3127 // Build a reference to the __builtin_shufflevector builtin
3128 FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3129 Expr *Callee = new (SemaRef.Context) DeclRefExpr(Builtin, false,
3130 SemaRef.Context.BuiltinFnTy,
3131 VK_RValue, BuiltinLoc);
3132 QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3133 Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3134 CK_BuiltinFnToFnPtr).get();
3135
3136 // Build the CallExpr
3137 ExprResult TheCall = new (SemaRef.Context) CallExpr(
3138 SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3139 Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
3140
3141 // Type-check the __builtin_shufflevector expression.
3142 return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3143 }
3144
3145 /// \brief Build a new convert vector expression.
3146 ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3147 Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3148 SourceLocation RParenLoc) {
3149 return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3150 BuiltinLoc, RParenLoc);
3151 }
3152
3153 /// \brief Build a new template argument pack expansion.
3154 ///
3155 /// By default, performs semantic analysis to build a new pack expansion
3156 /// for a template argument. Subclasses may override this routine to provide
3157 /// different behavior.
3158 TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3159 SourceLocation EllipsisLoc,
3160 Optional<unsigned> NumExpansions) {
3161 switch (Pattern.getArgument().getKind()) {
3162 case TemplateArgument::Expression: {
3163 ExprResult Result
3164 = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3165 EllipsisLoc, NumExpansions);
3166 if (Result.isInvalid())
3167 return TemplateArgumentLoc();
3168
3169 return TemplateArgumentLoc(Result.get(), Result.get());
3170 }
3171
3172 case TemplateArgument::Template:
3173 return TemplateArgumentLoc(TemplateArgument(
3174 Pattern.getArgument().getAsTemplate(),
3175 NumExpansions),
3176 Pattern.getTemplateQualifierLoc(),
3177 Pattern.getTemplateNameLoc(),
3178 EllipsisLoc);
3179
3180 case TemplateArgument::Null:
3181 case TemplateArgument::Integral:
3182 case TemplateArgument::Declaration:
3183 case TemplateArgument::Pack:
3184 case TemplateArgument::TemplateExpansion:
3185 case TemplateArgument::NullPtr:
3186 llvm_unreachable("Pack expansion pattern has no parameter packs")::llvm::llvm_unreachable_internal("Pack expansion pattern has no parameter packs"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 3186)
;
3187
3188 case TemplateArgument::Type:
3189 if (TypeSourceInfo *Expansion
3190 = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3191 EllipsisLoc,
3192 NumExpansions))
3193 return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3194 Expansion);
3195 break;
3196 }
3197
3198 return TemplateArgumentLoc();
3199 }
3200
3201 /// \brief Build a new expression pack expansion.
3202 ///
3203 /// By default, performs semantic analysis to build a new pack expansion
3204 /// for an expression. Subclasses may override this routine to provide
3205 /// different behavior.
3206 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3207 Optional<unsigned> NumExpansions) {
3208 return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3209 }
3210
3211 /// \brief Build a new C++1z fold-expression.
3212 ///
3213 /// By default, performs semantic analysis in order to build a new fold
3214 /// expression.
3215 ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
3216 BinaryOperatorKind Operator,
3217 SourceLocation EllipsisLoc, Expr *RHS,
3218 SourceLocation RParenLoc) {
3219 return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
3220 RHS, RParenLoc);
3221 }
3222
3223 /// \brief Build an empty C++1z fold-expression with the given operator.
3224 ///
3225 /// By default, produces the fallback value for the fold-expression, or
3226 /// produce an error if there is no fallback value.
3227 ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3228 BinaryOperatorKind Operator) {
3229 return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3230 }
3231
3232 /// \brief Build a new atomic operation expression.
3233 ///
3234 /// By default, performs semantic analysis to build the new expression.
3235 /// Subclasses may override this routine to provide different behavior.
3236 ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc,
3237 MultiExprArg SubExprs,
3238 QualType RetTy,
3239 AtomicExpr::AtomicOp Op,
3240 SourceLocation RParenLoc) {
3241 // Just create the expression; there is not any interesting semantic
3242 // analysis here because we can't actually build an AtomicExpr until
3243 // we are sure it is semantically sound.
3244 return new (SemaRef.Context) AtomicExpr(BuiltinLoc, SubExprs, RetTy, Op,
3245 RParenLoc);
3246 }
3247
3248private:
3249 TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3250 QualType ObjectType,
3251 NamedDecl *FirstQualifierInScope,
3252 CXXScopeSpec &SS);
3253
3254 TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3255 QualType ObjectType,
3256 NamedDecl *FirstQualifierInScope,
3257 CXXScopeSpec &SS);
3258
3259 TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3260 NamedDecl *FirstQualifierInScope,
3261 CXXScopeSpec &SS);
3262
3263 QualType TransformDependentNameType(TypeLocBuilder &TLB,
3264 DependentNameTypeLoc TL,
3265 bool DeducibleTSTContext);
3266};
3267
3268template<typename Derived>
3269StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S) {
3270 if (!S)
3271 return S;
3272
3273 switch (S->getStmtClass()) {
3274 case Stmt::NoStmtClass: break;
3275
3276 // Transform individual statement nodes
3277#define STMT(Node, Parent) \
3278 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3279#define ABSTRACT_STMT(Node)
3280#define EXPR(Node, Parent)
3281#include "clang/AST/StmtNodes.inc"
3282
3283 // Transform expressions by calling TransformExpr.
3284#define STMT(Node, Parent)
3285#define ABSTRACT_STMT(Stmt)
3286#define EXPR(Node, Parent) case Stmt::Node##Class:
3287#include "clang/AST/StmtNodes.inc"
3288 {
3289 ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3290 if (E.isInvalid())
3291 return StmtError();
3292
3293 return getSema().ActOnExprStmt(E);
3294 }
3295 }
3296
3297 return S;
3298}
3299
3300template<typename Derived>
3301OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3302 if (!S)
3303 return S;
3304
3305 switch (S->getClauseKind()) {
3306 default: break;
3307 // Transform individual clause nodes
3308#define OPENMP_CLAUSE(Name, Class) \
3309 case OMPC_ ## Name : \
3310 return getDerived().Transform ## Class(cast<Class>(S));
3311#include "clang/Basic/OpenMPKinds.def"
3312 }
3313
3314 return S;
3315}
3316
3317
3318template<typename Derived>
3319ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3320 if (!E)
3321 return E;
3322
3323 switch (E->getStmtClass()) {
3324 case Stmt::NoStmtClass: break;
3325#define STMT(Node, Parent) case Stmt::Node##Class: break;
3326#define ABSTRACT_STMT(Stmt)
3327#define EXPR(Node, Parent) \
3328 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3329#include "clang/AST/StmtNodes.inc"
3330 }
3331
3332 return E;
3333}
3334
3335template<typename Derived>
3336ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3337 bool NotCopyInit) {
3338 // Initializers are instantiated like expressions, except that various outer
3339 // layers are stripped.
3340 if (!Init)
3341 return Init;
3342
3343 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
3344 Init = ExprTemp->getSubExpr();
3345
3346 if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init))
3347 Init = AIL->getCommonExpr();
3348
3349 if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3350 Init = MTE->GetTemporaryExpr();
3351
3352 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3353 Init = Binder->getSubExpr();
3354
3355 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3356 Init = ICE->getSubExprAsWritten();
3357
3358 if (CXXStdInitializerListExpr *ILE =
3359 dyn_cast<CXXStdInitializerListExpr>(Init))
3360 return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3361
3362 // If this is copy-initialization, we only need to reconstruct
3363 // InitListExprs. Other forms of copy-initialization will be a no-op if
3364 // the initializer is already the right type.
3365 CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3366 if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3367 return getDerived().TransformExpr(Init);
3368
3369 // Revert value-initialization back to empty parens.
3370 if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3371 SourceRange Parens = VIE->getSourceRange();
3372 return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3373 Parens.getEnd());
3374 }
3375
3376 // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3377 if (isa<ImplicitValueInitExpr>(Init))
3378 return getDerived().RebuildParenListExpr(SourceLocation(), None,
3379 SourceLocation());
3380
3381 // Revert initialization by constructor back to a parenthesized or braced list
3382 // of expressions. Any other form of initializer can just be reused directly.
3383 if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3384 return getDerived().TransformExpr(Init);
3385
3386 // If the initialization implicitly converted an initializer list to a
3387 // std::initializer_list object, unwrap the std::initializer_list too.
3388 if (Construct && Construct->isStdInitListInitialization())
3389 return TransformInitializer(Construct->getArg(0), NotCopyInit);
3390
3391 SmallVector<Expr*, 8> NewArgs;
3392 bool ArgChanged = false;
3393 if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3394 /*IsCall*/true, NewArgs, &ArgChanged))
3395 return ExprError();
3396
3397 // If this was list initialization, revert to list form.
3398 if (Construct->isListInitialization())
3399 return getDerived().RebuildInitList(Construct->getLocStart(), NewArgs,
3400 Construct->getLocEnd(),
3401 Construct->getType());
3402
3403 // Build a ParenListExpr to represent anything else.
3404 SourceRange Parens = Construct->getParenOrBraceRange();
3405 if (Parens.isInvalid()) {
3406 // This was a variable declaration's initialization for which no initializer
3407 // was specified.
3408 assert(NewArgs.empty() &&(static_cast <bool> (NewArgs.empty() && "no parens or braces but have direct init with arguments?"
) ? void (0) : __assert_fail ("NewArgs.empty() && \"no parens or braces but have direct init with arguments?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 3409, __extension__ __PRETTY_FUNCTION__))
3409 "no parens or braces but have direct init with arguments?")(static_cast <bool> (NewArgs.empty() && "no parens or braces but have direct init with arguments?"
) ? void (0) : __assert_fail ("NewArgs.empty() && \"no parens or braces but have direct init with arguments?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 3409, __extension__ __PRETTY_FUNCTION__))
;
3410 return ExprEmpty();
3411 }
3412 return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3413 Parens.getEnd());
3414}
3415
3416template<typename Derived>
3417bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3418 unsigned NumInputs,
3419 bool IsCall,
3420 SmallVectorImpl<Expr *> &Outputs,
3421 bool *ArgChanged) {
3422 for (unsigned I = 0; I != NumInputs; ++I) {
3423 // If requested, drop call arguments that need to be dropped.
3424 if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3425 if (ArgChanged)
3426 *ArgChanged = true;
3427
3428 break;
3429 }
3430
3431 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3432 Expr *Pattern = Expansion->getPattern();
3433
3434 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3435 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3436 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 3436, __extension__ __PRETTY_FUNCTION__))
;
3437
3438 // Determine whether the set of unexpanded parameter packs can and should
3439 // be expanded.
3440 bool Expand = true;
3441 bool RetainExpansion = false;
3442 Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3443 Optional<unsigned> NumExpansions = OrigNumExpansions;
3444 if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3445 Pattern->getSourceRange(),
3446 Unexpanded,
3447 Expand, RetainExpansion,
3448 NumExpansions))
3449 return true;
3450
3451 if (!Expand) {
3452 // The transform has determined that we should perform a simple
3453 // transformation on the pack expansion, producing another pack
3454 // expansion.
3455 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3456 ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3457 if (OutPattern.isInvalid())
3458 return true;
3459
3460 ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3461 Expansion->getEllipsisLoc(),
3462 NumExpansions);
3463 if (Out.isInvalid())
3464 return true;
3465
3466 if (ArgChanged)
3467 *ArgChanged = true;
3468 Outputs.push_back(Out.get());
3469 continue;
3470 }
3471
3472 // Record right away that the argument was changed. This needs
3473 // to happen even if the array expands to nothing.
3474 if (ArgChanged) *ArgChanged = true;
3475
3476 // The transform has determined that we should perform an elementwise
3477 // expansion of the pattern. Do so.
3478 for (unsigned I = 0; I != *NumExpansions; ++I) {
3479 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3480 ExprResult Out = getDerived().TransformExpr(Pattern);
3481 if (Out.isInvalid())
3482 return true;
3483
3484 if (Out.get()->containsUnexpandedParameterPack()) {
3485 Out = getDerived().RebuildPackExpansion(
3486 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3487 if (Out.isInvalid())
3488 return true;
3489 }
3490
3491 Outputs.push_back(Out.get());
3492 }
3493
3494 // If we're supposed to retain a pack expansion, do so by temporarily
3495 // forgetting the partially-substituted parameter pack.
3496 if (RetainExpansion) {
3497 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3498
3499 ExprResult Out = getDerived().TransformExpr(Pattern);
3500 if (Out.isInvalid())
3501 return true;
3502
3503 Out = getDerived().RebuildPackExpansion(
3504 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3505 if (Out.isInvalid())
3506 return true;
3507
3508 Outputs.push_back(Out.get());
3509 }
3510
3511 continue;
3512 }
3513
3514 ExprResult Result =
3515 IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3516 : getDerived().TransformExpr(Inputs[I]);
3517 if (Result.isInvalid())
3518 return true;
3519
3520 if (Result.get() != Inputs[I] && ArgChanged)
3521 *ArgChanged = true;
3522
3523 Outputs.push_back(Result.get());
3524 }
3525
3526 return false;
3527}
3528
3529template <typename Derived>
3530Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
3531 SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
3532 if (Var) {
3533 VarDecl *ConditionVar = cast_or_null<VarDecl>(
3534 getDerived().TransformDefinition(Var->getLocation(), Var));
3535
3536 if (!ConditionVar)
3537 return Sema::ConditionError();
3538
3539 return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
3540 }
3541
3542 if (Expr) {
3543 ExprResult CondExpr = getDerived().TransformExpr(Expr);
3544
3545 if (CondExpr.isInvalid())
3546 return Sema::ConditionError();
3547
3548 return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind);
3549 }
3550
3551 return Sema::ConditionResult();
3552}
3553
3554template<typename Derived>
3555NestedNameSpecifierLoc
3556TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
3557 NestedNameSpecifierLoc NNS,
3558 QualType ObjectType,
3559 NamedDecl *FirstQualifierInScope) {
3560 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
3561 for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
3562 Qualifier = Qualifier.getPrefix())
3563 Qualifiers.push_back(Qualifier);
3564
3565 CXXScopeSpec SS;
3566 while (!Qualifiers.empty()) {
3567 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
3568 NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
3569
3570 switch (QNNS->getKind()) {
3571 case NestedNameSpecifier::Identifier: {
3572 Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
3573 Q.getLocalBeginLoc(), Q.getLocalEndLoc(), ObjectType);
3574 if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
3575 SS, FirstQualifierInScope, false))
3576 return NestedNameSpecifierLoc();
3577 }
3578 break;
3579
3580 case NestedNameSpecifier::Namespace: {
3581 NamespaceDecl *NS
3582 = cast_or_null<NamespaceDecl>(
3583 getDerived().TransformDecl(
3584 Q.getLocalBeginLoc(),
3585 QNNS->getAsNamespace()));
3586 SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
3587 break;
3588 }
3589
3590 case NestedNameSpecifier::NamespaceAlias: {
3591 NamespaceAliasDecl *Alias
3592 = cast_or_null<NamespaceAliasDecl>(
3593 getDerived().TransformDecl(Q.getLocalBeginLoc(),
3594 QNNS->getAsNamespaceAlias()));
3595 SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
3596 Q.getLocalEndLoc());
3597 break;
3598 }
3599
3600 case NestedNameSpecifier::Global:
3601 // There is no meaningful transformation that one could perform on the
3602 // global scope.
3603 SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
3604 break;
3605
3606 case NestedNameSpecifier::Super: {
3607 CXXRecordDecl *RD =
3608 cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
3609 SourceLocation(), QNNS->getAsRecordDecl()));
3610 SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
3611 break;
3612 }
3613
3614 case NestedNameSpecifier::TypeSpecWithTemplate:
3615 case NestedNameSpecifier::TypeSpec: {
3616 TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
3617 FirstQualifierInScope, SS);
3618
3619 if (!TL)
3620 return NestedNameSpecifierLoc();
3621
3622 if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
3623 (SemaRef.getLangOpts().CPlusPlus11 &&
3624 TL.getType()->isEnumeralType())) {
3625 assert(!TL.getType().hasLocalQualifiers() &&(static_cast <bool> (!TL.getType().hasLocalQualifiers()
&& "Can't get cv-qualifiers here") ? void (0) : __assert_fail
("!TL.getType().hasLocalQualifiers() && \"Can't get cv-qualifiers here\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 3626, __extension__ __PRETTY_FUNCTION__))
3626 "Can't get cv-qualifiers here")(static_cast <bool> (!TL.getType().hasLocalQualifiers()
&& "Can't get cv-qualifiers here") ? void (0) : __assert_fail
("!TL.getType().hasLocalQualifiers() && \"Can't get cv-qualifiers here\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 3626, __extension__ __PRETTY_FUNCTION__))
;
3627 if (TL.getType()->isEnumeralType())
3628 SemaRef.Diag(TL.getBeginLoc(),
3629 diag::warn_cxx98_compat_enum_nested_name_spec);
3630 SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
3631 Q.getLocalEndLoc());
3632 break;
3633 }
3634 // If the nested-name-specifier is an invalid type def, don't emit an
3635 // error because a previous error should have already been emitted.
3636 TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
3637 if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
3638 SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
3639 << TL.getType() << SS.getRange();
3640 }
3641 return NestedNameSpecifierLoc();
3642 }
3643 }
3644
3645 // The qualifier-in-scope and object type only apply to the leftmost entity.
3646 FirstQualifierInScope = nullptr;
3647 ObjectType = QualType();
3648 }
3649
3650 // Don't rebuild the nested-name-specifier if we don't have to.
3651 if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
3652 !getDerived().AlwaysRebuild())
3653 return NNS;
3654
3655 // If we can re-use the source-location data from the original
3656 // nested-name-specifier, do so.
3657 if (SS.location_size() == NNS.getDataLength() &&
3658 memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
3659 return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
3660
3661 // Allocate new nested-name-specifier location information.
3662 return SS.getWithLocInContext(SemaRef.Context);
3663}
3664
3665template<typename Derived>
3666DeclarationNameInfo
3667TreeTransform<Derived>
3668::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
3669 DeclarationName Name = NameInfo.getName();
3670 if (!Name)
3671 return DeclarationNameInfo();
3672
3673 switch (Name.getNameKind()) {
3674 case DeclarationName::Identifier:
3675 case DeclarationName::ObjCZeroArgSelector:
3676 case DeclarationName::ObjCOneArgSelector:
3677 case DeclarationName::ObjCMultiArgSelector:
3678 case DeclarationName::CXXOperatorName:
3679 case DeclarationName::CXXLiteralOperatorName:
3680 case DeclarationName::CXXUsingDirective:
3681 return NameInfo;
3682
3683 case DeclarationName::CXXDeductionGuideName: {
3684 TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
3685 TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
3686 getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
3687 if (!NewTemplate)
3688 return DeclarationNameInfo();
3689
3690 DeclarationNameInfo NewNameInfo(NameInfo);
3691 NewNameInfo.setName(
3692 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
3693 return NewNameInfo;
3694 }
3695
3696 case DeclarationName::CXXConstructorName:
3697 case DeclarationName::CXXDestructorName:
3698 case DeclarationName::CXXConversionFunctionName: {
3699 TypeSourceInfo *NewTInfo;
3700 CanQualType NewCanTy;
3701 if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
3702 NewTInfo = getDerived().TransformType(OldTInfo);
3703 if (!NewTInfo)
3704 return DeclarationNameInfo();
3705 NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
3706 }
3707 else {
3708 NewTInfo = nullptr;
3709 TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
3710 QualType NewT = getDerived().TransformType(Name.getCXXNameType());
3711 if (NewT.isNull())
3712 return DeclarationNameInfo();
3713 NewCanTy = SemaRef.Context.getCanonicalType(NewT);
3714 }
3715
3716 DeclarationName NewName
3717 = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
3718 NewCanTy);
3719 DeclarationNameInfo NewNameInfo(NameInfo);
3720 NewNameInfo.setName(NewName);
3721 NewNameInfo.setNamedTypeInfo(NewTInfo);
3722 return NewNameInfo;
3723 }
3724 }
3725
3726 llvm_unreachable("Unknown name kind.")::llvm::llvm_unreachable_internal("Unknown name kind.", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 3726)
;
3727}
3728
3729template<typename Derived>
3730TemplateName
3731TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
3732 TemplateName Name,
3733 SourceLocation NameLoc,
3734 QualType ObjectType,
3735 NamedDecl *FirstQualifierInScope,
3736 bool AllowInjectedClassName) {
3737 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
3738 TemplateDecl *Template = QTN->getTemplateDecl();
3739 assert(Template && "qualified template name must refer to a template")(static_cast <bool> (Template && "qualified template name must refer to a template"
) ? void (0) : __assert_fail ("Template && \"qualified template name must refer to a template\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 3739, __extension__ __PRETTY_FUNCTION__))
;
3740
3741 TemplateDecl *TransTemplate
3742 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3743 Template));
3744 if (!TransTemplate)
3745 return TemplateName();
3746
3747 if (!getDerived().AlwaysRebuild() &&
3748 SS.getScopeRep() == QTN->getQualifier() &&
3749 TransTemplate == Template)
3750 return Name;
3751
3752 return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
3753 TransTemplate);
3754 }
3755
3756 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
3757 if (SS.getScopeRep()) {
3758 // These apply to the scope specifier, not the template.
3759 ObjectType = QualType();
3760 FirstQualifierInScope = nullptr;
3761 }
3762
3763 if (!getDerived().AlwaysRebuild() &&
3764 SS.getScopeRep() == DTN->getQualifier() &&
3765 ObjectType.isNull())
3766 return Name;
3767
3768 if (DTN->isIdentifier()) {
3769 return getDerived().RebuildTemplateName(SS,
3770 *DTN->getIdentifier(),
3771 NameLoc,
3772 ObjectType,
3773 FirstQualifierInScope,
3774 AllowInjectedClassName);
3775 }
3776
3777 return getDerived().RebuildTemplateName(SS, DTN->getOperator(), NameLoc,
3778 ObjectType, AllowInjectedClassName);
3779 }
3780
3781 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3782 TemplateDecl *TransTemplate
3783 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3784 Template));
3785 if (!TransTemplate)
3786 return TemplateName();
3787
3788 if (!getDerived().AlwaysRebuild() &&
3789 TransTemplate == Template)
3790 return Name;
3791
3792 return TemplateName(TransTemplate);
3793 }
3794
3795 if (SubstTemplateTemplateParmPackStorage *SubstPack
3796 = Name.getAsSubstTemplateTemplateParmPack()) {
3797 TemplateTemplateParmDecl *TransParam
3798 = cast_or_null<TemplateTemplateParmDecl>(
3799 getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
3800 if (!TransParam)
3801 return TemplateName();
3802
3803 if (!getDerived().AlwaysRebuild() &&
3804 TransParam == SubstPack->getParameterPack())
3805 return Name;
3806
3807 return getDerived().RebuildTemplateName(TransParam,
3808 SubstPack->getArgumentPack());
3809 }
3810
3811 // These should be getting filtered out before they reach the AST.
3812 llvm_unreachable("overloaded function decl survived to here")::llvm::llvm_unreachable_internal("overloaded function decl survived to here"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 3812)
;
3813}
3814
3815template<typename Derived>
3816void TreeTransform<Derived>::InventTemplateArgumentLoc(
3817 const TemplateArgument &Arg,
3818 TemplateArgumentLoc &Output) {
3819 SourceLocation Loc = getDerived().getBaseLocation();
3820 switch (Arg.getKind()) {
3821 case TemplateArgument::Null:
3822 llvm_unreachable("null template argument in TreeTransform")::llvm::llvm_unreachable_internal("null template argument in TreeTransform"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 3822)
;
3823 break;
3824
3825 case TemplateArgument::Type:
3826 Output = TemplateArgumentLoc(Arg,
3827 SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
3828
3829 break;
3830
3831 case TemplateArgument::Template:
3832 case TemplateArgument::TemplateExpansion: {
3833 NestedNameSpecifierLocBuilder Builder;
3834 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
3835 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
3836 Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
3837 else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3838 Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
3839
3840 if (Arg.getKind() == TemplateArgument::Template)
3841 Output = TemplateArgumentLoc(Arg,
3842 Builder.getWithLocInContext(SemaRef.Context),
3843 Loc);
3844 else
3845 Output = TemplateArgumentLoc(Arg,
3846 Builder.getWithLocInContext(SemaRef.Context),
3847 Loc, Loc);
3848
3849 break;
3850 }
3851
3852 case TemplateArgument::Expression:
3853 Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
3854 break;
3855
3856 case TemplateArgument::Declaration:
3857 case TemplateArgument::Integral:
3858 case TemplateArgument::Pack:
3859 case TemplateArgument::NullPtr:
3860 Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
3861 break;
3862 }
3863}
3864
3865template<typename Derived>
3866bool TreeTransform<Derived>::TransformTemplateArgument(
3867 const TemplateArgumentLoc &Input,
3868 TemplateArgumentLoc &Output, bool Uneval) {
3869 const TemplateArgument &Arg = Input.getArgument();
3870 switch (Arg.getKind()) {
3871 case TemplateArgument::Null:
3872 case TemplateArgument::Integral:
3873 case TemplateArgument::Pack:
3874 case TemplateArgument::Declaration:
3875 case TemplateArgument::NullPtr:
3876 llvm_unreachable("Unexpected TemplateArgument")::llvm::llvm_unreachable_internal("Unexpected TemplateArgument"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 3876)
;
3877
3878 case TemplateArgument::Type: {
3879 TypeSourceInfo *DI = Input.getTypeSourceInfo();
3880 if (!DI)
3881 DI = InventTypeSourceInfo(Input.getArgument().getAsType());
3882
3883 DI = getDerived().TransformType(DI);
3884 if (!DI) return true;
3885
3886 Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3887 return false;
3888 }
3889
3890 case TemplateArgument::Template: {
3891 NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
3892 if (QualifierLoc) {
3893 QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
3894 if (!QualifierLoc)
3895 return true;
3896 }
3897
3898 CXXScopeSpec SS;
3899 SS.Adopt(QualifierLoc);
3900 TemplateName Template
3901 = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
3902 Input.getTemplateNameLoc());
3903 if (Template.isNull())
3904 return true;
3905
3906 Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
3907 Input.getTemplateNameLoc());
3908 return false;
3909 }
3910
3911 case TemplateArgument::TemplateExpansion:
3912 llvm_unreachable("Caller should expand pack expansions")::llvm::llvm_unreachable_internal("Caller should expand pack expansions"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 3912)
;
3913
3914 case TemplateArgument::Expression: {
3915 // Template argument expressions are constant expressions.
3916 EnterExpressionEvaluationContext Unevaluated(
3917 getSema(), Uneval
3918 ? Sema::ExpressionEvaluationContext::Unevaluated
3919 : Sema::ExpressionEvaluationContext::ConstantEvaluated);
3920
3921 Expr *InputExpr = Input.getSourceExpression();
3922 if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
3923
3924 ExprResult E = getDerived().TransformExpr(InputExpr);
3925 E = SemaRef.ActOnConstantExpression(E);
3926 if (E.isInvalid()) return true;
3927 Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
3928 return false;
3929 }
3930 }
3931
3932 // Work around bogus GCC warning
3933 return true;
3934}
3935
3936/// \brief Iterator adaptor that invents template argument location information
3937/// for each of the template arguments in its underlying iterator.
3938template<typename Derived, typename InputIterator>
3939class TemplateArgumentLocInventIterator {
3940 TreeTransform<Derived> &Self;
3941 InputIterator Iter;
3942
3943public:
3944 typedef TemplateArgumentLoc value_type;
3945 typedef TemplateArgumentLoc reference;
3946 typedef typename std::iterator_traits<InputIterator>::difference_type
3947 difference_type;
3948 typedef std::input_iterator_tag iterator_category;
3949
3950 class pointer {
3951 TemplateArgumentLoc Arg;
3952
3953 public:
3954 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
3955
3956 const TemplateArgumentLoc *operator->() const { return &Arg; }
3957 };
3958
3959 TemplateArgumentLocInventIterator() { }
3960
3961 explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
3962 InputIterator Iter)
3963 : Self(Self), Iter(Iter) { }
3964
3965 TemplateArgumentLocInventIterator &operator++() {
3966 ++Iter;
3967 return *this;
3968 }
3969
3970 TemplateArgumentLocInventIterator operator++(int) {
3971 TemplateArgumentLocInventIterator Old(*this);
3972 ++(*this);
3973 return Old;
3974 }
3975
3976 reference operator*() const {
3977 TemplateArgumentLoc Result;
3978 Self.InventTemplateArgumentLoc(*Iter, Result);
3979 return Result;
3980 }
3981
3982 pointer operator->() const { return pointer(**this); }
3983
3984 friend bool operator==(const TemplateArgumentLocInventIterator &X,
3985 const TemplateArgumentLocInventIterator &Y) {
3986 return X.Iter == Y.Iter;
3987 }
3988
3989 friend bool operator!=(const TemplateArgumentLocInventIterator &X,
3990 const TemplateArgumentLocInventIterator &Y) {
3991 return X.Iter != Y.Iter;
3992 }
3993};
3994
3995template<typename Derived>
3996template<typename InputIterator>
3997bool TreeTransform<Derived>::TransformTemplateArguments(
3998 InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
3999 bool Uneval) {
4000 for (; First != Last; ++First) {
4001 TemplateArgumentLoc Out;
4002 TemplateArgumentLoc In = *First;
4003
4004 if (In.getArgument().getKind() == TemplateArgument::Pack) {
4005 // Unpack argument packs, which we translate them into separate
4006 // arguments.
4007 // FIXME: We could do much better if we could guarantee that the
4008 // TemplateArgumentLocInfo for the pack expansion would be usable for
4009 // all of the template arguments in the argument pack.
4010 typedef TemplateArgumentLocInventIterator<Derived,
4011 TemplateArgument::pack_iterator>
4012 PackLocIterator;
4013 if (TransformTemplateArguments(PackLocIterator(*this,
4014 In.getArgument().pack_begin()),
4015 PackLocIterator(*this,
4016 In.getArgument().pack_end()),
4017 Outputs, Uneval))
4018 return true;
4019
4020 continue;
4021 }
4022
4023 if (In.getArgument().isPackExpansion()) {
4024 // We have a pack expansion, for which we will be substituting into
4025 // the pattern.
4026 SourceLocation Ellipsis;
4027 Optional<unsigned> OrigNumExpansions;
4028 TemplateArgumentLoc Pattern
4029 = getSema().getTemplateArgumentPackExpansionPattern(
4030 In, Ellipsis, OrigNumExpansions);
4031
4032 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4033 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4034 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 4034, __extension__ __PRETTY_FUNCTION__))
;
4035
4036 // Determine whether the set of unexpanded parameter packs can and should
4037 // be expanded.
4038 bool Expand = true;
4039 bool RetainExpansion = false;
4040 Optional<unsigned> NumExpansions = OrigNumExpansions;
4041 if (getDerived().TryExpandParameterPacks(Ellipsis,
4042 Pattern.getSourceRange(),
4043 Unexpanded,
4044 Expand,
4045 RetainExpansion,
4046 NumExpansions))
4047 return true;
4048
4049 if (!Expand) {
4050 // The transform has determined that we should perform a simple
4051 // transformation on the pack expansion, producing another pack
4052 // expansion.
4053 TemplateArgumentLoc OutPattern;
4054 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4055 if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4056 return true;
4057
4058 Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4059 NumExpansions);
4060 if (Out.getArgument().isNull())
4061 return true;
4062
4063 Outputs.addArgument(Out);
4064 continue;
4065 }
4066
4067 // The transform has determined that we should perform an elementwise
4068 // expansion of the pattern. Do so.
4069 for (unsigned I = 0; I != *NumExpansions; ++I) {
4070 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4071
4072 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4073 return true;
4074
4075 if (Out.getArgument().containsUnexpandedParameterPack()) {
4076 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4077 OrigNumExpansions);
4078 if (Out.getArgument().isNull())
4079 return true;
4080 }
4081
4082 Outputs.addArgument(Out);
4083 }
4084
4085 // If we're supposed to retain a pack expansion, do so by temporarily
4086 // forgetting the partially-substituted parameter pack.
4087 if (RetainExpansion) {
4088 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4089
4090 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4091 return true;
4092
4093 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4094 OrigNumExpansions);
4095 if (Out.getArgument().isNull())
4096 return true;
4097
4098 Outputs.addArgument(Out);
4099 }
4100
4101 continue;
4102 }
4103
4104 // The simple case:
4105 if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4106 return true;
4107
4108 Outputs.addArgument(Out);
4109 }
4110
4111 return false;
4112
4113}
4114
4115//===----------------------------------------------------------------------===//
4116// Type transformation
4117//===----------------------------------------------------------------------===//
4118
4119template<typename Derived>
4120QualType TreeTransform<Derived>::TransformType(QualType T) {
4121 if (getDerived().AlreadyTransformed(T))
4122 return T;
4123
4124 // Temporary workaround. All of these transformations should
4125 // eventually turn into transformations on TypeLocs.
4126 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4127 getDerived().getBaseLocation());
4128
4129 TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4130
4131 if (!NewDI)
4132 return QualType();
4133
4134 return NewDI->getType();
4135}
4136
4137template<typename Derived>
4138TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4139 // Refine the base location to the type's location.
4140 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4141 getDerived().getBaseEntity());
4142 if (getDerived().AlreadyTransformed(DI->getType()))
4143 return DI;
4144
4145 TypeLocBuilder TLB;
4146
4147 TypeLoc TL = DI->getTypeLoc();
4148 TLB.reserve(TL.getFullDataSize());
4149
4150 QualType Result = getDerived().TransformType(TLB, TL);
4151 if (Result.isNull())
4152 return nullptr;
4153
4154 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4155}
4156
4157template<typename Derived>
4158QualType
4159TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4160 switch (T.getTypeLocClass()) {
4161#define ABSTRACT_TYPELOC(CLASS, PARENT)
4162#define TYPELOC(CLASS, PARENT) \
4163 case TypeLoc::CLASS: \
4164 return getDerived().Transform##CLASS##Type(TLB, \
4165 T.castAs<CLASS##TypeLoc>());
4166#include "clang/AST/TypeLocNodes.def"
4167 }
4168
4169 llvm_unreachable("unhandled type loc!")::llvm::llvm_unreachable_internal("unhandled type loc!", "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 4169)
;
4170}
4171
4172template<typename Derived>
4173QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4174 if (!isa<DependentNameType>(T))
4175 return TransformType(T);
4176
4177 if (getDerived().AlreadyTransformed(T))
4178 return T;
4179 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4180 getDerived().getBaseLocation());
4181 TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4182 return NewDI ? NewDI->getType() : QualType();
4183}
4184
4185template<typename Derived>
4186TypeSourceInfo *
4187TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4188 if (!isa<DependentNameType>(DI->getType()))
4189 return TransformType(DI);
4190
4191 // Refine the base location to the type's location.
4192 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4193 getDerived().getBaseEntity());
4194 if (getDerived().AlreadyTransformed(DI->getType()))
4195 return DI;
4196
4197 TypeLocBuilder TLB;
4198
4199 TypeLoc TL = DI->getTypeLoc();
4200 TLB.reserve(TL.getFullDataSize());
4201
4202 auto QTL = TL.getAs<QualifiedTypeLoc>();
4203 if (QTL)
4204 TL = QTL.getUnqualifiedLoc();
4205
4206 auto DNTL = TL.castAs<DependentNameTypeLoc>();
4207
4208 QualType Result = getDerived().TransformDependentNameType(
4209 TLB, DNTL, /*DeducedTSTContext*/true);
4210 if (Result.isNull())
4211 return nullptr;
4212
4213 if (QTL) {
4214 Result = getDerived().RebuildQualifiedType(
4215 Result, QTL.getBeginLoc(), QTL.getType().getLocalQualifiers());
4216 TLB.TypeWasModifiedSafely(Result);
4217 }
4218
4219 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4220}
4221
4222template<typename Derived>
4223QualType
4224TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4225 QualifiedTypeLoc T) {
4226 Qualifiers Quals = T.getType().getLocalQualifiers();
4227
4228 QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4229 if (Result.isNull())
4230 return QualType();
4231
4232 Result = getDerived().RebuildQualifiedType(Result, T.getBeginLoc(), Quals);
4233
4234 // RebuildQualifiedType might have updated the type, but not in a way
4235 // that invalidates the TypeLoc. (There's no location information for
4236 // qualifiers.)
4237 TLB.TypeWasModifiedSafely(Result);
4238
4239 return Result;
4240}
4241
4242template<typename Derived>
4243QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4244 SourceLocation Loc,
4245 Qualifiers Quals) {
4246 // C++ [dcl.fct]p7:
4247 // [When] adding cv-qualifications on top of the function type [...] the
4248 // cv-qualifiers are ignored.
4249 // C++ [dcl.ref]p1:
4250 // when the cv-qualifiers are introduced through the use of a typedef-name
4251 // or decltype-specifier [...] the cv-qualifiers are ignored.
4252 // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4253 // applied to a reference type.
4254 // FIXME: This removes all qualifiers, not just cv-qualifiers!
4255 if (T->isFunctionType() || T->isReferenceType())
4256 return T;
4257
4258 // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4259 // resulting type.
4260 if (Quals.hasObjCLifetime()) {
4261 if (!T->isObjCLifetimeType() && !T->isDependentType())
4262 Quals.removeObjCLifetime();
4263 else if (T.getObjCLifetime()) {
4264 // Objective-C ARC:
4265 // A lifetime qualifier applied to a substituted template parameter
4266 // overrides the lifetime qualifier from the template argument.
4267 const AutoType *AutoTy;
4268 if (const SubstTemplateTypeParmType *SubstTypeParam
4269 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4270 QualType Replacement = SubstTypeParam->getReplacementType();
4271 Qualifiers Qs = Replacement.getQualifiers();
4272 Qs.removeObjCLifetime();
4273 Replacement = SemaRef.Context.getQualifiedType(
4274 Replacement.getUnqualifiedType(), Qs);
4275 T = SemaRef.Context.getSubstTemplateTypeParmType(
4276 SubstTypeParam->getReplacedParameter(), Replacement);
4277 } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4278 // 'auto' types behave the same way as template parameters.
4279 QualType Deduced = AutoTy->getDeducedType();
4280 Qualifiers Qs = Deduced.getQualifiers();
4281 Qs.removeObjCLifetime();
4282 Deduced =
4283 SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4284 T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4285 AutoTy->isDependentType());
4286 } else {
4287 // Otherwise, complain about the addition of a qualifier to an
4288 // already-qualified type.
4289 // FIXME: Why is this check not in Sema::BuildQualifiedType?
4290 SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4291 Quals.removeObjCLifetime();
4292 }
4293 }
4294 }
4295
4296 return SemaRef.BuildQualifiedType(T, Loc, Quals);
4297}
4298
4299template<typename Derived>
4300TypeLoc
4301TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4302 QualType ObjectType,
4303 NamedDecl *UnqualLookup,
4304 CXXScopeSpec &SS) {
4305 if (getDerived().AlreadyTransformed(TL.getType()))
4306 return TL;
4307
4308 TypeSourceInfo *TSI =
4309 TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4310 if (TSI)
4311 return TSI->getTypeLoc();
4312 return TypeLoc();
4313}
4314
4315template<typename Derived>
4316TypeSourceInfo *
4317TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4318 QualType ObjectType,
4319 NamedDecl *UnqualLookup,
4320 CXXScopeSpec &SS) {
4321 if (getDerived().AlreadyTransformed(TSInfo->getType()))
4322 return TSInfo;
4323
4324 return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4325 UnqualLookup, SS);
4326}
4327
4328template <typename Derived>
4329TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4330 TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4331 CXXScopeSpec &SS) {
4332 QualType T = TL.getType();
4333 assert(!getDerived().AlreadyTransformed(T))(static_cast <bool> (!getDerived().AlreadyTransformed(T
)) ? void (0) : __assert_fail ("!getDerived().AlreadyTransformed(T)"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 4333, __extension__ __PRETTY_FUNCTION__))
;
4334
4335 TypeLocBuilder TLB;
4336 QualType Result;
4337
4338 if (isa<TemplateSpecializationType>(T)) {
4339 TemplateSpecializationTypeLoc SpecTL =
4340 TL.castAs<TemplateSpecializationTypeLoc>();
4341
4342 TemplateName Template = getDerived().TransformTemplateName(
4343 SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4344 ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4345 if (Template.isNull())
4346 return nullptr;
4347
4348 Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4349 Template);
4350 } else if (isa<DependentTemplateSpecializationType>(T)) {
4351 DependentTemplateSpecializationTypeLoc SpecTL =
4352 TL.castAs<DependentTemplateSpecializationTypeLoc>();
4353
4354 TemplateName Template
4355 = getDerived().RebuildTemplateName(SS,
4356 *SpecTL.getTypePtr()->getIdentifier(),
4357 SpecTL.getTemplateNameLoc(),
4358 ObjectType, UnqualLookup,
4359 /*AllowInjectedClassName*/true);
4360 if (Template.isNull())
4361 return nullptr;
4362
4363 Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4364 SpecTL,
4365 Template,
4366 SS);
4367 } else {
4368 // Nothing special needs to be done for these.
4369 Result = getDerived().TransformType(TLB, TL);
4370 }
4371
4372 if (Result.isNull())
4373 return nullptr;
4374
4375 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4376}
4377
4378template <class TyLoc> static inline
4379QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4380 TyLoc NewT = TLB.push<TyLoc>(T.getType());
4381 NewT.setNameLoc(T.getNameLoc());
4382 return T.getType();
4383}
4384
4385template<typename Derived>
4386QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4387 BuiltinTypeLoc T) {
4388 BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4389 NewT.setBuiltinLoc(T.getBuiltinLoc());
4390 if (T.needsExtraLocalData())
4391 NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4392 return T.getType();
4393}
4394
4395template<typename Derived>
4396QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4397 ComplexTypeLoc T) {
4398 // FIXME: recurse?
4399 return TransformTypeSpecType(TLB, T);
4400}
4401
4402template <typename Derived>
4403QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4404 AdjustedTypeLoc TL) {
4405 // Adjustments applied during transformation are handled elsewhere.
4406 return getDerived().TransformType(TLB, TL.getOriginalLoc());
4407}
4408
4409template<typename Derived>
4410QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
4411 DecayedTypeLoc TL) {
4412 QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
4413 if (OriginalType.isNull())
4414 return QualType();
4415
4416 QualType Result = TL.getType();
4417 if (getDerived().AlwaysRebuild() ||
4418 OriginalType != TL.getOriginalLoc().getType())
4419 Result = SemaRef.Context.getDecayedType(OriginalType);
4420 TLB.push<DecayedTypeLoc>(Result);
4421 // Nothing to set for DecayedTypeLoc.
4422 return Result;
4423}
4424
4425template<typename Derived>
4426QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
4427 PointerTypeLoc TL) {
4428 QualType PointeeType
4429 = getDerived().TransformType(TLB, TL.getPointeeLoc());
4430 if (PointeeType.isNull())
4431 return QualType();
4432
4433 QualType Result = TL.getType();
4434 if (PointeeType->getAs<ObjCObjectType>()) {
4435 // A dependent pointer type 'T *' has is being transformed such
4436 // that an Objective-C class type is being replaced for 'T'. The
4437 // resulting pointer type is an ObjCObjectPointerType, not a
4438 // PointerType.
4439 Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
4440
4441 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
4442 NewT.setStarLoc(TL.getStarLoc());
4443 return Result;
4444 }
4445
4446 if (getDerived().AlwaysRebuild() ||
4447 PointeeType != TL.getPointeeLoc().getType()) {
4448 Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
4449 if (Result.isNull())
4450 return QualType();
4451 }
4452
4453 // Objective-C ARC can add lifetime qualifiers to the type that we're
4454 // pointing to.
4455 TLB.TypeWasModifiedSafely(Result->getPointeeType());
4456
4457 PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
4458 NewT.setSigilLoc(TL.getSigilLoc());
4459 return Result;
4460}
4461
4462template<typename Derived>
4463QualType
4464TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
4465 BlockPointerTypeLoc TL) {
4466 QualType PointeeType
4467 = getDerived().TransformType(TLB, TL.getPointeeLoc());
4468 if (PointeeType.isNull())
4469 return QualType();
4470
4471 QualType Result = TL.getType();
4472 if (getDerived().AlwaysRebuild() ||
4473 PointeeType != TL.getPointeeLoc().getType()) {
4474 Result = getDerived().RebuildBlockPointerType(PointeeType,
4475 TL.getSigilLoc());
4476 if (Result.isNull())
4477 return QualType();
4478 }
4479
4480 BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
4481 NewT.setSigilLoc(TL.getSigilLoc());
4482 return Result;
4483}
4484
4485/// Transforms a reference type. Note that somewhat paradoxically we
4486/// don't care whether the type itself is an l-value type or an r-value
4487/// type; we only care if the type was *written* as an l-value type
4488/// or an r-value type.
4489template<typename Derived>
4490QualType
4491TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
4492 ReferenceTypeLoc TL) {
4493 const ReferenceType *T = TL.getTypePtr();
4494
4495 // Note that this works with the pointee-as-written.
4496 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4497 if (PointeeType.isNull())
4498 return QualType();
4499
4500 QualType Result = TL.getType();
4501 if (getDerived().AlwaysRebuild() ||
4502 PointeeType != T->getPointeeTypeAsWritten()) {
4503 Result = getDerived().RebuildReferenceType(PointeeType,
4504 T->isSpelledAsLValue(),
4505 TL.getSigilLoc());
4506 if (Result.isNull())
4507 return QualType();
4508 }
4509
4510 // Objective-C ARC can add lifetime qualifiers to the type that we're
4511 // referring to.
4512 TLB.TypeWasModifiedSafely(
4513 Result->getAs<ReferenceType>()->getPointeeTypeAsWritten());
4514
4515 // r-value references can be rebuilt as l-value references.
4516 ReferenceTypeLoc NewTL;
4517 if (isa<LValueReferenceType>(Result))
4518 NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
4519 else
4520 NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
4521 NewTL.setSigilLoc(TL.getSigilLoc());
4522
4523 return Result;
4524}
4525
4526template<typename Derived>
4527QualType
4528TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
4529 LValueReferenceTypeLoc TL) {
4530 return TransformReferenceType(TLB, TL);
4531}
4532
4533template<typename Derived>
4534QualType
4535TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
4536 RValueReferenceTypeLoc TL) {
4537 return TransformReferenceType(TLB, TL);
4538}
4539
4540template<typename Derived>
4541QualType
4542TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
4543 MemberPointerTypeLoc TL) {
4544 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4545 if (PointeeType.isNull())
4546 return QualType();
4547
4548 TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
4549 TypeSourceInfo *NewClsTInfo = nullptr;
4550 if (OldClsTInfo) {
4551 NewClsTInfo = getDerived().TransformType(OldClsTInfo);
4552 if (!NewClsTInfo)
4553 return QualType();
4554 }
4555
4556 const MemberPointerType *T = TL.getTypePtr();
4557 QualType OldClsType = QualType(T->getClass(), 0);
4558 QualType NewClsType;
4559 if (NewClsTInfo)
4560 NewClsType = NewClsTInfo->getType();
4561 else {
4562 NewClsType = getDerived().TransformType(OldClsType);
4563 if (NewClsType.isNull())
4564 return QualType();
4565 }
4566
4567 QualType Result = TL.getType();
4568 if (getDerived().AlwaysRebuild() ||
4569 PointeeType != T->getPointeeType() ||
4570 NewClsType != OldClsType) {
4571 Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
4572 TL.getStarLoc());
4573 if (Result.isNull())
4574 return QualType();
4575 }
4576
4577 // If we had to adjust the pointee type when building a member pointer, make
4578 // sure to push TypeLoc info for it.
4579 const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
4580 if (MPT && PointeeType != MPT->getPointeeType()) {
4581 assert(isa<AdjustedType>(MPT->getPointeeType()))(static_cast <bool> (isa<AdjustedType>(MPT->getPointeeType
())) ? void (0) : __assert_fail ("isa<AdjustedType>(MPT->getPointeeType())"
, "/build/llvm-toolchain-snapshot-6.0~svn318693/tools/clang/lib/Sema/TreeTransform.h"
, 4581, __extension__ __PRETTY_FUNCTION__))
;
4582 TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
4583 }
4584
4585 MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
4586 NewTL.setSigilLoc(TL.getSigilLoc());
4587 NewTL.setClassTInfo(NewClsTInfo);
4588
4589 return Result;
4590}
4591
4592template<typename Derived>
4593QualType
4594TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
4595 ConstantArrayTypeLoc TL) {
4596 const ConstantArrayType *T = TL.getTypePtr();
4597 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4598 if (ElementType.isNull())
4599 return QualType();
4600
4601 QualType Result = TL.getType();
4602 if (getDerived().AlwaysRebuild() ||
4603 ElementType != T->getElementType()) {
4604 Result = getDerived().RebuildConstantArrayType(ElementType,
4605 T->getSizeModifier(),
4606 T->getSize(),
4607 T->getIndexTypeCVRQualifiers(),
4608 TL.getBracketsRange());
4609 if (Result.isNull())
4610 return QualType();
4611 }
4612
4613 // We might have either a ConstantArrayType or a VariableArrayType now:
4614 // a ConstantArrayType is allowed to have an element type which is a
4615 // VariableArrayType if the type is dependent. Fortunately, all array
4616 // types have the same location layout.
4617 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4618 NewTL.setLBracketLoc(TL.getLBracketLoc());
4619 NewTL.setRBracketLoc(TL.getRBracketLoc());
4620
4621 Expr *Size = TL.getSizeExpr();
4622 if (Size) {
4623 EnterExpressionEvaluationContext Unevaluated(
4624 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4625 Size = getDerived().TransformExpr(Size).template getAs<Expr>();
4626 Size = SemaRef.ActOnConstantExpression(Size).get();
4627 }
4628 NewTL.setSizeExpr(Size);
4629
4630 return Result;
4631}
4632
4633template<typename Derived>
4634QualType TreeTransform<Derived>::TransformIncompleteArrayType(
4635 TypeLocBuilder &TLB,
4636 IncompleteArrayTypeLoc TL) {
4637 const IncompleteArrayType *T = TL.getTypePtr();
4638 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4639 if (ElementType.isNull())
4640 return QualType();
4641
4642 QualType Result = TL.getType();
4643 if (getDerived().AlwaysRebuild() ||
4644 ElementType != T->getElementType()) {
4645 Result = getDerived().RebuildIncompleteArrayType(ElementType,
4646 T->getSizeModifier(),
4647 T->getIndexTypeCVRQualifiers(),
4648 TL.getBracketsRange());
4649 if (Result.isNull())
4650 return QualType();
4651 }
4652
4653 IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
4654 NewTL.setLBracketLoc(TL.getLBracketLoc());
4655 NewTL.setRBracketLoc(TL.getRBracketLoc());
4656 NewTL.setSizeExpr(nullptr);
4657
4658 return Result;
4659}
4660
4661template<typename Derived>
4662QualType
4663TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
4664 VariableArrayTypeLoc TL) {
4665 const VariableArrayType *T = TL.getTypePtr();
4666 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4667 if (ElementType.isNull())
4668 return QualType();
4669
4670 ExprResult SizeResult;
4671 {
4672 EnterExpressionEvaluationContext Context(
4673 SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4674 SizeResult = getDerived().TransformExpr(T->getSizeExpr());
4675 }
4676 if (SizeResult.isInvalid())
4677 return QualType();
4678 SizeResult = SemaRef.ActOnFinishFullExpr(SizeResult.get());
4679 if (SizeResult.isInvalid())
4680 return QualType();
4681
4682 Expr *Size = SizeResult.get();
4683
4684 QualType Result = TL.getType();
4685 if (getDerived().AlwaysRebuild() ||
4686 ElementType != T->getElementType() ||
4687 Size != T->getSizeExpr()) {
4688 Result = getDerived().RebuildVariableArrayType(ElementType,
4689 T->getSizeModifier(),
4690 Size,
4691 T->getIndexTypeCVRQualifiers(),
4692 TL.getBracketsRange());
4693 if (Result.isNull())
4694 return QualType();
4695 }
4696
4697 // We might have constant size array now, but fortunately it has the same
4698 // location layout.
4699 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4700 NewTL.setLBracketLoc(TL.getLBracketLoc());
4701 NewTL.setRBracketLoc(TL.getRBracketLoc());
4702 NewTL.setSizeExpr(Size);
4703
4704 return Result;
4705}
4706
4707template<typename Derived>
4708QualType
4709TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
4710 DependentSizedArrayTypeLoc TL) {
4711 const DependentSizedArrayType *T = TL.getTypePtr();
4712 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4713 if (ElementType.isNull())
4714 return QualType();
4715
4716 // Array bounds are constant expressions.
4717 EnterExpressionEvaluationContext Unevaluated(
4718 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4719
4720 // Prefer the expression from the TypeLoc; the other may have been uniqued.
4721 Expr *origSize = TL.getSizeExpr();
4722 if (!origSize) origSize = T->getSizeExpr();
4723
4724 ExprResult sizeResult
4725 = getDerived().TransformExpr(origSize);
4726 sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
4727 if (sizeResult.isInvalid())
4728 return QualType();
4729
4730 Expr *size = sizeResult.get();
4731
4732 QualType Result = TL.getType();
4733 if (getDerived().AlwaysRebuild() ||
4734 ElementType != T->getElementType() ||
4735 size != origSize) {
4736 Result = getDerived().RebuildDependentSizedArrayType(ElementType,
4737 T->getSizeModifier(),
4738 size,
4739 T->getIndexTypeCVRQualifiers(),
4740 TL.getBracketsRange());
4741 if (Result.isNull())
4742 return QualType();
4743 }
4744
4745 // We might have any sort of array type now, but fortunately they
4746 // all have the same location layout.
4747 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4748 NewTL.setLBracketLoc(TL.getLBracketLoc());
4749 NewTL.setRBracketLoc(TL.getRBracketLoc());
4750 NewTL.setSizeExpr(size);
4751
4752 return Result;
4753}
4754
4755template<typename Derived>
4756QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
4757 TypeLocBuilder &TLB,
4758 DependentSizedExtVectorTypeLoc TL) {
4759 const DependentSizedExtVectorType *T = TL.getTypePtr();
4760
4761 // FIXME: ext vector locs should be nested
4762 QualType ElementType = getDerived().TransformType(T->getElementType());
4763 if (ElementType.isNull())
4764 return QualType();
4765
4766 // Vector sizes are constant expressions.
4767 EnterExpressionEvaluationContext Unevaluated(
4768 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4769
4770 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4771 Size = SemaRef.ActOnConstantExpression(Size);
4772 if (Size.isInvalid())
4773 return QualType();
4774
4775 QualType Result = TL.getType();
4776 if (getDerived().AlwaysRebuild() ||
4777 ElementType != T->getElementType() ||
4778 Size.get() != T->getSizeExpr()) {
4779 Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
4780 Size.get(),
4781 T->getAttributeLoc());
4782 if (Result.isNull())
4783 return QualType();
4784 }
4785
4786 // Result might be dependent or not.
4787 if (isa<DependentSizedExtVectorType>(Result)) {
4788 DependentSizedExtVectorTypeLoc NewTL
4789 = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
4790 NewTL.setNameLoc(TL.getNameLoc());
4791 } else {
4792 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4793 NewTL.setNameLoc(TL.getNameLoc());
4794 }
4795
4796 return Result;
4797}
4798
4799template <typename Derived>
4800QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
4801 TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
4802 const DependentAddressSpaceType *T = TL.getTypePtr();
4803
4804 QualType pointeeType = getDerived().TransformType(T->getPointeeType());
4805
4806 if (pointeeType.isNull())
4807 return QualType();
4808
4809 // Address spaces are constant expressions.
4810 EnterExpressionEvaluationContext Unevaluated(
4811 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4812
4813 ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
4814 AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
4815 if (AddrSpace.isInvalid())
4816 return QualType();
4817
4818 QualType Result = TL.getType();
4819 if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
4820 AddrSpace.get() != T->getAddrSpaceExpr()) {
4821 Result = getDerived().RebuildDependentAddressSpaceType(
4822 pointeeType, AddrSpace.get(), T->getAttributeLoc());
4823 if (Result.isNull())
4824 return QualType();
4825 }
4826
4827 // Result might be dependent or not.
4828 if (isa<DependentAddressSpaceType>(Result)) {
4829 DependentAddressSpaceTypeLoc NewTL =
4830 TLB.push<DependentAddressSpaceTypeLoc>(Result);
4831
4832 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
4833 NewTL.setAttrExprOperand(TL.getAttrExprOperand());
4834 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
4835
4836 } else {
4837 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
4838 Result, getDerived().getBaseLocation());
4839 TransformType(TLB, DI->getTypeLoc());
4840 }
4841
4842 return Result;
4843}
4844
4845template <typename Derived>
4846QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
4847 VectorTypeLoc TL) {
4848 const VectorType *T = TL.getTypePtr();
4849 QualType ElementType = getDerived().TransformType(T->getElementType());
4850 if (ElementType.isNull())
4851 return