Coverage Report

Created: 2022-07-16 07:03

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