Coverage Report

Created: 2020-02-15 09:57

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