Coverage Report

Created: 2019-07-24 05:18

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