Coverage Report

Created: 2021-08-24 07:12

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