Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl 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 for declarations.
9
//
10
//===----------------------------------------------------------------------===/
11
#include "clang/Sema/SemaInternal.h"
12
#include "clang/AST/ASTConsumer.h"
13
#include "clang/AST/ASTContext.h"
14
#include "clang/AST/ASTMutationListener.h"
15
#include "clang/AST/DeclTemplate.h"
16
#include "clang/AST/DeclVisitor.h"
17
#include "clang/AST/DependentDiagnostic.h"
18
#include "clang/AST/Expr.h"
19
#include "clang/AST/ExprCXX.h"
20
#include "clang/AST/PrettyDeclStackTrace.h"
21
#include "clang/AST/TypeLoc.h"
22
#include "clang/Sema/Initialization.h"
23
#include "clang/Sema/Lookup.h"
24
#include "clang/Sema/Template.h"
25
#include "clang/Sema/TemplateInstCallback.h"
26
#include "llvm/Support/TimeProfiler.h"
27
28
using namespace clang;
29
30
5.38k
static bool isDeclWithinFunction(const Decl *D) {
31
5.38k
  const DeclContext *DC = D->getDeclContext();
32
5.38k
  if (DC->isFunctionOrMethod())
33
78
    return true;
34
5.31k
35
5.31k
  if (DC->isRecord())
36
5.31k
    return cast<CXXRecordDecl>(DC)->isLocalClass();
37
0
38
0
  return false;
39
0
}
40
41
template<typename DeclT>
42
static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
43
1.81M
                           const MultiLevelTemplateArgumentList &TemplateArgs) {
44
1.81M
  if (!OldDecl->getQualifierLoc())
45
1.78M
    return false;
46
33.8k
47
33.8k
  assert((NewDecl->getFriendObjectKind() ||
48
33.8k
          !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
49
33.8k
         "non-friend with qualified name defined in dependent context");
50
33.8k
  Sema::ContextRAII SavedContext(
51
33.8k
      SemaRef,
52
33.8k
      const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
53
33.8k
                                    ? 
NewDecl->getLexicalDeclContext()10
54
33.8k
                                    : 
OldDecl->getLexicalDeclContext()33.8k
));
55
33.8k
56
33.8k
  NestedNameSpecifierLoc NewQualifierLoc
57
33.8k
      = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
58
33.8k
                                            TemplateArgs);
59
33.8k
60
33.8k
  if (!NewQualifierLoc)
61
2
    return true;
62
33.8k
63
33.8k
  NewDecl->setQualifierInfo(NewQualifierLoc);
64
33.8k
  return false;
65
33.8k
}
SemaTemplateInstantiateDecl.cpp:bool SubstQualifier<clang::DeclaratorDecl>(clang::Sema&, clang::DeclaratorDecl const*, clang::DeclaratorDecl*, clang::MultiLevelTemplateArgumentList const&)
Line
Count
Source
43
352k
                           const MultiLevelTemplateArgumentList &TemplateArgs) {
44
352k
  if (!OldDecl->getQualifierLoc())
45
345k
    return false;
46
6.64k
47
6.64k
  assert((NewDecl->getFriendObjectKind() ||
48
6.64k
          !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
49
6.64k
         "non-friend with qualified name defined in dependent context");
50
6.64k
  Sema::ContextRAII SavedContext(
51
6.64k
      SemaRef,
52
6.64k
      const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
53
6.64k
                                    ? 
NewDecl->getLexicalDeclContext()0
54
6.64k
                                    : OldDecl->getLexicalDeclContext()));
55
6.64k
56
6.64k
  NestedNameSpecifierLoc NewQualifierLoc
57
6.64k
      = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
58
6.64k
                                            TemplateArgs);
59
6.64k
60
6.64k
  if (!NewQualifierLoc)
61
1
    return true;
62
6.64k
63
6.64k
  NewDecl->setQualifierInfo(NewQualifierLoc);
64
6.64k
  return false;
65
6.64k
}
SemaTemplateInstantiateDecl.cpp:bool SubstQualifier<clang::TagDecl>(clang::Sema&, clang::TagDecl const*, clang::TagDecl*, clang::MultiLevelTemplateArgumentList const&)
Line
Count
Source
43
1.14M
                           const MultiLevelTemplateArgumentList &TemplateArgs) {
44
1.14M
  if (!OldDecl->getQualifierLoc())
45
1.14M
    return false;
46
9
47
9
  assert((NewDecl->getFriendObjectKind() ||
48
9
          !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
49
9
         "non-friend with qualified name defined in dependent context");
50
9
  Sema::ContextRAII SavedContext(
51
9
      SemaRef,
52
9
      const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
53
9
                                    ? 
NewDecl->getLexicalDeclContext()0
54
9
                                    : OldDecl->getLexicalDeclContext()));
55
9
56
9
  NestedNameSpecifierLoc NewQualifierLoc
57
9
      = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
58
9
                                            TemplateArgs);
59
9
60
9
  if (!NewQualifierLoc)
61
0
    return true;
62
9
63
9
  NewDecl->setQualifierInfo(NewQualifierLoc);
64
9
  return false;
65
9
}
SemaTemplateInstantiateDecl.cpp:bool SubstQualifier<clang::FunctionDecl>(clang::Sema&, clang::FunctionDecl const*, clang::FunctionDecl*, clang::MultiLevelTemplateArgumentList const&)
Line
Count
Source
43
320k
                           const MultiLevelTemplateArgumentList &TemplateArgs) {
44
320k
  if (!OldDecl->getQualifierLoc())
45
293k
    return false;
46
27.1k
47
27.1k
  assert((NewDecl->getFriendObjectKind() ||
48
27.1k
          !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
49
27.1k
         "non-friend with qualified name defined in dependent context");
50
27.1k
  Sema::ContextRAII SavedContext(
51
27.1k
      SemaRef,
52
27.1k
      const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
53
27.1k
                                    ? 
NewDecl->getLexicalDeclContext()10
54
27.1k
                                    : 
OldDecl->getLexicalDeclContext()27.1k
));
55
27.1k
56
27.1k
  NestedNameSpecifierLoc NewQualifierLoc
57
27.1k
      = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
58
27.1k
                                            TemplateArgs);
59
27.1k
60
27.1k
  if (!NewQualifierLoc)
61
1
    return true;
62
27.1k
63
27.1k
  NewDecl->setQualifierInfo(NewQualifierLoc);
64
27.1k
  return false;
65
27.1k
}
66
67
bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
68
352k
                                              DeclaratorDecl *NewDecl) {
69
352k
  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
70
352k
}
71
72
bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
73
1.14M
                                              TagDecl *NewDecl) {
74
1.14M
  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
75
1.14M
}
76
77
// Include attribute instantiation code.
78
#include "clang/Sema/AttrTemplateInstantiate.inc"
79
80
static void instantiateDependentAlignedAttr(
81
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
82
194
    const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
83
194
  if (Aligned->isAlignmentExpr()) {
84
194
    // The alignment expression is a constant expression.
85
194
    EnterExpressionEvaluationContext Unevaluated(
86
194
        S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
87
194
    ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
88
194
    if (!Result.isInvalid())
89
194
      S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
90
194
                       Aligned->getSpellingListIndex(), IsPackExpansion);
91
194
  } else {
92
0
    TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
93
0
                                         TemplateArgs, Aligned->getLocation(),
94
0
                                         DeclarationName());
95
0
    if (Result)
96
0
      S.AddAlignedAttr(Aligned->getLocation(), New, Result,
97
0
                       Aligned->getSpellingListIndex(), IsPackExpansion);
98
0
  }
99
194
}
100
101
static void instantiateDependentAlignedAttr(
102
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
103
188
    const AlignedAttr *Aligned, Decl *New) {
104
188
  if (!Aligned->isPackExpansion()) {
105
177
    instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
106
177
    return;
107
177
  }
108
11
109
11
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
110
11
  if (Aligned->isAlignmentExpr())
111
11
    S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
112
11
                                      Unexpanded);
113
0
  else
114
0
    S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
115
0
                                      Unexpanded);
116
11
  assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
117
11
118
11
  // Determine whether we can expand this attribute pack yet.
119
11
  bool Expand = true, RetainExpansion = false;
120
11
  Optional<unsigned> NumExpansions;
121
11
  // FIXME: Use the actual location of the ellipsis.
122
11
  SourceLocation EllipsisLoc = Aligned->getLocation();
123
11
  if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
124
11
                                        Unexpanded, TemplateArgs, Expand,
125
11
                                        RetainExpansion, NumExpansions))
126
1
    return;
127
10
128
10
  if (!Expand) {
129
0
    Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
130
0
    instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
131
10
  } else {
132
27
    for (unsigned I = 0; I != *NumExpansions; 
++I17
) {
133
17
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
134
17
      instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
135
17
    }
136
10
  }
137
10
}
138
139
static void instantiateDependentAssumeAlignedAttr(
140
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
141
10
    const AssumeAlignedAttr *Aligned, Decl *New) {
142
10
  // The alignment expression is a constant expression.
143
10
  EnterExpressionEvaluationContext Unevaluated(
144
10
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
145
10
146
10
  Expr *E, *OE = nullptr;
147
10
  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
148
10
  if (Result.isInvalid())
149
2
    return;
150
8
  E = Result.getAs<Expr>();
151
8
152
8
  if (Aligned->getOffset()) {
153
3
    Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
154
3
    if (Result.isInvalid())
155
0
      return;
156
3
    OE = Result.getAs<Expr>();
157
3
  }
158
8
159
8
  S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE,
160
8
                         Aligned->getSpellingListIndex());
161
8
}
162
163
static void instantiateDependentAlignValueAttr(
164
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
165
3
    const AlignValueAttr *Aligned, Decl *New) {
166
3
  // The alignment expression is a constant expression.
167
3
  EnterExpressionEvaluationContext Unevaluated(
168
3
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
169
3
  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
170
3
  if (!Result.isInvalid())
171
3
    S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
172
3
                        Aligned->getSpellingListIndex());
173
3
}
174
175
static void instantiateDependentAllocAlignAttr(
176
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
177
8
    const AllocAlignAttr *Align, Decl *New) {
178
8
  Expr *Param = IntegerLiteral::Create(
179
8
      S.getASTContext(),
180
8
      llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
181
8
      S.getASTContext().UnsignedLongLongTy, Align->getLocation());
182
8
  S.AddAllocAlignAttr(Align->getLocation(), New, Param,
183
8
                      Align->getSpellingListIndex());
184
8
}
185
186
static Expr *instantiateDependentFunctionAttrCondition(
187
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
188
537
    const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
189
537
  Expr *Cond = nullptr;
190
537
  {
191
537
    Sema::ContextRAII SwitchContext(S, New);
192
537
    EnterExpressionEvaluationContext Unevaluated(
193
537
        S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
194
537
    ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
195
537
    if (Result.isInvalid())
196
0
      return nullptr;
197
537
    Cond = Result.getAs<Expr>();
198
537
  }
199
537
  if (!Cond->isTypeDependent()) {
200
537
    ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
201
537
    if (Converted.isInvalid())
202
1
      return nullptr;
203
536
    Cond = Converted.get();
204
536
  }
205
537
206
537
  SmallVector<PartialDiagnosticAt, 8> Diags;
207
536
  if (OldCond->isValueDependent() && 
!Cond->isValueDependent()208
&&
208
536
      
!Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)208
) {
209
0
    S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
210
0
    for (const auto &P : Diags)
211
0
      S.Diag(P.first, P.second);
212
0
    return nullptr;
213
0
  }
214
536
  return Cond;
215
536
}
216
217
static void instantiateDependentEnableIfAttr(
218
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
219
17
    const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
220
17
  Expr *Cond = instantiateDependentFunctionAttrCondition(
221
17
      S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
222
17
223
17
  if (Cond)
224
16
    New->addAttr(new (S.getASTContext()) EnableIfAttr(
225
16
        EIA->getLocation(), S.getASTContext(), Cond, EIA->getMessage(),
226
16
        EIA->getSpellingListIndex()));
227
17
}
228
229
static void instantiateDependentDiagnoseIfAttr(
230
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
231
520
    const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
232
520
  Expr *Cond = instantiateDependentFunctionAttrCondition(
233
520
      S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
234
520
235
520
  if (Cond)
236
520
    New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
237
520
        DIA->getLocation(), S.getASTContext(), Cond, DIA->getMessage(),
238
520
        DIA->getDiagnosticType(), DIA->getArgDependent(), New,
239
520
        DIA->getSpellingListIndex()));
240
520
}
241
242
// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
243
// template A as the base and arguments from TemplateArgs.
244
static void instantiateDependentCUDALaunchBoundsAttr(
245
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
246
6
    const CUDALaunchBoundsAttr &Attr, Decl *New) {
247
6
  // The alignment expression is a constant expression.
248
6
  EnterExpressionEvaluationContext Unevaluated(
249
6
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
250
6
251
6
  ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
252
6
  if (Result.isInvalid())
253
0
    return;
254
6
  Expr *MaxThreads = Result.getAs<Expr>();
255
6
256
6
  Expr *MinBlocks = nullptr;
257
6
  if (Attr.getMinBlocks()) {
258
4
    Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
259
4
    if (Result.isInvalid())
260
0
      return;
261
4
    MinBlocks = Result.getAs<Expr>();
262
4
  }
263
6
264
6
  S.AddLaunchBoundsAttr(Attr.getLocation(), New, MaxThreads, MinBlocks,
265
6
                        Attr.getSpellingListIndex());
266
6
}
267
268
static void
269
instantiateDependentModeAttr(Sema &S,
270
                             const MultiLevelTemplateArgumentList &TemplateArgs,
271
84
                             const ModeAttr &Attr, Decl *New) {
272
84
  S.AddModeAttr(Attr.getRange(), New, Attr.getMode(),
273
84
                Attr.getSpellingListIndex(), /*InInstantiation=*/true);
274
84
}
275
276
/// Instantiation of 'declare simd' attribute and its arguments.
277
static void instantiateOMPDeclareSimdDeclAttr(
278
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
279
58
    const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
280
58
  // Allow 'this' in clauses with varlists.
281
58
  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
282
0
    New = FTD->getTemplatedDecl();
283
58
  auto *FD = cast<FunctionDecl>(New);
284
58
  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
285
58
  SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
286
58
  SmallVector<unsigned, 4> LinModifiers;
287
58
288
110
  auto SubstExpr = [&](Expr *E) -> ExprResult {
289
110
    if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
290
102
      if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
291
80
        Sema::ContextRAII SavedContext(S, FD);
292
80
        LocalInstantiationScope Local(S);
293
80
        if (FD->getNumParams() > PVD->getFunctionScopeIndex())
294
80
          Local.InstantiatedLocal(
295
80
              PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
296
80
        return S.SubstExpr(E, TemplateArgs);
297
80
      }
298
30
    Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
299
30
                                     FD->isCXXInstanceMember());
300
30
    return S.SubstExpr(E, TemplateArgs);
301
30
  };
302
58
303
58
  // Substitute a single OpenMP clause, which is a potentially-evaluated
304
58
  // full-expression.
305
110
  auto Subst = [&](Expr *E) -> ExprResult {
306
110
    EnterExpressionEvaluationContext Evaluated(
307
110
        S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
308
110
    ExprResult Res = SubstExpr(E);
309
110
    if (Res.isInvalid())
310
0
      return Res;
311
110
    return S.ActOnFinishFullExpr(Res.get(), false);
312
110
  };
313
58
314
58
  ExprResult Simdlen;
315
58
  if (auto *E = Attr.getSimdlen())
316
18
    Simdlen = Subst(E);
317
58
318
58
  if (Attr.uniforms_size() > 0) {
319
18
    for(auto *E : Attr.uniforms()) {
320
18
      ExprResult Inst = Subst(E);
321
18
      if (Inst.isInvalid())
322
0
        continue;
323
18
      Uniforms.push_back(Inst.get());
324
18
    }
325
10
  }
326
58
327
58
  auto AI = Attr.alignments_begin();
328
58
  for (auto *E : Attr.aligneds()) {
329
58
    ExprResult Inst = Subst(E);
330
58
    if (Inst.isInvalid())
331
0
      continue;
332
58
    Aligneds.push_back(Inst.get());
333
58
    Inst = ExprEmpty();
334
58
    if (*AI)
335
16
      Inst = S.SubstExpr(*AI, TemplateArgs);
336
58
    Alignments.push_back(Inst.get());
337
58
    ++AI;
338
58
  }
339
58
340
58
  auto SI = Attr.steps_begin();
341
58
  for (auto *E : Attr.linears()) {
342
16
    ExprResult Inst = Subst(E);
343
16
    if (Inst.isInvalid())
344
0
      continue;
345
16
    Linears.push_back(Inst.get());
346
16
    Inst = ExprEmpty();
347
16
    if (*SI)
348
16
      Inst = S.SubstExpr(*SI, TemplateArgs);
349
16
    Steps.push_back(Inst.get());
350
16
    ++SI;
351
16
  }
352
58
  LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
353
58
  (void)S.ActOnOpenMPDeclareSimdDirective(
354
58
      S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
355
58
      Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
356
58
      Attr.getRange());
357
58
}
358
359
static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
360
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
361
2
    const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
362
2
  // Both min and max expression are constant expressions.
363
2
  EnterExpressionEvaluationContext Unevaluated(
364
2
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
365
2
366
2
  ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
367
2
  if (Result.isInvalid())
368
0
    return;
369
2
  Expr *MinExpr = Result.getAs<Expr>();
370
2
371
2
  Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
372
2
  if (Result.isInvalid())
373
0
    return;
374
2
  Expr *MaxExpr = Result.getAs<Expr>();
375
2
376
2
  S.addAMDGPUFlatWorkGroupSizeAttr(Attr.getLocation(), New, MinExpr, MaxExpr,
377
2
                                   Attr.getSpellingListIndex());
378
2
}
379
380
static ExplicitSpecifier
381
instantiateExplicitSpecifier(Sema &S,
382
                             const MultiLevelTemplateArgumentList &TemplateArgs,
383
1.70M
                             ExplicitSpecifier ES, FunctionDecl *New) {
384
1.70M
  if (!ES.getExpr())
385
1.70M
    return ES;
386
184
  Expr *OldCond = ES.getExpr();
387
184
  Expr *Cond = nullptr;
388
184
  {
389
184
    EnterExpressionEvaluationContext Unevaluated(
390
184
        S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
391
184
    ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
392
184
    if (SubstResult.isInvalid()) {
393
71
      return ExplicitSpecifier::Invalid();
394
71
    }
395
113
    Cond = SubstResult.get();
396
113
  }
397
113
  ExplicitSpecifier Result(Cond, ES.getKind());
398
113
  if (!Cond->isTypeDependent())
399
98
    S.tryResolveExplicitSpecifier(Result);
400
113
  return Result;
401
113
}
402
403
static void instantiateDependentAMDGPUWavesPerEUAttr(
404
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
405
3
    const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
406
3
  // Both min and max expression are constant expressions.
407
3
  EnterExpressionEvaluationContext Unevaluated(
408
3
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
409
3
410
3
  ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
411
3
  if (Result.isInvalid())
412
0
    return;
413
3
  Expr *MinExpr = Result.getAs<Expr>();
414
3
415
3
  Expr *MaxExpr = nullptr;
416
3
  if (auto Max = Attr.getMax()) {
417
2
    Result = S.SubstExpr(Max, TemplateArgs);
418
2
    if (Result.isInvalid())
419
0
      return;
420
2
    MaxExpr = Result.getAs<Expr>();
421
2
  }
422
3
423
3
  S.addAMDGPUWavesPerEUAttr(Attr.getLocation(), New, MinExpr, MaxExpr,
424
3
                            Attr.getSpellingListIndex());
425
3
}
426
427
void Sema::InstantiateAttrsForDecl(
428
    const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
429
    Decl *New, LateInstantiatedAttrVec *LateAttrs,
430
2.42M
    LocalInstantiationScope *OuterMostScope) {
431
2.42M
  if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
432
2.42M
    for (const auto *TmplAttr : Tmpl->attrs()) {
433
731k
      // FIXME: If any of the special case versions from InstantiateAttrs become
434
731k
      // applicable to template declaration, we'll need to add them here.
435
731k
      CXXThisScopeRAII ThisScope(
436
731k
          *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
437
731k
          Qualifiers(), ND->isCXXInstanceMember());
438
731k
439
731k
      Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
440
731k
          TmplAttr, Context, *this, TemplateArgs);
441
731k
      if (NewAttr)
442
45
        New->addAttr(NewAttr);
443
731k
    }
444
2.42M
  }
445
2.42M
}
446
447
static Sema::RetainOwnershipKind
448
89
attrToRetainOwnershipKind(const Attr *A) {
449
89
  switch (A->getKind()) {
450
89
  case clang::attr::CFConsumed:
451
0
    return Sema::RetainOwnershipKind::CF;
452
89
  case clang::attr::OSConsumed:
453
0
    return Sema::RetainOwnershipKind::OS;
454
89
  case clang::attr::NSConsumed:
455
89
    return Sema::RetainOwnershipKind::NS;
456
89
  default:
457
0
    llvm_unreachable("Wrong argument supplied");
458
89
  }
459
89
}
460
461
void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
462
                            const Decl *Tmpl, Decl *New,
463
                            LateInstantiatedAttrVec *LateAttrs,
464
6.90M
                            LocalInstantiationScope *OuterMostScope) {
465
6.90M
  for (const auto *TmplAttr : Tmpl->attrs()) {
466
2.72M
    // FIXME: This should be generalized to more than just the AlignedAttr.
467
2.72M
    const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
468
2.72M
    if (Aligned && 
Aligned->isAlignmentDependent()1.92k
) {
469
188
      instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
470
188
      continue;
471
188
    }
472
2.72M
473
2.72M
    const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr);
474
2.72M
    if (AssumeAligned) {
475
10
      instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
476
10
      continue;
477
10
    }
478
2.72M
479
2.72M
    const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr);
480
2.72M
    if (AlignValue) {
481
3
      instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
482
3
      continue;
483
3
    }
484
2.72M
485
2.72M
    if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
486
8
      instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
487
8
      continue;
488
8
    }
489
2.72M
490
2.72M
491
2.72M
    if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
492
17
      instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
493
17
                                       cast<FunctionDecl>(New));
494
17
      continue;
495
17
    }
496
2.72M
497
2.72M
    if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
498
520
      instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
499
520
                                         cast<FunctionDecl>(New));
500
520
      continue;
501
520
    }
502
2.72M
503
2.72M
    if (const CUDALaunchBoundsAttr *CUDALaunchBounds =
504
6
            dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
505
6
      instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
506
6
                                               *CUDALaunchBounds, New);
507
6
      continue;
508
6
    }
509
2.72M
510
2.72M
    if (const ModeAttr *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
511
84
      instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
512
84
      continue;
513
84
    }
514
2.72M
515
2.72M
    if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
516
58
      instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
517
58
      continue;
518
58
    }
519
2.72M
520
2.72M
    if (const AMDGPUFlatWorkGroupSizeAttr *AMDGPUFlatWorkGroupSize =
521
2
            dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
522
2
      instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
523
2
          *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
524
2
    }
525
2.72M
526
2.72M
    if (const AMDGPUWavesPerEUAttr *AMDGPUFlatWorkGroupSize =
527
3
            dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
528
3
      instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
529
3
                                               *AMDGPUFlatWorkGroupSize, New);
530
3
    }
531
2.72M
532
2.72M
    // Existing DLL attribute on the instantiation takes precedence.
533
2.72M
    if (TmplAttr->getKind() == attr::DLLExport ||
534
2.72M
        
TmplAttr->getKind() == attr::DLLImport2.71M
) {
535
1.04k
      if (New->hasAttr<DLLExportAttr>() || 
New->hasAttr<DLLImportAttr>()1.03k
) {
536
24
        continue;
537
24
      }
538
2.72M
    }
539
2.72M
540
2.72M
    if (auto ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
541
6
      AddParameterABIAttr(ABIAttr->getRange(), New, ABIAttr->getABI(),
542
6
                          ABIAttr->getSpellingListIndex());
543
6
      continue;
544
6
    }
545
2.72M
546
2.72M
    if (isa<NSConsumedAttr>(TmplAttr) || 
isa<OSConsumedAttr>(TmplAttr)2.71M
||
547
2.72M
        
isa<CFConsumedAttr>(TmplAttr)2.71M
) {
548
89
      AddXConsumedAttr(New, TmplAttr->getRange(),
549
89
                       TmplAttr->getSpellingListIndex(),
550
89
                       attrToRetainOwnershipKind(TmplAttr),
551
89
                       /*template instantiation=*/true);
552
89
      continue;
553
89
    }
554
2.71M
555
2.71M
    assert(!TmplAttr->isPackExpansion());
556
2.71M
    if (TmplAttr->isLateParsed() && 
LateAttrs130
) {
557
82
      // Late parsed attributes must be instantiated and attached after the
558
82
      // enclosing class has been instantiated.  See Sema::InstantiateClass.
559
82
      LocalInstantiationScope *Saved = nullptr;
560
82
      if (CurrentInstantiationScope)
561
82
        Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
562
82
      LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
563
2.71M
    } else {
564
2.71M
      // Allow 'this' within late-parsed attributes.
565
2.71M
      NamedDecl *ND = dyn_cast<NamedDecl>(New);
566
2.71M
      CXXRecordDecl *ThisContext =
567
2.71M
          dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
568
2.71M
      CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
569
2.71M
                                 ND && ND->isCXXInstanceMember());
570
2.71M
571
2.71M
      Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
572
2.71M
                                                         *this, TemplateArgs);
573
2.71M
      if (NewAttr)
574
1.18M
        New->addAttr(NewAttr);
575
2.71M
    }
576
2.71M
  }
577
6.90M
}
578
579
/// Get the previous declaration of a declaration for the purposes of template
580
/// instantiation. If this finds a previous declaration, then the previous
581
/// declaration of the instantiation of D should be an instantiation of the
582
/// result of this function.
583
template<typename DeclT>
584
961k
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
585
961k
  DeclT *Result = D->getPreviousDecl();
586
961k
587
961k
  // If the declaration is within a class, and the previous declaration was
588
961k
  // merged from a different definition of that class, then we don't have a
589
961k
  // previous declaration for the purpose of template instantiation.
590
961k
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())450
&&
591
961k
      
D->getLexicalDeclContext() != Result->getLexicalDeclContext()23
)
592
5
    return nullptr;
593
961k
594
961k
  return Result;
595
961k
}
SemaTemplateInstantiateDecl.cpp:clang::TypedefNameDecl* getPreviousDeclForInstantiation<clang::TypedefNameDecl>(clang::TypedefNameDecl*)
Line
Count
Source
584
910k
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
585
910k
  DeclT *Result = D->getPreviousDecl();
586
910k
587
910k
  // If the declaration is within a class, and the previous declaration was
588
910k
  // merged from a different definition of that class, then we don't have a
589
910k
  // previous declaration for the purpose of template instantiation.
590
910k
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())399
&&
591
910k
      
D->getLexicalDeclContext() != Result->getLexicalDeclContext()0
)
592
0
    return nullptr;
593
910k
594
910k
  return Result;
595
910k
}
SemaTemplateInstantiateDecl.cpp:clang::EnumDecl* getPreviousDeclForInstantiation<clang::EnumDecl>(clang::EnumDecl*)
Line
Count
Source
584
5.34k
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
585
5.34k
  DeclT *Result = D->getPreviousDecl();
586
5.34k
587
5.34k
  // If the declaration is within a class, and the previous declaration was
588
5.34k
  // merged from a different definition of that class, then we don't have a
589
5.34k
  // previous declaration for the purpose of template instantiation.
590
5.34k
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())16
&&
591
5.34k
      
D->getLexicalDeclContext() != Result->getLexicalDeclContext()0
)
592
0
    return nullptr;
593
5.34k
594
5.34k
  return Result;
595
5.34k
}
SemaTemplateInstantiateDecl.cpp:clang::CXXRecordDecl* getPreviousDeclForInstantiation<clang::CXXRecordDecl>(clang::CXXRecordDecl*)
Line
Count
Source
584
45.5k
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
585
45.5k
  DeclT *Result = D->getPreviousDecl();
586
45.5k
587
45.5k
  // If the declaration is within a class, and the previous declaration was
588
45.5k
  // merged from a different definition of that class, then we don't have a
589
45.5k
  // previous declaration for the purpose of template instantiation.
590
45.5k
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())35
&&
591
45.5k
      
D->getLexicalDeclContext() != Result->getLexicalDeclContext()23
)
592
5
    return nullptr;
593
45.5k
594
45.5k
  return Result;
595
45.5k
}
SemaTemplateInstantiateDecl.cpp:clang::VarDecl* getPreviousDeclForInstantiation<clang::VarDecl>(clang::VarDecl*)
Line
Count
Source
584
183
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
585
183
  DeclT *Result = D->getPreviousDecl();
586
183
587
183
  // If the declaration is within a class, and the previous declaration was
588
183
  // merged from a different definition of that class, then we don't have a
589
183
  // previous declaration for the purpose of template instantiation.
590
183
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())0
&&
591
183
      
D->getLexicalDeclContext() != Result->getLexicalDeclContext()0
)
592
0
    return nullptr;
593
183
594
183
  return Result;
595
183
}
SemaTemplateInstantiateDecl.cpp:clang::FunctionTemplateDecl* getPreviousDeclForInstantiation<clang::FunctionTemplateDecl>(clang::FunctionTemplateDecl*)
Line
Count
Source
584
6
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
585
6
  DeclT *Result = D->getPreviousDecl();
586
6
587
6
  // If the declaration is within a class, and the previous declaration was
588
6
  // merged from a different definition of that class, then we don't have a
589
6
  // previous declaration for the purpose of template instantiation.
590
6
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())0
&&
591
6
      
D->getLexicalDeclContext() != Result->getLexicalDeclContext()0
)
592
0
    return nullptr;
593
6
594
6
  return Result;
595
6
}
SemaTemplateInstantiateDecl.cpp:clang::UsingShadowDecl* getPreviousDeclForInstantiation<clang::UsingShadowDecl>(clang::UsingShadowDecl*)
Line
Count
Source
584
58
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
585
58
  DeclT *Result = D->getPreviousDecl();
586
58
587
58
  // If the declaration is within a class, and the previous declaration was
588
58
  // merged from a different definition of that class, then we don't have a
589
58
  // previous declaration for the purpose of template instantiation.
590
58
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())0
&&
591
58
      
D->getLexicalDeclContext() != Result->getLexicalDeclContext()0
)
592
0
    return nullptr;
593
58
594
58
  return Result;
595
58
}
596
597
Decl *
598
0
TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
599
0
  llvm_unreachable("Translation units cannot be instantiated");
600
0
}
601
602
Decl *
603
0
TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
604
0
  llvm_unreachable("pragma comment cannot be instantiated");
605
0
}
606
607
Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
608
0
    PragmaDetectMismatchDecl *D) {
609
0
  llvm_unreachable("pragma comment cannot be instantiated");
610
0
}
611
612
Decl *
613
0
TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
614
0
  llvm_unreachable("extern \"C\" context cannot be instantiated");
615
0
}
616
617
Decl *
618
321
TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
619
321
  LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
620
321
                                      D->getIdentifier());
621
321
  Owner->addDecl(Inst);
622
321
  return Inst;
623
321
}
624
625
Decl *
626
0
TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
627
0
  llvm_unreachable("Namespaces cannot be instantiated");
628
0
}
629
630
Decl *
631
2
TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
632
2
  NamespaceAliasDecl *Inst
633
2
    = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
634
2
                                 D->getNamespaceLoc(),
635
2
                                 D->getAliasLoc(),
636
2
                                 D->getIdentifier(),
637
2
                                 D->getQualifierLoc(),
638
2
                                 D->getTargetNameLoc(),
639
2
                                 D->getNamespace());
640
2
  Owner->addDecl(Inst);
641
2
  return Inst;
642
2
}
643
644
Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
645
882k
                                                           bool IsTypeAlias) {
646
882k
  bool Invalid = false;
647
882k
  TypeSourceInfo *DI = D->getTypeSourceInfo();
648
882k
  if (DI->getType()->isInstantiationDependentType() ||
649
882k
      
DI->getType()->isVariablyModifiedType()50.8k
) {
650
831k
    DI = SemaRef.SubstType(DI, TemplateArgs,
651
831k
                           D->getLocation(), D->getDeclName());
652
831k
    if (!DI) {
653
185
      Invalid = true;
654
185
      DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
655
185
    }
656
831k
  } else {
657
50.8k
    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
658
50.8k
  }
659
882k
660
882k
  // HACK: g++ has a bug where it gets the value kind of ?: wrong.
661
882k
  // libstdc++ relies upon this bug in its implementation of common_type.
662
882k
  // If we happen to be processing that implementation, fake up the g++ ?:
663
882k
  // semantics. See LWG issue 2141 for more information on the bug.
664
882k
  const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
665
882k
  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
666
882k
  if (DT && 
RD497
&&
isa<ConditionalOperator>(DT->getUnderlyingExpr())459
&&
667
882k
      
DT->isReferenceType()1
&&
668
882k
      
RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace()1
&&
669
882k
      
RD->getIdentifier()1
&&
RD->getIdentifier()->isStr("common_type")1
&&
670
882k
      
D->getIdentifier()1
&&
D->getIdentifier()->isStr("type")1
&&
671
882k
      
SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc())1
)
672
1
    // Fold it to the (non-reference) type which g++ would have produced.
673
1
    DI = SemaRef.Context.getTrivialTypeSourceInfo(
674
1
      DI->getType().getNonReferenceType());
675
882k
676
882k
  // Create the new typedef
677
882k
  TypedefNameDecl *Typedef;
678
882k
  if (IsTypeAlias)
679
40.7k
    Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
680
40.7k
                                    D->getLocation(), D->getIdentifier(), DI);
681
841k
  else
682
841k
    Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
683
841k
                                  D->getLocation(), D->getIdentifier(), DI);
684
882k
  if (Invalid)
685
185
    Typedef->setInvalidDecl();
686
882k
687
882k
  // If the old typedef was the name for linkage purposes of an anonymous
688
882k
  // tag decl, re-establish that relationship for the new typedef.
689
882k
  if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
690
21.2k
    TagDecl *oldTag = oldTagType->getDecl();
691
21.2k
    if (oldTag->getTypedefNameForAnonDecl() == D && 
!Invalid18
) {
692
18
      TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
693
18
      assert(!newTag->hasNameForLinkage());
694
18
      newTag->setTypedefNameForAnonDecl(Typedef);
695
18
    }
696
21.2k
  }
697
882k
698
882k
  if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
699
399
    NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
700
399
                                                       TemplateArgs);
701
399
    if (!InstPrev)
702
0
      return nullptr;
703
399
704
399
    TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
705
399
706
399
    // If the typedef types are not identical, reject them.
707
399
    SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
708
399
709
399
    Typedef->setPreviousDecl(InstPrevTypedef);
710
399
  }
711
882k
712
882k
  SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
713
882k
714
882k
  Typedef->setAccess(D->getAccess());
715
882k
716
882k
  return Typedef;
717
882k
}
718
719
841k
Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
720
841k
  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
721
841k
  if (Typedef)
722
841k
    Owner->addDecl(Typedef);
723
841k
  return Typedef;
724
841k
}
725
726
12.2k
Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
727
12.2k
  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
728
12.2k
  if (Typedef)
729
12.2k
    Owner->addDecl(Typedef);
730
12.2k
  return Typedef;
731
12.2k
}
732
733
Decl *
734
28.4k
TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
735
28.4k
  // Create a local instantiation scope for this type alias template, which
736
28.4k
  // will contain the instantiations of the template parameters.
737
28.4k
  LocalInstantiationScope Scope(SemaRef);
738
28.4k
739
28.4k
  TemplateParameterList *TempParams = D->getTemplateParameters();
740
28.4k
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
741
28.4k
  if (!InstParams)
742
0
    return nullptr;
743
28.4k
744
28.4k
  TypeAliasDecl *Pattern = D->getTemplatedDecl();
745
28.4k
746
28.4k
  TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
747
28.4k
  if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
748
0
    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
749
0
    if (!Found.empty()) {
750
0
      PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
751
0
    }
752
0
  }
753
28.4k
754
28.4k
  TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
755
28.4k
    InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
756
28.4k
  if (!AliasInst)
757
0
    return nullptr;
758
28.4k
759
28.4k
  TypeAliasTemplateDecl *Inst
760
28.4k
    = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
761
28.4k
                                    D->getDeclName(), InstParams, AliasInst);
762
28.4k
  AliasInst->setDescribedAliasTemplate(Inst);
763
28.4k
  if (PrevAliasTemplate)
764
0
    Inst->setPreviousDecl(PrevAliasTemplate);
765
28.4k
766
28.4k
  Inst->setAccess(D->getAccess());
767
28.4k
768
28.4k
  if (!PrevAliasTemplate)
769
28.4k
    Inst->setInstantiatedFromMemberTemplate(D);
770
28.4k
771
28.4k
  Owner->addDecl(Inst);
772
28.4k
773
28.4k
  return Inst;
774
28.4k
}
775
776
27
Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
777
27
  auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
778
27
                                    D->getIdentifier());
779
27
  NewBD->setReferenced(D->isReferenced());
780
27
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
781
27
  return NewBD;
782
27
}
783
784
17
Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
785
17
  // Transform the bindings first.
786
17
  SmallVector<BindingDecl*, 16> NewBindings;
787
17
  for (auto *OldBD : D->bindings())
788
27
    NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
789
17
  ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
790
17
791
17
  auto *NewDD = cast_or_null<DecompositionDecl>(
792
17
      VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
793
17
794
17
  if (!NewDD || NewDD->isInvalidDecl())
795
4
    for (auto *NewBD : NewBindings)
796
8
      NewBD->setInvalidDecl();
797
17
798
17
  return NewDD;
799
17
}
800
801
351k
Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
802
351k
  return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
803
351k
}
804
805
Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
806
                                             bool InstantiatingVarTemplate,
807
351k
                                             ArrayRef<BindingDecl*> *Bindings) {
808
351k
809
351k
  // Do substitution on the type of the declaration
810
351k
  TypeSourceInfo *DI = SemaRef.SubstType(
811
351k
      D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
812
351k
      D->getDeclName(), /*AllowDeducedTST*/true);
813
351k
  if (!DI)
814
78
    return nullptr;
815
351k
816
351k
  if (DI->getType()->isFunctionType()) {
817
6
    SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
818
6
      << D->isStaticDataMember() << DI->getType();
819
6
    return nullptr;
820
6
  }
821
351k
822
351k
  DeclContext *DC = Owner;
823
351k
  if (D->isLocalExternDecl())
824
78
    SemaRef.adjustContextForLocalExternDecl(DC);
825
351k
826
351k
  // Build the instantiated declaration.
827
351k
  VarDecl *Var;
828
351k
  if (Bindings)
829
17
    Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
830
17
                                    D->getLocation(), DI->getType(), DI,
831
17
                                    D->getStorageClass(), *Bindings);
832
351k
  else
833
351k
    Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
834
351k
                          D->getLocation(), D->getIdentifier(), DI->getType(),
835
351k
                          DI, D->getStorageClass());
836
351k
837
351k
  // In ARC, infer 'retaining' for variables of retainable type.
838
351k
  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
839
351k
      
SemaRef.inferObjCARCLifetime(Var)57
)
840
0
    Var->setInvalidDecl();
841
351k
842
351k
  // Substitute the nested name specifier, if any.
843
351k
  if (SubstQualifier(D, Var))
844
1
    return nullptr;
845
351k
846
351k
  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
847
351k
                                     StartingScope, InstantiatingVarTemplate);
848
351k
849
351k
  if (D->isNRVOVariable()) {
850
7.38k
    QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
851
7.38k
    if (SemaRef.isCopyElisionCandidate(ReturnType, Var, Sema::CES_Strict))
852
1.22k
      Var->setNRVOVariable(true);
853
7.38k
  }
854
351k
855
351k
  Var->setImplicit(D->isImplicit());
856
351k
857
351k
  if (Var->isStaticLocal())
858
517
    SemaRef.CheckStaticLocalForDllExport(Var);
859
351k
860
351k
  return Var;
861
351k
}
862
863
249k
Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
864
249k
  AccessSpecDecl* AD
865
249k
    = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
866
249k
                             D->getAccessSpecifierLoc(), D->getColonLoc());
867
249k
  Owner->addHiddenDecl(AD);
868
249k
  return AD;
869
249k
}
870
871
160k
Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
872
160k
  bool Invalid = false;
873
160k
  TypeSourceInfo *DI = D->getTypeSourceInfo();
874
160k
  if (DI->getType()->isInstantiationDependentType() ||
875
160k
      
DI->getType()->isVariablyModifiedType()57.4k
) {
876
102k
    DI = SemaRef.SubstType(DI, TemplateArgs,
877
102k
                           D->getLocation(), D->getDeclName());
878
102k
    if (!DI) {
879
49
      DI = D->getTypeSourceInfo();
880
49
      Invalid = true;
881
102k
    } else if (DI->getType()->isFunctionType()) {
882
15
      // C++ [temp.arg.type]p3:
883
15
      //   If a declaration acquires a function type through a type
884
15
      //   dependent on a template-parameter and this causes a
885
15
      //   declaration that does not use the syntactic form of a
886
15
      //   function declarator to have function type, the program is
887
15
      //   ill-formed.
888
15
      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
889
15
        << DI->getType();
890
15
      Invalid = true;
891
15
    }
892
102k
  } else {
893
57.4k
    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
894
57.4k
  }
895
160k
896
160k
  Expr *BitWidth = D->getBitWidth();
897
160k
  if (Invalid)
898
64
    BitWidth = nullptr;
899
160k
  else if (BitWidth) {
900
81
    // The bit-width expression is a constant expression.
901
81
    EnterExpressionEvaluationContext Unevaluated(
902
81
        SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
903
81
904
81
    ExprResult InstantiatedBitWidth
905
81
      = SemaRef.SubstExpr(BitWidth, TemplateArgs);
906
81
    if (InstantiatedBitWidth.isInvalid()) {
907
0
      Invalid = true;
908
0
      BitWidth = nullptr;
909
0
    } else
910
81
      BitWidth = InstantiatedBitWidth.getAs<Expr>();
911
81
  }
912
160k
913
160k
  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
914
160k
                                            DI->getType(), DI,
915
160k
                                            cast<RecordDecl>(Owner),
916
160k
                                            D->getLocation(),
917
160k
                                            D->isMutable(),
918
160k
                                            BitWidth,
919
160k
                                            D->getInClassInitStyle(),
920
160k
                                            D->getInnerLocStart(),
921
160k
                                            D->getAccess(),
922
160k
                                            nullptr);
923
160k
  if (!Field) {
924
0
    cast<Decl>(Owner)->setInvalidDecl();
925
0
    return nullptr;
926
0
  }
927
160k
928
160k
  SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
929
160k
930
160k
  if (Field->hasAttrs())
931
29
    SemaRef.CheckAlignasUnderalignment(Field);
932
160k
933
160k
  if (Invalid)
934
64
    Field->setInvalidDecl();
935
160k
936
160k
  if (!Field->getDeclName()) {
937
1.77k
    // Keep track of where this decl came from.
938
1.77k
    SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
939
1.77k
  }
940
160k
  if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
941
160k
    if (Parent->isAnonymousStructOrUnion() &&
942
160k
        
Parent->getRedeclContext()->isFunctionOrMethod()3.70k
)
943
0
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
944
160k
  }
945
160k
946
160k
  Field->setImplicit(D->isImplicit());
947
160k
  Field->setAccess(D->getAccess());
948
160k
  Owner->addDecl(Field);
949
160k
950
160k
  return Field;
951
160k
}
952
953
29
Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
954
29
  bool Invalid = false;
955
29
  TypeSourceInfo *DI = D->getTypeSourceInfo();
956
29
957
29
  if (DI->getType()->isVariablyModifiedType()) {
958
0
    SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
959
0
      << D;
960
0
    Invalid = true;
961
29
  } else if (DI->getType()->isInstantiationDependentType())  {
962
26
    DI = SemaRef.SubstType(DI, TemplateArgs,
963
26
                           D->getLocation(), D->getDeclName());
964
26
    if (!DI) {
965
0
      DI = D->getTypeSourceInfo();
966
0
      Invalid = true;
967
26
    } else if (DI->getType()->isFunctionType()) {
968
0
      // C++ [temp.arg.type]p3:
969
0
      //   If a declaration acquires a function type through a type
970
0
      //   dependent on a template-parameter and this causes a
971
0
      //   declaration that does not use the syntactic form of a
972
0
      //   function declarator to have function type, the program is
973
0
      //   ill-formed.
974
0
      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
975
0
      << DI->getType();
976
0
      Invalid = true;
977
0
    }
978
26
  } else {
979
3
    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
980
3
  }
981
29
982
29
  MSPropertyDecl *Property = MSPropertyDecl::Create(
983
29
      SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
984
29
      DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
985
29
986
29
  SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
987
29
                           StartingScope);
988
29
989
29
  if (Invalid)
990
0
    Property->setInvalidDecl();
991
29
992
29
  Property->setAccess(D->getAccess());
993
29
  Owner->addDecl(Property);
994
29
995
29
  return Property;
996
29
}
997
998
3.70k
Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
999
3.70k
  NamedDecl **NamedChain =
1000
3.70k
    new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1001
3.70k
1002
3.70k
  int i = 0;
1003
7.42k
  for (auto *PI : D->chain()) {
1004
7.42k
    NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1005
7.42k
                                              TemplateArgs);
1006
7.42k
    if (!Next)
1007
0
      return nullptr;
1008
7.42k
1009
7.42k
    NamedChain[i++] = Next;
1010
7.42k
  }
1011
3.70k
1012
3.70k
  QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1013
3.70k
  IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1014
3.70k
      SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1015
3.70k
      {NamedChain, D->getChainingSize()});
1016
3.70k
1017
3.70k
  for (const auto *Attr : D->attrs())
1018
0
    IndirectField->addAttr(Attr->clone(SemaRef.Context));
1019
3.70k
1020
3.70k
  IndirectField->setImplicit(D->isImplicit());
1021
3.70k
  IndirectField->setAccess(D->getAccess());
1022
3.70k
  Owner->addDecl(IndirectField);
1023
3.70k
  return IndirectField;
1024
3.70k
}
1025
1026
44.3k
Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1027
44.3k
  // Handle friend type expressions by simply substituting template
1028
44.3k
  // parameters into the pattern type and checking the result.
1029
44.3k
  if (TypeSourceInfo *Ty = D->getFriendType()) {
1030
6.98k
    TypeSourceInfo *InstTy;
1031
6.98k
    // If this is an unsupported friend, don't bother substituting template
1032
6.98k
    // arguments into it. The actual type referred to won't be used by any
1033
6.98k
    // parts of Clang, and may not be valid for instantiating. Just use the
1034
6.98k
    // same info for the instantiated friend.
1035
6.98k
    if (D->isUnsupportedFriend()) {
1036
3
      InstTy = Ty;
1037
6.98k
    } else {
1038
6.98k
      InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1039
6.98k
                                 D->getLocation(), DeclarationName());
1040
6.98k
    }
1041
6.98k
    if (!InstTy)
1042
1
      return nullptr;
1043
6.98k
1044
6.98k
    FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
1045
6.98k
                                                 D->getFriendLoc(), InstTy);
1046
6.98k
    if (!FD)
1047
0
      return nullptr;
1048
6.98k
1049
6.98k
    FD->setAccess(AS_public);
1050
6.98k
    FD->setUnsupportedFriend(D->isUnsupportedFriend());
1051
6.98k
    Owner->addDecl(FD);
1052
6.98k
    return FD;
1053
6.98k
  }
1054
37.3k
1055
37.3k
  NamedDecl *ND = D->getFriendDecl();
1056
37.3k
  assert(ND && "friend decl must be a decl or a type!");
1057
37.3k
1058
37.3k
  // All of the Visit implementations for the various potential friend
1059
37.3k
  // declarations have to be carefully written to work for friend
1060
37.3k
  // objects, with the most important detail being that the target
1061
37.3k
  // decl should almost certainly not be placed in Owner.
1062
37.3k
  Decl *NewND = Visit(ND);
1063
37.3k
  if (!NewND) 
return nullptr5
;
1064
37.3k
1065
37.3k
  FriendDecl *FD =
1066
37.3k
    FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1067
37.3k
                       cast<NamedDecl>(NewND), D->getFriendLoc());
1068
37.3k
  FD->setAccess(AS_public);
1069
37.3k
  FD->setUnsupportedFriend(D->isUnsupportedFriend());
1070
37.3k
  Owner->addDecl(FD);
1071
37.3k
  return FD;
1072
37.3k
}
1073
1074
35.6k
Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1075
35.6k
  Expr *AssertExpr = D->getAssertExpr();
1076
35.6k
1077
35.6k
  // The expression in a static assertion is a constant expression.
1078
35.6k
  EnterExpressionEvaluationContext Unevaluated(
1079
35.6k
      SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1080
35.6k
1081
35.6k
  ExprResult InstantiatedAssertExpr
1082
35.6k
    = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1083
35.6k
  if (InstantiatedAssertExpr.isInvalid())
1084
3
    return nullptr;
1085
35.6k
1086
35.6k
  return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
1087
35.6k
                                              InstantiatedAssertExpr.get(),
1088
35.6k
                                              D->getMessage(),
1089
35.6k
                                              D->getRParenLoc(),
1090
35.6k
                                              D->isFailed());
1091
35.6k
}
1092
1093
5.34k
Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1094
5.34k
  EnumDecl *PrevDecl = nullptr;
1095
5.34k
  if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1096
16
    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1097
16
                                                   PatternPrev,
1098
16
                                                   TemplateArgs);
1099
16
    if (!Prev) 
return nullptr0
;
1100
16
    PrevDecl = cast<EnumDecl>(Prev);
1101
16
  }
1102
5.34k
1103
5.34k
  EnumDecl *Enum =
1104
5.34k
      EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1105
5.34k
                       D->getLocation(), D->getIdentifier(), PrevDecl,
1106
5.34k
                       D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1107
5.34k
  if (D->isFixed()) {
1108
209
    if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1109
147
      // If we have type source information for the underlying type, it means it
1110
147
      // has been explicitly set by the user. Perform substitution on it before
1111
147
      // moving on.
1112
147
      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1113
147
      TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1114
147
                                                DeclarationName());
1115
147
      if (!NewTI || 
SemaRef.CheckEnumUnderlyingType(NewTI)146
)
1116
3
        Enum->setIntegerType(SemaRef.Context.IntTy);
1117
144
      else
1118
144
        Enum->setIntegerTypeSourceInfo(NewTI);
1119
147
    } else {
1120
62
      assert(!D->getIntegerType()->isDependentType()
1121
62
             && "Dependent type without type source info");
1122
62
      Enum->setIntegerType(D->getIntegerType());
1123
62
    }
1124
209
  }
1125
5.34k
1126
5.34k
  SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1127
5.34k
1128
5.34k
  Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1129
5.34k
  Enum->setAccess(D->getAccess());
1130
5.34k
  // Forward the mangling number from the template to the instantiated decl.
1131
5.34k
  SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
1132
5.34k
  // See if the old tag was defined along with a declarator.
1133
5.34k
  // If it did, mark the new tag as being associated with that declarator.
1134
5.34k
  if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1135
3
    SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1136
5.34k
  // See if the old tag was defined along with a typedef.
1137
5.34k
  // If it did, mark the new tag as being associated with that typedef.
1138
5.34k
  if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1139
0
    SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
1140
5.34k
  if (SubstQualifier(D, Enum)) 
return nullptr0
;
1141
5.34k
  Owner->addDecl(Enum);
1142
5.34k
1143
5.34k
  EnumDecl *Def = D->getDefinition();
1144
5.34k
  if (Def && 
Def != D5.28k
) {
1145
35
    // If this is an out-of-line definition of an enum member template, check
1146
35
    // that the underlying types match in the instantiation of both
1147
35
    // declarations.
1148
35
    if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1149
21
      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1150
21
      QualType DefnUnderlying =
1151
21
        SemaRef.SubstType(TI->getType(), TemplateArgs,
1152
21
                          UnderlyingLoc, DeclarationName());
1153
21
      SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1154
21
                                     DefnUnderlying, /*IsFixed=*/true, Enum);
1155
21
    }
1156
35
  }
1157
5.34k
1158
5.34k
  // C++11 [temp.inst]p1: The implicit instantiation of a class template
1159
5.34k
  // specialization causes the implicit instantiation of the declarations, but
1160
5.34k
  // not the definitions of scoped member enumerations.
1161
5.34k
  //
1162
5.34k
  // DR1484 clarifies that enumeration definitions inside of a template
1163
5.34k
  // declaration aren't considered entities that can be separately instantiated
1164
5.34k
  // from the rest of the entity they are declared inside of.
1165
5.34k
  if (isDeclWithinFunction(D) ? 
D == Def76
:
Def5.26k
&&
!Enum->isScoped()5.21k
) {
1166
5.23k
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
1167
5.23k
    InstantiateEnumDefinition(Enum, Def);
1168
5.23k
  }
1169
5.34k
1170
5.34k
  return Enum;
1171
5.34k
}
1172
1173
void TemplateDeclInstantiator::InstantiateEnumDefinition(
1174
5.25k
    EnumDecl *Enum, EnumDecl *Pattern) {
1175
5.25k
  Enum->startDefinition();
1176
5.25k
1177
5.25k
  // Update the location to refer to the definition.
1178
5.25k
  Enum->setLocation(Pattern->getLocation());
1179
5.25k
1180
5.25k
  SmallVector<Decl*, 4> Enumerators;
1181
5.25k
1182
5.25k
  EnumConstantDecl *LastEnumConst = nullptr;
1183
5.45k
  for (auto *EC : Pattern->enumerators()) {
1184
5.45k
    // The specified value for the enumerator.
1185
5.45k
    ExprResult Value((Expr *)nullptr);
1186
5.45k
    if (Expr *UninstValue = EC->getInitExpr()) {
1187
5.22k
      // The enumerator's value expression is a constant expression.
1188
5.22k
      EnterExpressionEvaluationContext Unevaluated(
1189
5.22k
          SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1190
5.22k
1191
5.22k
      Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1192
5.22k
    }
1193
5.45k
1194
5.45k
    // Drop the initial value and continue.
1195
5.45k
    bool isInvalid = false;
1196
5.45k
    if (Value.isInvalid()) {
1197
19
      Value = nullptr;
1198
19
      isInvalid = true;
1199
19
    }
1200
5.45k
1201
5.45k
    EnumConstantDecl *EnumConst
1202
5.45k
      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1203
5.45k
                                  EC->getLocation(), EC->getIdentifier(),
1204
5.45k
                                  Value.get());
1205
5.45k
1206
5.45k
    if (isInvalid) {
1207
19
      if (EnumConst)
1208
19
        EnumConst->setInvalidDecl();
1209
19
      Enum->setInvalidDecl();
1210
19
    }
1211
5.45k
1212
5.45k
    if (EnumConst) {
1213
5.45k
      SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1214
5.45k
1215
5.45k
      EnumConst->setAccess(Enum->getAccess());
1216
5.45k
      Enum->addDecl(EnumConst);
1217
5.45k
      Enumerators.push_back(EnumConst);
1218
5.45k
      LastEnumConst = EnumConst;
1219
5.45k
1220
5.45k
      if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1221
5.45k
          
!Enum->isScoped()73
) {
1222
57
        // If the enumeration is within a function or method, record the enum
1223
57
        // constant as a local.
1224
57
        SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1225
57
      }
1226
5.45k
    }
1227
5.45k
  }
1228
5.25k
1229
5.25k
  SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1230
5.25k
                        Enumerators, nullptr, ParsedAttributesView());
1231
5.25k
}
1232
1233
0
Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1234
0
  llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1235
0
}
1236
1237
Decl *
1238
0
TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1239
0
  llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1240
0
}
1241
1242
23.1k
Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1243
23.1k
  bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1244
23.1k
1245
23.1k
  // Create a local instantiation scope for this class template, which
1246
23.1k
  // will contain the instantiations of the template parameters.
1247
23.1k
  LocalInstantiationScope Scope(SemaRef);
1248
23.1k
  TemplateParameterList *TempParams = D->getTemplateParameters();
1249
23.1k
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1250
23.1k
  if (!InstParams)
1251
5
    return nullptr;
1252
23.1k
1253
23.1k
  CXXRecordDecl *Pattern = D->getTemplatedDecl();
1254
23.1k
1255
23.1k
  // Instantiate the qualifier.  We have to do this first in case
1256
23.1k
  // we're a friend declaration, because if we are then we need to put
1257
23.1k
  // the new declaration in the appropriate context.
1258
23.1k
  NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1259
23.1k
  if (QualifierLoc) {
1260
7
    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1261
7
                                                       TemplateArgs);
1262
7
    if (!QualifierLoc)
1263
0
      return nullptr;
1264
23.1k
  }
1265
23.1k
1266
23.1k
  CXXRecordDecl *PrevDecl = nullptr;
1267
23.1k
  ClassTemplateDecl *PrevClassTemplate = nullptr;
1268
23.1k
1269
23.1k
  if (!isFriend && 
getPreviousDeclForInstantiation(Pattern)15.1k
) {
1270
2
    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1271
2
    if (!Found.empty()) {
1272
2
      PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1273
2
      if (PrevClassTemplate)
1274
2
        PrevDecl = PrevClassTemplate->getTemplatedDecl();
1275
2
    }
1276
2
  }
1277
23.1k
1278
23.1k
  // If this isn't a friend, then it's a member template, in which
1279
23.1k
  // case we just want to build the instantiation in the
1280
23.1k
  // specialization.  If it is a friend, we want to build it in
1281
23.1k
  // the appropriate context.
1282
23.1k
  DeclContext *DC = Owner;
1283
23.1k
  if (isFriend) {
1284
7.96k
    if (QualifierLoc) {
1285
7
      CXXScopeSpec SS;
1286
7
      SS.Adopt(QualifierLoc);
1287
7
      DC = SemaRef.computeDeclContext(SS);
1288
7
      if (!DC) 
return nullptr0
;
1289
7.95k
    } else {
1290
7.95k
      DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1291
7.95k
                                           Pattern->getDeclContext(),
1292
7.95k
                                           TemplateArgs);
1293
7.95k
    }
1294
7.96k
1295
7.96k
    // Look for a previous declaration of the template in the owning
1296
7.96k
    // context.
1297
7.96k
    LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1298
7.96k
                   Sema::LookupOrdinaryName,
1299
7.96k
                   SemaRef.forRedeclarationInCurContext());
1300
7.96k
    SemaRef.LookupQualifiedName(R, DC);
1301
7.96k
1302
7.96k
    if (R.isSingleResult()) {
1303
7.68k
      PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1304
7.68k
      if (PrevClassTemplate)
1305
7.68k
        PrevDecl = PrevClassTemplate->getTemplatedDecl();
1306
7.68k
    }
1307
7.96k
1308
7.96k
    if (!PrevClassTemplate && 
QualifierLoc276
) {
1309
0
      SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1310
0
        << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
1311
0
        << QualifierLoc.getSourceRange();
1312
0
      return nullptr;
1313
0
    }
1314
7.96k
1315
7.96k
    bool AdoptedPreviousTemplateParams = false;
1316
7.96k
    if (PrevClassTemplate) {
1317
7.68k
      bool Complain = true;
1318
7.68k
1319
7.68k
      // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
1320
7.68k
      // template for struct std::tr1::__detail::_Map_base, where the
1321
7.68k
      // template parameters of the friend declaration don't match the
1322
7.68k
      // template parameters of the original declaration. In this one
1323
7.68k
      // case, we don't complain about the ill-formed friend
1324
7.68k
      // declaration.
1325
7.68k
      if (isFriend && Pattern->getIdentifier() &&
1326
7.68k
          Pattern->getIdentifier()->isStr("_Map_base") &&
1327
7.68k
          
DC->isNamespace()1
&&
1328
7.68k
          
cast<NamespaceDecl>(DC)->getIdentifier()1
&&
1329
7.68k
          
cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")1
) {
1330
1
        DeclContext *DCParent = DC->getParent();
1331
1
        if (DCParent->isNamespace() &&
1332
1
            cast<NamespaceDecl>(DCParent)->getIdentifier() &&
1333
1
            cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
1334
1
          if (cast<Decl>(DCParent)->isInStdNamespace())
1335
1
            Complain = false;
1336
1
        }
1337
1
      }
1338
7.68k
1339
7.68k
      TemplateParameterList *PrevParams
1340
7.68k
        = PrevClassTemplate->getMostRecentDecl()->getTemplateParameters();
1341
7.68k
1342
7.68k
      // Make sure the parameter lists match.
1343
7.68k
      if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
1344
7.68k
                                                  Complain,
1345
7.68k
                                                  Sema::TPL_TemplateMatch)) {
1346
3
        if (Complain)
1347
2
          return nullptr;
1348
1
1349
1
        AdoptedPreviousTemplateParams = true;
1350
1
        InstParams = PrevParams;
1351
1
      }
1352
7.68k
1353
7.68k
      // Do some additional validation, then merge default arguments
1354
7.68k
      // from the existing declarations.
1355
7.68k
      
if (7.68k
!AdoptedPreviousTemplateParams7.68k
&&
1356
7.68k
          SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1357
7.68k
                                             Sema::TPC_ClassTemplate))
1358
0
        return nullptr;
1359
23.1k
    }
1360
7.96k
  }
1361
23.1k
1362
23.1k
  CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1363
23.1k
      SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1364
23.1k
      Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1365
23.1k
      /*DelayTypeCreation=*/true);
1366
23.1k
1367
23.1k
  if (QualifierLoc)
1368
6
    RecordInst->setQualifierInfo(QualifierLoc);
1369
23.1k
1370
23.1k
  SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1371
23.1k
                                                              StartingScope);
1372
23.1k
1373
23.1k
  ClassTemplateDecl *Inst
1374
23.1k
    = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1375
23.1k
                                D->getIdentifier(), InstParams, RecordInst);
1376
23.1k
  assert(!(isFriend && Owner->isDependentContext()));
1377
23.1k
  Inst->setPreviousDecl(PrevClassTemplate);
1378
23.1k
1379
23.1k
  RecordInst->setDescribedClassTemplate(Inst);
1380
23.1k
1381
23.1k
  if (isFriend) {
1382
7.96k
    if (PrevClassTemplate)
1383
7.68k
      Inst->setAccess(PrevClassTemplate->getAccess());
1384
276
    else
1385
276
      Inst->setAccess(D->getAccess());
1386
7.96k
1387
7.96k
    Inst->setObjectOfFriendDecl();
1388
7.96k
    // TODO: do we want to track the instantiation progeny of this
1389
7.96k
    // friend target decl?
1390
15.1k
  } else {
1391
15.1k
    Inst->setAccess(D->getAccess());
1392
15.1k
    if (!PrevClassTemplate)
1393
15.1k
      Inst->setInstantiatedFromMemberTemplate(D);
1394
15.1k
  }
1395
23.1k
1396
23.1k
  // Trigger creation of the type for the instantiation.
1397
23.1k
  SemaRef.Context.getInjectedClassNameType(RecordInst,
1398
23.1k
                                    Inst->getInjectedClassNameSpecialization());
1399
23.1k
1400
23.1k
  // Finish handling of friends.
1401
23.1k
  if (isFriend) {
1402
7.96k
    DC->makeDeclVisibleInContext(Inst);
1403
7.96k
    Inst->setLexicalDeclContext(Owner);
1404
7.96k
    RecordInst->setLexicalDeclContext(Owner);
1405
7.96k
    return Inst;
1406
7.96k
  }
1407
15.1k
1408
15.1k
  if (D->isOutOfLine()) {
1409
0
    Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1410
0
    RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1411
0
  }
1412
15.1k
1413
15.1k
  Owner->addDecl(Inst);
1414
15.1k
1415
15.1k
  if (!PrevClassTemplate) {
1416
15.1k
    // Queue up any out-of-line partial specializations of this member
1417
15.1k
    // class template; the client will force their instantiation once
1418
15.1k
    // the enclosing class has been instantiated.
1419
15.1k
    SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1420
15.1k
    D->getPartialSpecializations(PartialSpecs);
1421
19.3k
    for (unsigned I = 0, N = PartialSpecs.size(); I != N; 
++I4.20k
)
1422
4.20k
      if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1423
9
        OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1424
15.1k
  }
1425
15.1k
1426
15.1k
  return Inst;
1427
15.1k
}
1428
1429
Decl *
1430
TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1431
4.20k
                                   ClassTemplatePartialSpecializationDecl *D) {
1432
4.20k
  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1433
4.20k
1434
4.20k
  // Lookup the already-instantiated declaration in the instantiation
1435
4.20k
  // of the class template and return that.
1436
4.20k
  DeclContext::lookup_result Found
1437
4.20k
    = Owner->lookup(ClassTemplate->getDeclName());
1438
4.20k
  if (Found.empty())
1439
0
    return nullptr;
1440
4.20k
1441
4.20k
  ClassTemplateDecl *InstClassTemplate
1442
4.20k
    = dyn_cast<ClassTemplateDecl>(Found.front());
1443
4.20k
  if (!InstClassTemplate)
1444
0
    return nullptr;
1445
4.20k
1446
4.20k
  if (ClassTemplatePartialSpecializationDecl *Result
1447
0
        = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1448
0
    return Result;
1449
4.20k
1450
4.20k
  return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1451
4.20k
}
1452
1453
183
Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1454
183
  assert(D->getTemplatedDecl()->isStaticDataMember() &&
1455
183
         "Only static data member templates are allowed.");
1456
183
1457
183
  // Create a local instantiation scope for this variable template, which
1458
183
  // will contain the instantiations of the template parameters.
1459
183
  LocalInstantiationScope Scope(SemaRef);
1460
183
  TemplateParameterList *TempParams = D->getTemplateParameters();
1461
183
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1462
183
  if (!InstParams)
1463
0
    return nullptr;
1464
183
1465
183
  VarDecl *Pattern = D->getTemplatedDecl();
1466
183
  VarTemplateDecl *PrevVarTemplate = nullptr;
1467
183
1468
183
  if (getPreviousDeclForInstantiation(Pattern)) {
1469
0
    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1470
0
    if (!Found.empty())
1471
0
      PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1472
0
  }
1473
183
1474
183
  VarDecl *VarInst =
1475
183
      cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1476
183
                                         /*InstantiatingVarTemplate=*/true));
1477
183
  if (!VarInst) 
return nullptr3
;
1478
180
1479
180
  DeclContext *DC = Owner;
1480
180
1481
180
  VarTemplateDecl *Inst = VarTemplateDecl::Create(
1482
180
      SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1483
180
      VarInst);
1484
180
  VarInst->setDescribedVarTemplate(Inst);
1485
180
  Inst->setPreviousDecl(PrevVarTemplate);
1486
180
1487
180
  Inst->setAccess(D->getAccess());
1488
180
  if (!PrevVarTemplate)
1489
180
    Inst->setInstantiatedFromMemberTemplate(D);
1490
180
1491
180
  if (D->isOutOfLine()) {
1492
0
    Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1493
0
    VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1494
0
  }
1495
180
1496
180
  Owner->addDecl(Inst);
1497
180
1498
180
  if (!PrevVarTemplate) {
1499
180
    // Queue up any out-of-line partial specializations of this member
1500
180
    // variable template; the client will force their instantiation once
1501
180
    // the enclosing class has been instantiated.
1502
180
    SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1503
180
    D->getPartialSpecializations(PartialSpecs);
1504
226
    for (unsigned I = 0, N = PartialSpecs.size(); I != N; 
++I46
)
1505
46
      if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1506
7
        OutOfLineVarPartialSpecs.push_back(
1507
7
            std::make_pair(Inst, PartialSpecs[I]));
1508
180
  }
1509
180
1510
180
  return Inst;
1511
180
}
1512
1513
Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1514
41
    VarTemplatePartialSpecializationDecl *D) {
1515
41
  assert(D->isStaticDataMember() &&
1516
41
         "Only static data member templates are allowed.");
1517
41
1518
41
  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1519
41
1520
41
  // Lookup the already-instantiated declaration and return that.
1521
41
  DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1522
41
  assert(!Found.empty() && "Instantiation found nothing?");
1523
41
1524
41
  VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1525
41
  assert(InstVarTemplate && "Instantiation did not find a variable template?");
1526
41
1527
41
  if (VarTemplatePartialSpecializationDecl *Result =
1528
0
          InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1529
0
    return Result;
1530
41
1531
41
  return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1532
41
}
1533
1534
Decl *
1535
263k
TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1536
263k
  // Create a local instantiation scope for this function template, which
1537
263k
  // will contain the instantiations of the template parameters and then get
1538
263k
  // merged with the local instantiation scope for the function template
1539
263k
  // itself.
1540
263k
  LocalInstantiationScope Scope(SemaRef);
1541
263k
1542
263k
  TemplateParameterList *TempParams = D->getTemplateParameters();
1543
263k
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1544
263k
  if (!InstParams)
1545
0
    return nullptr;
1546
263k
1547
263k
  FunctionDecl *Instantiated = nullptr;
1548
263k
  if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1549
245k
    Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1550
245k
                                                                 InstParams));
1551
17.7k
  else
1552
17.7k
    Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1553
17.7k
                                                          D->getTemplatedDecl(),
1554
17.7k
                                                                InstParams));
1555
263k
1556
263k
  if (!Instantiated)
1557
4
    return nullptr;
1558
263k
1559
263k
  // Link the instantiated function template declaration to the function
1560
263k
  // template from which it was instantiated.
1561
263k
  FunctionTemplateDecl *InstTemplate
1562
263k
    = Instantiated->getDescribedFunctionTemplate();
1563
263k
  InstTemplate->setAccess(D->getAccess());
1564
263k
  assert(InstTemplate &&
1565
263k
         "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1566
263k
1567
263k
  bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1568
263k
1569
263k
  // Link the instantiation back to the pattern *unless* this is a
1570
263k
  // non-definition friend declaration.
1571
263k
  if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1572
263k
      
!(263k
isFriend263k
&&
!D->getTemplatedDecl()->isThisDeclarationADefinition()17.6k
))
1573
245k
    InstTemplate->setInstantiatedFromMemberTemplate(D);
1574
263k
1575
263k
  // Make declarations visible in the appropriate context.
1576
263k
  if (!isFriend) {
1577
245k
    Owner->addDecl(InstTemplate);
1578
245k
  } else 
if (17.7k
InstTemplate->getDeclContext()->isRecord()17.7k
&&
1579
17.7k
             
!getPreviousDeclForInstantiation(D)6
) {
1580
6
    SemaRef.CheckFriendAccess(InstTemplate);
1581
6
  }
1582
263k
1583
263k
  return InstTemplate;
1584
263k
}
1585
1586
1.13M
Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1587
1.13M
  CXXRecordDecl *PrevDecl = nullptr;
1588
1.13M
  if (D->isInjectedClassName())
1589
1.10M
    PrevDecl = cast<CXXRecordDecl>(Owner);
1590
30.4k
  else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1591
28
    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1592
28
                                                   PatternPrev,
1593
28
                                                   TemplateArgs);
1594
28
    if (!Prev) 
return nullptr0
;
1595
28
    PrevDecl = cast<CXXRecordDecl>(Prev);
1596
28
  }
1597
1.13M
1598
1.13M
  CXXRecordDecl *Record = CXXRecordDecl::Create(
1599
1.13M
      SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
1600
1.13M
      D->getLocation(), D->getIdentifier(), PrevDecl);
1601
1.13M
1602
1.13M
  // Substitute the nested name specifier, if any.
1603
1.13M
  if (SubstQualifier(D, Record))
1604
0
    return nullptr;
1605
1.13M
1606
1.13M
  SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
1607
1.13M
                                                              StartingScope);
1608
1.13M
1609
1.13M
  Record->setImplicit(D->isImplicit());
1610
1.13M
  // FIXME: Check against AS_none is an ugly hack to work around the issue that
1611
1.13M
  // the tag decls introduced by friend class declarations don't have an access
1612
1.13M
  // specifier. Remove once this area of the code gets sorted out.
1613
1.13M
  if (D->getAccess() != AS_none)
1614
1.13M
    Record->setAccess(D->getAccess());
1615
1.13M
  if (!D->isInjectedClassName())
1616
30.4k
    Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1617
1.13M
1618
1.13M
  // If the original function was part of a friend declaration,
1619
1.13M
  // inherit its namespace state.
1620
1.13M
  if (D->getFriendObjectKind())
1621
0
    Record->setObjectOfFriendDecl();
1622
1.13M
1623
1.13M
  // Make sure that anonymous structs and unions are recorded.
1624
1.13M
  if (D->isAnonymousStructOrUnion())
1625
1.78k
    Record->setAnonymousStructOrUnion(true);
1626
1.13M
1627
1.13M
  if (D->isLocalClass())
1628
1.92k
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1629
1.13M
1630
1.13M
  // Forward the mangling number from the template to the instantiated decl.
1631
1.13M
  SemaRef.Context.setManglingNumber(Record,
1632
1.13M
                                    SemaRef.Context.getManglingNumber(D));
1633
1.13M
1634
1.13M
  // See if the old tag was defined along with a declarator.
1635
1.13M
  // If it did, mark the new tag as being associated with that declarator.
1636
1.13M
  if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1637
3
    SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1638
1.13M
1639
1.13M
  // See if the old tag was defined along with a typedef.
1640
1.13M
  // If it did, mark the new tag as being associated with that typedef.
1641
1.13M
  if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1642
0
    SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1643
1.13M
1644
1.13M
  Owner->addDecl(Record);
1645
1.13M
1646
1.13M
  // DR1484 clarifies that the members of a local class are instantiated as part
1647
1.13M
  // of the instantiation of their enclosing entity.
1648
1.13M
  if (D->isCompleteDefinition() && 
D->isLocalClass()29.5k
) {
1649
1.68k
    Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
1650
1.68k
1651
1.68k
    SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1652
1.68k
                             TSK_ImplicitInstantiation,
1653
1.68k
                             /*Complain=*/true);
1654
1.68k
1655
1.68k
    // For nested local classes, we will instantiate the members when we
1656
1.68k
    // reach the end of the outermost (non-nested) local class.
1657
1.68k
    if (!D->isCXXClassMember())
1658
1.38k
      SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1659
1.38k
                                      TSK_ImplicitInstantiation);
1660
1.68k
1661
1.68k
    // This class may have local implicit instantiations that need to be
1662
1.68k
    // performed within this scope.
1663
1.68k
    LocalInstantiations.perform();
1664
1.68k
  }
1665
1.13M
1666
1.13M
  SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1667
1.13M
1668
1.13M
  return Record;
1669
1.13M
}
1670
1671
/// Adjust the given function type for an instantiation of the
1672
/// given declaration, to cope with modifications to the function's type that
1673
/// aren't reflected in the type-source information.
1674
///
1675
/// \param D The declaration we're instantiating.
1676
/// \param TInfo The already-instantiated type.
1677
static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1678
                                                   FunctionDecl *D,
1679
1.85M
                                                   TypeSourceInfo *TInfo) {
1680
1.85M
  const FunctionProtoType *OrigFunc
1681
1.85M
    = D->getType()->castAs<FunctionProtoType>();
1682
1.85M
  const FunctionProtoType *NewFunc
1683
1.85M
    = TInfo->getType()->castAs<FunctionProtoType>();
1684
1.85M
  if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1685
1.85M
    return TInfo->getType();
1686
1
1687
1
  FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1688
1
  NewEPI.ExtInfo = OrigFunc->getExtInfo();
1689
1
  return Context.getFunctionType(NewFunc->getReturnType(),
1690
1
                                 NewFunc->getParamTypes(), NewEPI);
1691
1
}
1692
1693
/// Normal class members are of more specific types and therefore
1694
/// don't make it here.  This function serves three purposes:
1695
///   1) instantiating function templates
1696
///   2) substituting friend declarations
1697
///   3) substituting deduction guide declarations for nested class templates
1698
Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1699
444k
                                       TemplateParameterList *TemplateParams) {
1700
444k
  // Check whether there is already a function template specialization for
1701
444k
  // this declaration.
1702
444k
  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1703
444k
  if (FunctionTemplate && 
!TemplateParams432k
) {
1704
414k
    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1705
414k
1706
414k
    void *InsertPos = nullptr;
1707
414k
    FunctionDecl *SpecFunc
1708
414k
      = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1709
414k
1710
414k
    // If we already have a function template specialization, return it.
1711
414k
    if (SpecFunc)
1712
208k
      return SpecFunc;
1713
235k
  }
1714
235k
1715
235k
  bool isFriend;
1716
235k
  if (FunctionTemplate)
1717
223k
    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1718
11.7k
  else
1719
11.7k
    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1720
235k
1721
235k
  bool MergeWithParentScope = (TemplateParams != nullptr) ||
1722
235k
    
Owner->isFunctionOrMethod()217k
||
1723
235k
    
!(217k
isa<Decl>(Owner)217k
&&
1724
217k
      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1725
235k
  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1726
235k
1727
235k
  ExplicitSpecifier InstantiatedExplicitSpecifier;
1728
235k
  if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
1729
146
    InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
1730
146
        SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
1731
146
    if (InstantiatedExplicitSpecifier.isInvalid())
1732
5
      return nullptr;
1733
235k
  }
1734
235k
1735
235k
  SmallVector<ParmVarDecl *, 4> Params;
1736
235k
  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1737
235k
  if (!TInfo)
1738
40.0k
    return nullptr;
1739
195k
  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1740
195k
1741
195k
  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1742
195k
  if (QualifierLoc) {
1743
13
    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1744
13
                                                       TemplateArgs);
1745
13
    if (!QualifierLoc)
1746
0
      return nullptr;
1747
195k
  }
1748
195k
1749
195k
  // If we're instantiating a local function declaration, put the result
1750
195k
  // in the enclosing namespace; otherwise we need to find the instantiated
1751
195k
  // context.
1752
195k
  DeclContext *DC;
1753
195k
  if (D->isLocalExternDecl()) {
1754
74
    DC = Owner;
1755
74
    SemaRef.adjustContextForLocalExternDecl(DC);
1756
195k
  } else if (isFriend && 
QualifierLoc29.5k
) {
1757
13
    CXXScopeSpec SS;
1758
13
    SS.Adopt(QualifierLoc);
1759
13
    DC = SemaRef.computeDeclContext(SS);
1760
13
    if (!DC) 
return nullptr0
;
1761
195k
  } else {
1762
195k
    DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1763
195k
                                         TemplateArgs);
1764
195k
  }
1765
195k
1766
195k
  DeclarationNameInfo NameInfo
1767
195k
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1768
195k
1769
195k
  FunctionDecl *Function;
1770
195k
  if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
1771
138
    Function = CXXDeductionGuideDecl::Create(
1772
138
        SemaRef.Context, DC, D->getInnerLocStart(),
1773
138
        InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
1774
138
        D->getSourceRange().getEnd());
1775
138
    if (DGuide->isCopyDeductionCandidate())
1776
9
      cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
1777
138
    Function->setAccess(D->getAccess());
1778
195k
  } else {
1779
195k
    Function = FunctionDecl::Create(
1780
195k
        SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
1781
195k
        D->getCanonicalDecl()->getStorageClass(), D->isInlineSpecified(),
1782
195k
        D->hasWrittenPrototype(), D->getConstexprKind());
1783
195k
    Function->setRangeEnd(D->getSourceRange().getEnd());
1784
195k
  }
1785
195k
1786
195k
  if (D->isInlined())
1787
64.9k
    Function->setImplicitlyInline();
1788
195k
1789
195k
  if (QualifierLoc)
1790
13
    Function->setQualifierInfo(QualifierLoc);
1791
195k
1792
195k
  if (D->isLocalExternDecl())
1793
74
    Function->setLocalExternDecl();
1794
195k
1795
195k
  DeclContext *LexicalDC = Owner;
1796
195k
  if (!isFriend && 
D->isOutOfLine()165k
&&
!D->isLocalExternDecl()0
) {
1797
0
    assert(D->getDeclContext()->isFileContext());
1798
0
    LexicalDC = D->getDeclContext();
1799
0
  }
1800
195k
1801
195k
  Function->setLexicalDeclContext(LexicalDC);
1802
195k
1803
195k
  // Attach the parameters
1804
501k
  for (unsigned P = 0; P < Params.size(); 
++P305k
)
1805
305k
    if (Params[P])
1806
305k
      Params[P]->setOwningFunction(Function);
1807
195k
  Function->setParams(Params);
1808
195k
1809
195k
  if (TemplateParams) {
1810
17.7k
    // Our resulting instantiation is actually a function template, since we
1811
17.7k
    // are substituting only the outer template parameters. For example, given
1812
17.7k
    //
1813
17.7k
    //   template<typename T>
1814
17.7k
    //   struct X {
1815
17.7k
    //     template<typename U> friend void f(T, U);
1816
17.7k
    //   };
1817
17.7k
    //
1818
17.7k
    //   X<int> x;
1819
17.7k
    //
1820
17.7k
    // We are instantiating the friend function template "f" within X<int>,
1821
17.7k
    // which means substituting int for T, but leaving "f" as a friend function
1822
17.7k
    // template.
1823
17.7k
    // Build the function template itself.
1824
17.7k
    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1825
17.7k
                                                    Function->getLocation(),
1826
17.7k
                                                    Function->getDeclName(),
1827
17.7k
                                                    TemplateParams, Function);
1828
17.7k
    Function->setDescribedFunctionTemplate(FunctionTemplate);
1829
17.7k
1830
17.7k
    FunctionTemplate->setLexicalDeclContext(LexicalDC);
1831
17.7k
1832
17.7k
    if (isFriend && 
D->isThisDeclarationADefinition()17.7k
) {
1833
121
      FunctionTemplate->setInstantiatedFromMemberTemplate(
1834
121
                                           D->getDescribedFunctionTemplate());
1835
121
    }
1836
177k
  } else if (FunctionTemplate) {
1837
166k
    // Record this function template specialization.
1838
166k
    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1839
166k
    Function->setFunctionTemplateSpecialization(FunctionTemplate,
1840
166k
                            TemplateArgumentList::CreateCopy(SemaRef.Context,
1841
166k
                                                             Innermost),
1842
166k
                                                /*InsertPos=*/nullptr);
1843
166k
  } else 
if (11.7k
isFriend11.7k
&&
D->isThisDeclarationADefinition()11.6k
) {
1844
7.23k
    // Do not connect the friend to the template unless it's actually a
1845
7.23k
    // definition. We don't want non-template functions to be marked as being
1846
7.23k
    // template instantiations.
1847
7.23k
    Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1848
7.23k
  }
1849
195k
1850
195k
  if (isFriend)
1851
29.5k
    Function->setObjectOfFriendDecl();
1852
195k
1853
195k
  if (InitFunctionInstantiation(Function, D))
1854
0
    Function->setInvalidDecl();
1855
195k
1856
195k
  bool IsExplicitSpecialization = false;
1857
195k
1858
195k
  LookupResult Previous(
1859
195k
      SemaRef, Function->getDeclName(), SourceLocation(),
1860
195k
      D->isLocalExternDecl() ? 
Sema::LookupRedeclarationWithLinkage74
1861
195k
                             : 
Sema::LookupOrdinaryName195k
,
1862
195k
      D->isLocalExternDecl() ? 
Sema::ForExternalRedeclaration74
1863
195k
                             : 
SemaRef.forRedeclarationInCurContext()195k
);
1864
195k
1865
195k
  if (DependentFunctionTemplateSpecializationInfo *Info
1866
4.31k
        = D->getDependentSpecializationInfo()) {
1867
4.31k
    assert(isFriend && "non-friend has dependent specialization info?");
1868
4.31k
1869
4.31k
    // Instantiate the explicit template arguments.
1870
4.31k
    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1871
4.31k
                                          Info->getRAngleLoc());
1872
4.31k
    if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1873
4.31k
                      ExplicitArgs, TemplateArgs))
1874
0
      return nullptr;
1875
4.31k
1876
4.31k
    // Map the candidate templates to their instantiations.
1877
38.6k
    
for (unsigned I = 0, E = Info->getNumTemplates(); 4.31k
I != E;
++I34.3k
) {
1878
34.3k
      Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1879
34.3k
                                                Info->getTemplate(I),
1880
34.3k
                                                TemplateArgs);
1881
34.3k
      if (!Temp) 
return nullptr0
;
1882
34.3k
1883
34.3k
      Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1884
34.3k
    }
1885
4.31k
1886
4.31k
    if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1887
4.31k
                                                    &ExplicitArgs,
1888
4.31k
                                                    Previous))
1889
0
      Function->setInvalidDecl();
1890
4.31k
1891
4.31k
    IsExplicitSpecialization = true;
1892
191k
  } else if (const ASTTemplateArgumentListInfo *Info =
1893
1
                 D->getTemplateSpecializationArgsAsWritten()) {
1894
1
    // The name of this function was written as a template-id.
1895
1
    SemaRef.LookupQualifiedName(Previous, DC);
1896
1
1897
1
    // Instantiate the explicit template arguments.
1898
1
    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1899
1
                                          Info->getRAngleLoc());
1900
1
    if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1901
1
                      ExplicitArgs, TemplateArgs))
1902
0
      return nullptr;
1903
1
1904
1
    if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1905
1
                                                    &ExplicitArgs,
1906
1
                                                    Previous))
1907
0
      Function->setInvalidDecl();
1908
1
1909
1
    IsExplicitSpecialization = true;
1910
191k
  } else if (TemplateParams || 
!FunctionTemplate173k
) {
1911
25.1k
    // Look only into the namespace where the friend would be declared to
1912
25.1k
    // find a previous declaration. This is the innermost enclosing namespace,
1913
25.1k
    // as described in ActOnFriendFunctionDecl.
1914
25.1k
    SemaRef.LookupQualifiedName(Previous, DC);
1915
25.1k
1916
25.1k
    // In C++, the previous declaration we find might be a tag type
1917
25.1k
    // (class or enum). In this case, the new declaration will hide the
1918
25.1k
    // tag type. Note that this does does not apply if we're declaring a
1919
25.1k
    // typedef (C++ [dcl.typedef]p4).
1920
25.1k
    if (Previous.isSingleTagDecl())
1921
0
      Previous.clear();
1922
25.1k
  }
1923
195k
1924
195k
  SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
1925
195k
                                   IsExplicitSpecialization);
1926
195k
1927
195k
  NamedDecl *PrincipalDecl = (TemplateParams
1928
195k
                              ? 
cast<NamedDecl>(FunctionTemplate)17.7k
1929
195k
                              : 
Function177k
);
1930
195k
1931
195k
  // If the original function was part of a friend declaration,
1932
195k
  // inherit its namespace state and add it to the owner.
1933
195k
  if (isFriend) {
1934
29.5k
    Function->setObjectOfFriendDecl();
1935
29.5k
    if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
1936
17.7k
      FT->setObjectOfFriendDecl();
1937
29.5k
    DC->makeDeclVisibleInContext(PrincipalDecl);
1938
29.5k
1939
29.5k
    bool QueuedInstantiation = false;
1940
29.5k
1941
29.5k
    // C++11 [temp.friend]p4 (DR329):
1942
29.5k
    //   When a function is defined in a friend function declaration in a class
1943
29.5k
    //   template, the function is instantiated when the function is odr-used.
1944
29.5k
    //   The same restrictions on multiple declarations and definitions that
1945
29.5k
    //   apply to non-template function declarations and definitions also apply
1946
29.5k
    //   to these implicit definitions.
1947
29.5k
    if (D->isThisDeclarationADefinition()) {
1948
7.39k
      SemaRef.CheckForFunctionRedefinition(Function);
1949
7.39k
      if (!Function->isInvalidDecl()) {
1950
7.38k
        for (auto R : Function->redecls()) {
1951
7.38k
          if (R == Function)
1952
7.37k
            continue;
1953
17
1954
17
          // If some prior declaration of this function has been used, we need
1955
17
          // to instantiate its definition.
1956
17
          if (!QueuedInstantiation && 
R->isUsed(false)15
) {
1957
5
            if (MemberSpecializationInfo *MSInfo =
1958
5
                Function->getMemberSpecializationInfo()) {
1959
5
              if (MSInfo->getPointOfInstantiation().isInvalid()) {
1960
5
                SourceLocation Loc = R->getLocation(); // FIXME
1961
5
                MSInfo->setPointOfInstantiation(Loc);
1962
5
                SemaRef.PendingLocalImplicitInstantiations.push_back(
1963
5
                    std::make_pair(Function, Loc));
1964
5
                QueuedInstantiation = true;
1965
5
              }
1966
5
            }
1967
5
          }
1968
17
        }
1969
7.37k
      }
1970
7.39k
    }
1971
29.5k
1972
29.5k
    // Check the template parameter list against the previous declaration. The
1973
29.5k
    // goal here is to pick up default arguments added since the friend was
1974
29.5k
    // declared; we know the template parameter lists match, since otherwise
1975
29.5k
    // we would not have picked this template as the previous declaration.
1976
29.5k
    if (TemplateParams && 
FunctionTemplate->getPreviousDecl()17.7k
) {
1977
17.6k
      SemaRef.CheckTemplateParameterList(
1978
17.6k
          TemplateParams,
1979
17.6k
          FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
1980
17.6k
          Function->isThisDeclarationADefinition()
1981
17.6k
              ? 
Sema::TPC_FriendFunctionTemplateDefinition0
1982
17.6k
              : Sema::TPC_FriendFunctionTemplate);
1983
17.6k
    }
1984
29.5k
  }
1985
195k
1986
195k
  if (Function->isLocalExternDecl() && 
!Function->getPreviousDecl()74
)
1987
53
    DC->makeDeclVisibleInContext(PrincipalDecl);
1988
195k
1989
195k
  if (Function->isOverloadedOperator() && 
!DC->isRecord()25.6k
&&
1990
195k
      
PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)25.6k
)
1991
18.3k
    PrincipalDecl->setNonMemberOperator();
1992
195k
1993
195k
  assert(!D->isDefaulted() && "only methods should be defaulted");
1994
195k
  return Function;
1995
195k
}
1996
1997
Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
1998
    CXXMethodDecl *D, TemplateParameterList *TemplateParams,
1999
    Optional<const ASTTemplateArgumentListInfo *>
2000
1.79M
        ClassScopeSpecializationArgs) {
2001
1.79M
  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2002
1.79M
  if (FunctionTemplate && 
!TemplateParams507k
) {
2003
262k
    // We are creating a function template specialization from a function
2004
262k
    // template. Check whether there is already a function template
2005
262k
    // specialization for this particular set of template arguments.
2006
262k
    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2007
262k
2008
262k
    void *InsertPos = nullptr;
2009
262k
    FunctionDecl *SpecFunc
2010
262k
      = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2011
262k
2012
262k
    // If we already have a function template specialization, return it.
2013
262k
    if (SpecFunc)
2014
88.3k
      return SpecFunc;
2015
1.70M
  }
2016
1.70M
2017
1.70M
  bool isFriend;
2018
1.70M
  if (FunctionTemplate)
2019
419k
    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2020
1.28M
  else
2021
1.28M
    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2022
1.70M
2023
1.70M
  bool MergeWithParentScope = (TemplateParams != nullptr) ||
2024
1.70M
    
!(1.45M
isa<Decl>(Owner)1.45M
&&
2025
1.45M
      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2026
1.70M
  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2027
1.70M
2028
1.70M
  // Instantiate enclosing template arguments for friends.
2029
1.70M
  SmallVector<TemplateParameterList *, 4> TempParamLists;
2030
1.70M
  unsigned NumTempParamLists = 0;
2031
1.70M
  if (isFriend && 
(NumTempParamLists = D->getNumTemplateParameterLists())40
) {
2032
3
    TempParamLists.resize(NumTempParamLists);
2033
10
    for (unsigned I = 0; I != NumTempParamLists; 
++I7
) {
2034
7
      TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2035
7
      TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2036
7
      if (!InstParams)
2037
0
        return nullptr;
2038
7
      TempParamLists[I] = InstParams;
2039
7
    }
2040
3
  }
2041
1.70M
2042
1.70M
  ExplicitSpecifier InstantiatedExplicitSpecifier =
2043
1.70M
      instantiateExplicitSpecifier(SemaRef, TemplateArgs,
2044
1.70M
                                   ExplicitSpecifier::getFromDecl(D), D);
2045
1.70M
  if (InstantiatedExplicitSpecifier.isInvalid())
2046
67
    return nullptr;
2047
1.70M
2048
1.70M
  SmallVector<ParmVarDecl *, 4> Params;
2049
1.70M
  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2050
1.70M
  if (!TInfo)
2051
43.0k
    return nullptr;
2052
1.65M
  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2053
1.65M
2054
1.65M
  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2055
1.65M
  if (QualifierLoc) {
2056
222
    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2057
222
                                                 TemplateArgs);
2058
222
    if (!QualifierLoc)
2059
1
      return nullptr;
2060
1.65M
  }
2061
1.65M
2062
1.65M
  DeclContext *DC = Owner;
2063
1.65M
  if (isFriend) {
2064
39
    if (QualifierLoc) {
2065
39
      CXXScopeSpec SS;
2066
39
      SS.Adopt(QualifierLoc);
2067
39
      DC = SemaRef.computeDeclContext(SS);
2068
39
2069
39
      if (DC && 
SemaRef.RequireCompleteDeclContext(SS, DC)37
)
2070
0
        return nullptr;
2071
0
    } else {
2072
0
      DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2073
0
                                           D->getDeclContext(),
2074
0
                                           TemplateArgs);
2075
0
    }
2076
39
    if (!DC) 
return nullptr2
;
2077
1.65M
  }
2078
1.65M
2079
1.65M
  // Build the instantiated method declaration.
2080
1.65M
  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2081
1.65M
  CXXMethodDecl *Method = nullptr;
2082
1.65M
2083
1.65M
  SourceLocation StartLoc = D->getInnerLocStart();
2084
1.65M
  DeclarationNameInfo NameInfo
2085
1.65M
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2086
1.65M
  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2087
280k
    Method = CXXConstructorDecl::Create(
2088
280k
        SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2089
280k
        InstantiatedExplicitSpecifier, Constructor->isInlineSpecified(), false,
2090
280k
        Constructor->getConstexprKind());
2091
280k
    Method->setRangeEnd(Constructor->getEndLoc());
2092
1.37M
  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2093
30.0k
    Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
2094
30.0k
                                       StartLoc, NameInfo, T, TInfo,
2095
30.0k
                                       Destructor->isInlineSpecified(),
2096
30.0k
                                       false);
2097
30.0k
    Method->setRangeEnd(Destructor->getEndLoc());
2098
1.34M
  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2099
12.3k
    Method = CXXConversionDecl::Create(
2100
12.3k
        SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2101
12.3k
        Conversion->isInlineSpecified(), InstantiatedExplicitSpecifier,
2102
12.3k
        Conversion->getConstexprKind(), Conversion->getEndLoc());
2103
1.33M
  } else {
2104
1.33M
    StorageClass SC = D->isStatic() ? 
SC_Static260k
:
SC_None1.07M
;
2105
1.33M
    Method = CXXMethodDecl::Create(SemaRef.Context, Record, StartLoc, NameInfo,
2106
1.33M
                                   T, TInfo, SC, D->isInlineSpecified(),
2107
1.33M
                                   D->getConstexprKind(), D->getEndLoc());
2108
1.33M
  }
2109
1.65M
2110
1.65M
  if (D->isInlined())
2111
1.26M
    Method->setImplicitlyInline();
2112
1.65M
2113
1.65M
  if (QualifierLoc)
2114
219
    Method->setQualifierInfo(QualifierLoc);
2115
1.65M
2116
1.65M
  if (TemplateParams) {
2117
245k
    // Our resulting instantiation is actually a function template, since we
2118
245k
    // are substituting only the outer template parameters. For example, given
2119
245k
    //
2120
245k
    //   template<typename T>
2121
245k
    //   struct X {
2122
245k
    //     template<typename U> void f(T, U);
2123
245k
    //   };
2124
245k
    //
2125
245k
    //   X<int> x;
2126
245k
    //
2127
245k
    // We are instantiating the member template "f" within X<int>, which means
2128
245k
    // substituting int for T, but leaving "f" as a member function template.
2129
245k
    // Build the function template itself.
2130
245k
    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2131
245k
                                                    Method->getLocation(),
2132
245k
                                                    Method->getDeclName(),
2133
245k
                                                    TemplateParams, Method);
2134
245k
    if (isFriend) {
2135
6
      FunctionTemplate->setLexicalDeclContext(Owner);
2136
6
      FunctionTemplate->setObjectOfFriendDecl();
2137
245k
    } else if (D->isOutOfLine())
2138
0
      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2139
245k
    Method->setDescribedFunctionTemplate(FunctionTemplate);
2140
1.41M
  } else if (FunctionTemplate) {
2141
130k
    // Record this function template specialization.
2142
130k
    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2143
130k
    Method->setFunctionTemplateSpecialization(FunctionTemplate,
2144
130k
                         TemplateArgumentList::CreateCopy(SemaRef.Context,
2145
130k
                                                          Innermost),
2146
130k
                                              /*InsertPos=*/nullptr);
2147
1.28M
  } else if (!isFriend) {
2148
1.28M
    // Record that this is an instantiation of a member function.
2149
1.28M
    Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2150
1.28M
  }
2151
1.65M
2152
1.65M
  // If we are instantiating a member function defined
2153
1.65M
  // out-of-line, the instantiation will have the same lexical
2154
1.65M
  // context (which will be a namespace scope) as the template.
2155
1.65M
  if (isFriend) {
2156
37
    if (NumTempParamLists)
2157
0
      Method->setTemplateParameterListsInfo(
2158
0
          SemaRef.Context,
2159
0
          llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
2160
37
2161
37
    Method->setLexicalDeclContext(Owner);
2162
37
    Method->setObjectOfFriendDecl();
2163
1.65M
  } else if (D->isOutOfLine())
2164
182
    Method->setLexicalDeclContext(D->getLexicalDeclContext());
2165
1.65M
2166
1.65M
  // Attach the parameters
2167
3.57M
  for (unsigned P = 0; P < Params.size(); 
++P1.91M
)
2168
1.91M
    Params[P]->setOwningFunction(Method);
2169
1.65M
  Method->setParams(Params);
2170
1.65M
2171
1.65M
  if (InitMethodInstantiation(Method, D))
2172
0
    Method->setInvalidDecl();
2173
1.65M
2174
1.65M
  LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2175
1.65M
                        Sema::ForExternalRedeclaration);
2176
1.65M
2177
1.65M
  bool IsExplicitSpecialization = false;
2178
1.65M
2179
1.65M
  // If the name of this function was written as a template-id, instantiate
2180
1.65M
  // the explicit template arguments.
2181
1.65M
  if (DependentFunctionTemplateSpecializationInfo *Info
2182
4
        = D->getDependentSpecializationInfo()) {
2183
4
    assert(isFriend && "non-friend has dependent specialization info?");
2184
4
2185
4
    // Instantiate the explicit template arguments.
2186
4
    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2187
4
                                          Info->getRAngleLoc());
2188
4
    if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2189
4
                      ExplicitArgs, TemplateArgs))
2190
0
      return nullptr;
2191
4
2192
4
    // Map the candidate templates to their instantiations.
2193
8
    
for (unsigned I = 0, E = Info->getNumTemplates(); 4
I != E;
++I4
) {
2194
4
      Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2195
4
                                                Info->getTemplate(I),
2196
4
                                                TemplateArgs);
2197
4
      if (!Temp) 
return nullptr0
;
2198
4
2199
4
      Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2200
4
    }
2201
4
2202
4
    if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2203
4
                                                    &ExplicitArgs,
2204
4
                                                    Previous))
2205
0
      Method->setInvalidDecl();
2206
4
2207
4
    IsExplicitSpecialization = true;
2208
1.65M
  } else if (const ASTTemplateArgumentListInfo *Info =
2209
72
                 ClassScopeSpecializationArgs.getValueOr(
2210
72
                     D->getTemplateSpecializationArgsAsWritten())) {
2211
72
    SemaRef.LookupQualifiedName(Previous, DC);
2212
72
2213
72
    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2214
72
                                          Info->getRAngleLoc());
2215
72
    if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
2216
72
                      ExplicitArgs, TemplateArgs))
2217
0
      return nullptr;
2218
72
2219
72
    if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2220
72
                                                    &ExplicitArgs,
2221
72
                                                    Previous))
2222
0
      Method->setInvalidDecl();
2223
72
2224
72
    IsExplicitSpecialization = true;
2225
1.65M
  } else if (ClassScopeSpecializationArgs) {
2226
7
    // Class-scope explicit specialization written without explicit template
2227
7
    // arguments.
2228
7
    SemaRef.LookupQualifiedName(Previous, DC);
2229
7
    if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
2230
0
      Method->setInvalidDecl();
2231
7
2232
7
    IsExplicitSpecialization = true;
2233
1.65M
  } else if (!FunctionTemplate || 
TemplateParams376k
||
isFriend130k
) {
2234
1.52M
    SemaRef.LookupQualifiedName(Previous, Record);
2235
1.52M
2236
1.52M
    // In C++, the previous declaration we find might be a tag type
2237
1.52M
    // (class or enum). In this case, the new declaration will hide the
2238
1.52M
    // tag type. Note that this does does not apply if we're declaring a
2239
1.52M
    // typedef (C++ [dcl.typedef]p4).
2240
1.52M
    if (Previous.isSingleTagDecl())
2241
0
      Previous.clear();
2242
1.52M
  }
2243
1.65M
2244
1.65M
  SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2245
1.65M
                                   IsExplicitSpecialization);
2246
1.65M
2247
1.65M
  if (D->isPure())
2248
64
    SemaRef.CheckPureMethod(Method, SourceRange());
2249
1.65M
2250
1.65M
  // Propagate access.  For a non-friend declaration, the access is
2251
1.65M
  // whatever we're propagating from.  For a friend, it should be the
2252
1.65M
  // previous declaration we just found.
2253
1.65M
  if (isFriend && 
Method->getPreviousDecl()37
)
2254
35
    Method->setAccess(Method->getPreviousDecl()->getAccess());
2255
1.65M
  else
2256
1.65M
    Method->setAccess(D->getAccess());
2257
1.65M
  if (FunctionTemplate)
2258
376k
    FunctionTemplate->setAccess(Method->getAccess());
2259
1.65M
2260
1.65M
  SemaRef.CheckOverrideControl(Method);
2261
1.65M
2262
1.65M
  // If a function is defined as defaulted or deleted, mark it as such now.
2263
1.65M
  if (D->isExplicitlyDefaulted())
2264
12.4k
    SemaRef.SetDeclDefaulted(Method, Method->getLocation());
2265
1.65M
  if (D->isDeletedAsWritten())
2266
19.6k
    SemaRef.SetDeclDeleted(Method, Method->getLocation());
2267
1.65M
2268
1.65M
  // If this is an explicit specialization, mark the implicitly-instantiated
2269
1.65M
  // template specialization as being an explicit specialization too.
2270
1.65M
  // FIXME: Is this necessary?
2271
1.65M
  if (IsExplicitSpecialization && 
!isFriend83
)
2272
78
    SemaRef.CompleteMemberSpecialization(Method, Previous);
2273
1.65M
2274
1.65M
  // If there's a function template, let our caller handle it.
2275
1.65M
  if (FunctionTemplate) {
2276
376k
    // do nothing
2277
376k
2278
376k
  // Don't hide a (potentially) valid declaration with an invalid one.
2279
1.28M
  } else if (Method->isInvalidDecl() && 
!Previous.empty()5
) {
2280
4
    // do nothing
2281
4
2282
4
  // Otherwise, check access to friends and make them visible.
2283
1.28M
  } else if (isFriend) {
2284
30
    // We only need to re-check access for methods which we didn't
2285
30
    // manage to match during parsing.
2286
30
    if (!D->getPreviousDecl())
2287
25
      SemaRef.CheckFriendAccess(Method);
2288
30
2289
30
    Record->makeDeclVisibleInContext(Method);
2290
30
2291
30
  // Otherwise, add the declaration.  We don't need to do this for
2292
30
  // class-scope specializations because we'll have matched them with
2293
30
  // the appropriate template.
2294
1.28M
  } else {
2295
1.28M
    Owner->addDecl(Method);
2296
1.28M
  }
2297
1.65M
2298
1.65M
  // PR17480: Honor the used attribute to instantiate member function
2299
1.65M
  // definitions
2300
1.65M
  if (Method->hasAttr<UsedAttr>()) {
2301
4
    if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2302
4
      SourceLocation Loc;
2303
4
      if (const MemberSpecializationInfo *MSInfo =
2304
0
              A->getMemberSpecializationInfo())
2305
0
        Loc = MSInfo->getPointOfInstantiation();
2306
4
      else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2307
4
        Loc = Spec->getPointOfInstantiation();
2308
4
      SemaRef.MarkFunctionReferenced(Loc, Method);
2309
4
    }
2310
4
  }
2311
1.65M
2312
1.65M
  return Method;
2313
1.65M
}
2314
2315
273k
Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2316
273k
  return VisitCXXMethodDecl(D);
2317
273k
}
2318
2319
30.0k
Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2320
30.0k
  return VisitCXXMethodDecl(D);
2321
30.0k
}
2322
2323
13.8k
Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2324
13.8k
  return VisitCXXMethodDecl(D);
2325
13.8k
}
2326
2327
0
Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2328
0
  return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
2329
0
                                  /*ExpectParameterPack=*/ false);
2330
0
}
2331
2332
Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2333
443k
                                                    TemplateTypeParmDecl *D) {
2334
443k
  // TODO: don't always clone when decls are refcounted.
2335
443k
  assert(D->getTypeForDecl()->isTemplateTypeParmType());
2336
443k
2337
443k
  TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
2338
443k
      SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
2339
443k
      D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2340
443k
      D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack());
2341
443k
  Inst->setAccess(AS_public);
2342
443k
2343
443k
  if (D->hasDefaultArgument() && 
!D->defaultArgumentWasInherited()51.0k
) {
2344
51.0k
    TypeSourceInfo *InstantiatedDefaultArg =
2345
51.0k
        SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2346
51.0k
                          D->getDefaultArgumentLoc(), D->getDeclName());
2347
51.0k
    if (InstantiatedDefaultArg)
2348
51.0k
      Inst->setDefaultArgument(InstantiatedDefaultArg);
2349
51.0k
  }
2350
443k
2351
443k
  // Introduce this template parameter's instantiation into the instantiation
2352
443k
  // scope.
2353
443k
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2354
443k
2355
443k
  return Inst;
2356
443k
}
2357
2358
Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2359
113k
                                                 NonTypeTemplateParmDecl *D) {
2360
113k
  // Substitute into the type of the non-type template parameter.
2361
113k
  TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2362
113k
  SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2363
113k
  SmallVector<QualType, 4> ExpandedParameterPackTypes;
2364
113k
  bool IsExpandedParameterPack = false;
2365
113k
  TypeSourceInfo *DI;
2366
113k
  QualType T;
2367
113k
  bool Invalid = false;
2368
113k
2369
113k
  if (D->isExpandedParameterPack()) {
2370
3
    // The non-type template parameter pack is an already-expanded pack
2371
3
    // expansion of types. Substitute into each of the expanded types.
2372
3
    ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2373
3
    ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2374
12
    for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; 
++I9
) {
2375
9
      TypeSourceInfo *NewDI =
2376
9
          SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2377
9
                            D->getLocation(), D->getDeclName());
2378
9
      if (!NewDI)
2379
0
        return nullptr;
2380
9
2381
9
      QualType NewT =
2382
9
          SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2383
9
      if (NewT.isNull())
2384
0
        return nullptr;
2385
9
2386
9
      ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2387
9
      ExpandedParameterPackTypes.push_back(NewT);
2388
9
    }
2389
3
2390
3
    IsExpandedParameterPack = true;
2391
3
    DI = D->getTypeSourceInfo();
2392
3
    T = DI->getType();
2393
113k
  } else if (D->isPackExpansion()) {
2394
39
    // The non-type template parameter pack's type is a pack expansion of types.
2395
39
    // Determine whether we need to expand this parameter pack into separate
2396
39
    // types.
2397
39
    PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
2398
39
    TypeLoc Pattern = Expansion.getPatternLoc();
2399
39
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2400
39
    SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2401
39
2402
39
    // Determine whether the set of unexpanded parameter packs can and should
2403
39
    // be expanded.
2404
39
    bool Expand = true;
2405
39
    bool RetainExpansion = false;
2406
39
    Optional<unsigned> OrigNumExpansions
2407
39
      = Expansion.getTypePtr()->getNumExpansions();
2408
39
    Optional<unsigned> NumExpansions = OrigNumExpansions;
2409
39
    if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2410
39
                                                Pattern.getSourceRange(),
2411
39
                                                Unexpanded,
2412
39
                                                TemplateArgs,
2413
39
                                                Expand, RetainExpansion,
2414
39
                                                NumExpansions))
2415
0
      return nullptr;
2416
39
2417
39
    if (Expand) {
2418
89
      for (unsigned I = 0; I != *NumExpansions; 
++I55
) {
2419
56
        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2420
56
        TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2421
56
                                                  D->getLocation(),
2422
56
                                                  D->getDeclName());
2423
56
        if (!NewDI)
2424
0
          return nullptr;
2425
56
2426
56
        QualType NewT =
2427
56
            SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2428
56
        if (NewT.isNull())
2429
1
          return nullptr;
2430
55
2431
55
        ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2432
55
        ExpandedParameterPackTypes.push_back(NewT);
2433
55
      }
2434
34
2435
34
      // Note that we have an expanded parameter pack. The "type" of this
2436
34
      // expanded parameter pack is the original expansion type, but callers
2437
34
      // will end up using the expanded parameter pack types for type-checking.
2438
34
      IsExpandedParameterPack = true;
2439
33
      DI = D->getTypeSourceInfo();
2440
33
      T = DI->getType();
2441
33
    } else {
2442
5
      // We cannot fully expand the pack expansion now, so substitute into the
2443
5
      // pattern and create a new pack expansion type.
2444
5
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2445
5
      TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2446
5
                                                     D->getLocation(),
2447
5
                                                     D->getDeclName());
2448
5
      if (!NewPattern)
2449
0
        return nullptr;
2450
5
2451
5
      SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
2452
5
      DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2453
5
                                      NumExpansions);
2454
5
      if (!DI)
2455
0
        return nullptr;
2456
5
2457
5
      T = DI->getType();
2458
5
    }
2459
113k
  } else {
2460
113k
    // Simple case: substitution into a parameter that is not a parameter pack.
2461
113k
    DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2462
113k
                           D->getLocation(), D->getDeclName());
2463
113k
    if (!DI)
2464
3
      return nullptr;
2465
113k
2466
113k
    // Check that this type is acceptable for a non-type template parameter.
2467
113k
    T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
2468
113k
    if (T.isNull()) {
2469
4
      T = SemaRef.Context.IntTy;
2470
4
      Invalid = true;
2471
4
    }
2472
113k
  }
2473
113k
2474
113k
  NonTypeTemplateParmDecl *Param;
2475
113k
  if (IsExpandedParameterPack)
2476
36
    Param = NonTypeTemplateParmDecl::Create(
2477
36
        SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2478
36
        D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2479
36
        D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
2480
36
        ExpandedParameterPackTypesAsWritten);
2481
113k
  else
2482
113k
    Param = NonTypeTemplateParmDecl::Create(
2483
113k
        SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2484
113k
        D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2485
113k
        D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
2486
113k
2487
113k
  Param->setAccess(AS_public);
2488
113k
  if (Invalid)
2489
4
    Param->setInvalidDecl();
2490
113k
2491
113k
  if (D->hasDefaultArgument() && 
!D->defaultArgumentWasInherited()40.5k
) {
2492
40.5k
    EnterExpressionEvaluationContext ConstantEvaluated(
2493
40.5k
        SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2494
40.5k
    ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2495
40.5k
    if (!Value.isInvalid())
2496
40.4k
      Param->setDefaultArgument(Value.get());
2497
40.5k
  }
2498
113k
2499
113k
  // Introduce this template parameter's instantiation into the instantiation
2500
113k
  // scope.
2501
113k
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2502
113k
  return Param;
2503
113k
}
2504
2505
static void collectUnexpandedParameterPacks(
2506
    Sema &S,
2507
    TemplateParameterList *Params,
2508
13
    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
2509
14
  for (const auto &P : *Params) {
2510
14
    if (P->isTemplateParameterPack())
2511
0
      continue;
2512
14
    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
2513
13
      S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2514
13
                                        Unexpanded);
2515
14
    if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
2516
0
      collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2517
0
                                      Unexpanded);
2518
14
  }
2519
13
}
2520
2521
Decl *
2522
TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2523
1.35k
                                                  TemplateTemplateParmDecl *D) {
2524
1.35k
  // Instantiate the template parameter list of the template template parameter.
2525
1.35k
  TemplateParameterList *TempParams = D->getTemplateParameters();
2526
1.35k
  TemplateParameterList *InstParams;
2527
1.35k
  SmallVector<TemplateParameterList*, 8> ExpandedParams;
2528
1.35k
2529
1.35k
  bool IsExpandedParameterPack = false;
2530
1.35k
2531
1.35k
  if (D->isExpandedParameterPack()) {
2532
0
    // The template template parameter pack is an already-expanded pack
2533
0
    // expansion of template parameters. Substitute into each of the expanded
2534
0
    // parameters.
2535
0
    ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2536
0
    for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2537
0
         I != N; ++I) {
2538
0
      LocalInstantiationScope Scope(SemaRef);
2539
0
      TemplateParameterList *Expansion =
2540
0
        SubstTemplateParams(D->getExpansionTemplateParameters(I));
2541
0
      if (!Expansion)
2542
0
        return nullptr;
2543
0
      ExpandedParams.push_back(Expansion);
2544
0
    }
2545
0
2546
0
    IsExpandedParameterPack = true;
2547
0
    InstParams = TempParams;
2548
1.35k
  } else if (D->isPackExpansion()) {
2549
13
    // The template template parameter pack expands to a pack of template
2550
13
    // template parameters. Determine whether we need to expand this parameter
2551
13
    // pack into separate parameters.
2552
13
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2553
13
    collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2554
13
                                    Unexpanded);
2555
13
2556
13
    // Determine whether the set of unexpanded parameter packs can and should
2557
13
    // be expanded.
2558
13
    bool Expand = true;
2559
13
    bool RetainExpansion = false;
2560
13
    Optional<unsigned> NumExpansions;
2561
13
    if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2562
13
                                                TempParams->getSourceRange(),
2563
13
                                                Unexpanded,
2564
13
                                                TemplateArgs,
2565
13
                                                Expand, RetainExpansion,
2566
13
                                                NumExpansions))
2567
0
      return nullptr;
2568
13
2569
13
    if (Expand) {
2570
8.23k
      for (unsigned I = 0; I != *NumExpansions; 
++I8.22k
) {
2571
8.22k
        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2572
8.22k
        LocalInstantiationScope Scope(SemaRef);
2573
8.22k
        TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2574
8.22k
        if (!Expansion)
2575
0
          return nullptr;
2576
8.22k
        ExpandedParams.push_back(Expansion);
2577
8.22k
      }
2578
13
2579
13
      // Note that we have an expanded parameter pack. The "type" of this
2580
13
      // expanded parameter pack is the original expansion type, but callers
2581
13
      // will end up using the expanded parameter pack types for type-checking.
2582
13
      IsExpandedParameterPack = true;
2583
13
      InstParams = TempParams;
2584
13
    } else {
2585
0
      // We cannot fully expand the pack expansion now, so just substitute
2586
0
      // into the pattern.
2587
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2588
0
2589
0
      LocalInstantiationScope Scope(SemaRef);
2590
0
      InstParams = SubstTemplateParams(TempParams);
2591
0
      if (!InstParams)
2592
0
        return nullptr;
2593
1.34k
    }
2594
1.34k
  } else {
2595
1.34k
    // Perform the actual substitution of template parameters within a new,
2596
1.34k
    // local instantiation scope.
2597
1.34k
    LocalInstantiationScope Scope(SemaRef);
2598
1.34k
    InstParams = SubstTemplateParams(TempParams);
2599
1.34k
    if (!InstParams)
2600
3
      return nullptr;
2601
1.35k
  }
2602
1.35k
2603
1.35k
  // Build the template template parameter.
2604
1.35k
  TemplateTemplateParmDecl *Param;
2605
1.35k
  if (IsExpandedParameterPack)
2606
13
    Param = TemplateTemplateParmDecl::Create(
2607
13
        SemaRef.Context, Owner, D->getLocation(),
2608
13
        D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2609
13
        D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
2610
1.34k
  else
2611
1.34k
    Param = TemplateTemplateParmDecl::Create(
2612
1.34k
        SemaRef.Context, Owner, D->getLocation(),
2613
1.34k
        D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2614
1.34k
        D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
2615
1.35k
  if (D->hasDefaultArgument() && 
!D->defaultArgumentWasInherited()5
) {
2616
5
    NestedNameSpecifierLoc QualifierLoc =
2617
5
        D->getDefaultArgument().getTemplateQualifierLoc();
2618
5
    QualifierLoc =
2619
5
        SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2620
5
    TemplateName TName = SemaRef.SubstTemplateName(
2621
5
        QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2622
5
        D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2623
5
    if (!TName.isNull())
2624
5
      Param->setDefaultArgument(
2625
5
          SemaRef.Context,
2626
5
          TemplateArgumentLoc(TemplateArgument(TName),
2627
5
                              D->getDefaultArgument().getTemplateQualifierLoc(),
2628
5
                              D->getDefaultArgument().getTemplateNameLoc()));
2629
5
  }
2630
1.35k
  Param->setAccess(AS_public);
2631
1.35k
2632
1.35k
  // Introduce this template parameter's instantiation into the instantiation
2633
1.35k
  // scope.
2634
1.35k
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2635
1.35k
2636
1.35k
  return Param;
2637
1.35k
}
2638
2639
2
Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2640
2
  // Using directives are never dependent (and never contain any types or
2641
2
  // expressions), so they require no explicit instantiation work.
2642
2
2643
2
  UsingDirectiveDecl *Inst
2644
2
    = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2645
2
                                 D->getNamespaceKeyLocation(),
2646
2
                                 D->getQualifierLoc(),
2647
2
                                 D->getIdentLocation(),
2648
2
                                 D->getNominatedNamespace(),
2649
2
                                 D->getCommonAncestor());
2650
2
2651
2
  // Add the using directive to its declaration context
2652
2
  // only if this is not a function or method.
2653
2
  if (!Owner->isFunctionOrMethod())
2654
0
    Owner->addDecl(Inst);
2655
2
2656
2
  return Inst;
2657
2
}
2658
2659
186
Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2660
186
2661
186
  // The nested name specifier may be dependent, for example
2662
186
  //     template <typename T> struct t {
2663
186
  //       struct s1 { T f1(); };
2664
186
  //       struct s2 : s1 { using s1::f1; };
2665
186
  //     };
2666
186
  //     template struct t<int>;
2667
186
  // Here, in using s1::f1, s1 refers to t<T>::s1;
2668
186
  // we need to substitute for t<int>::s1.
2669
186
  NestedNameSpecifierLoc QualifierLoc
2670
186
    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2671
186
                                          TemplateArgs);
2672
186
  if (!QualifierLoc)
2673
0
    return nullptr;
2674
186
2675
186
  // For an inheriting constructor declaration, the name of the using
2676
186
  // declaration is the name of a constructor in this class, not in the
2677
186
  // base class.
2678
186
  DeclarationNameInfo NameInfo = D->getNameInfo();
2679
186
  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2680
17
    if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
2681
17
      NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
2682
17
          SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
2683
186
2684
186
  // We only need to do redeclaration lookups if we're in a class
2685
186
  // scope (in fact, it's not really even possible in non-class
2686
186
  // scopes).
2687
186
  bool CheckRedeclaration = Owner->isRecord();
2688
186
2689
186
  LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2690
186
                    Sema::ForVisibleRedeclaration);
2691
186
2692
186
  UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2693
186
                                       D->getUsingLoc(),
2694
186
                                       QualifierLoc,
2695
186
                                       NameInfo,
2696
186
                                       D->hasTypename());
2697
186
2698
186
  CXXScopeSpec SS;
2699
186
  SS.Adopt(QualifierLoc);
2700
186
  if (CheckRedeclaration) {
2701
176
    Prev.setHideTags(false);
2702
176
    SemaRef.LookupQualifiedName(Prev, Owner);
2703
176
2704
176
    // Check for invalid redeclarations.
2705
176
    if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2706
176
                                            D->hasTypename(), SS,
2707
176
                                            D->getLocation(), Prev))
2708
0
      NewUD->setInvalidDecl();
2709
176
2710
176
  }
2711
186
2712
186
  if (!NewUD->isInvalidDecl() &&
2713
186
      SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(),
2714
186
                                      SS, NameInfo, D->getLocation()))
2715
2
    NewUD->setInvalidDecl();
2716
186
2717
186
  SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2718
186
  NewUD->setAccess(D->getAccess());
2719
186
  Owner->addDecl(NewUD);
2720
186
2721
186
  // Don't process the shadow decls for an invalid decl.
2722
186
  if (NewUD->isInvalidDecl())
2723
2
    return NewUD;
2724
184
2725
184
  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2726
16
    SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
2727
184
2728
184
  bool isFunctionScope = Owner->isFunctionOrMethod();
2729
184
2730
184
  // Process the shadow decls.
2731
286
  for (auto *Shadow : D->shadows()) {
2732
286
    // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
2733
286
    // reconstruct it in the case where it matters.
2734
286
    NamedDecl *OldTarget = Shadow->getTargetDecl();
2735
286
    if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
2736
48
      if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
2737
4
        OldTarget = BaseShadow;
2738
286
2739
286
    NamedDecl *InstTarget =
2740
286
        cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2741
286
            Shadow->getLocation(), OldTarget, TemplateArgs));
2742
286
    if (!InstTarget)
2743
0
      return nullptr;
2744
286
2745
286
    UsingShadowDecl *PrevDecl = nullptr;
2746
286
    if (CheckRedeclaration) {
2747
228
      if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2748
3
        continue;
2749
58
    } else if (UsingShadowDecl *OldPrev =
2750
0
                   getPreviousDeclForInstantiation(Shadow)) {
2751
0
      PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2752
0
          Shadow->getLocation(), OldPrev, TemplateArgs));
2753
0
    }
2754
286
2755
286
    UsingShadowDecl *InstShadow =
2756
283
        SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2757
283
                                     PrevDecl);
2758
283
    SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2759
283
2760
283
    if (isFunctionScope)
2761
58
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2762
283
  }
2763
184
2764
184
  return NewUD;
2765
184
}
2766
2767
181
Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2768
181
  // Ignore these;  we handle them in bulk when processing the UsingDecl.
2769
181
  return nullptr;
2770
181
}
2771
2772
Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
2773
51
    ConstructorUsingShadowDecl *D) {
2774
51
  // Ignore these;  we handle them in bulk when processing the UsingDecl.
2775
51
  return nullptr;
2776
51
}
2777
2778
template <typename T>
2779
Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
2780
510
    T *D, bool InstantiatingPackElement) {
2781
510
  // If this is a pack expansion, expand it now.
2782
510
  if (D->isPackExpansion() && 
!InstantiatingPackElement96
) {
2783
40
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2784
40
    SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
2785
40
    SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
2786
40
2787
40
    // Determine whether the set of unexpanded parameter packs can and should
2788
40
    // be expanded.
2789
40
    bool Expand = true;
2790
40
    bool RetainExpansion = false;
2791
40
    Optional<unsigned> NumExpansions;
2792
40
    if (SemaRef.CheckParameterPacksForExpansion(
2793
40
          D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
2794
40
            Expand, RetainExpansion, NumExpansions))
2795
0
      return nullptr;
2796
40
2797
40
    // This declaration cannot appear within a function template signature,
2798
40
    // so we can't have a partial argument list for a parameter pack.
2799
40
    assert(!RetainExpansion &&
2800
40
           "should never need to retain an expansion for UsingPackDecl");
2801
40
2802
40
    if (!Expand) {
2803
0
      // We cannot fully expand the pack expansion now, so substitute into the
2804
0
      // pattern and create a new pack expansion.
2805
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2806
0
      return instantiateUnresolvedUsingDecl(D, true);
2807
0
    }
2808
40
2809
40
    // Within a function, we don't have any normal way to check for conflicts
2810
40
    // between shadow declarations from different using declarations in the
2811
40
    // same pack expansion, but this is always ill-formed because all expansions
2812
40
    // must produce (conflicting) enumerators.
2813
40
    //
2814
40
    // Sadly we can't just reject this in the template definition because it
2815
40
    // could be valid if the pack is empty or has exactly one expansion.
2816
40
    if (D->getDeclContext()->isFunctionOrMethod() && 
*NumExpansions > 16
) {
2817
2
      SemaRef.Diag(D->getEllipsisLoc(),
2818
2
                   diag::err_using_decl_redeclaration_expansion);
2819
2
      return nullptr;
2820
2
    }
2821
38
2822
38
    // Instantiate the slices of this pack and build a UsingPackDecl.
2823
38
    SmallVector<NamedDecl*, 8> Expansions;
2824
92
    for (unsigned I = 0; I != *NumExpansions; 
++I54
) {
2825
56
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2826
56
      Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
2827
56
      if (!Slice)
2828
2
        return nullptr;
2829
54
      // Note that we can still get unresolved using declarations here, if we
2830
54
      // had arguments for all packs but the pattern also contained other
2831
54
      // template arguments (this only happens during partial substitution, eg
2832
54
      // into the body of a generic lambda in a function template).
2833
54
      Expansions.push_back(cast<NamedDecl>(Slice));
2834
54
    }
2835
38
2836
38
    auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2837
36
    if (isDeclWithinFunction(D))
2838
16
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2839
36
    return NewD;
2840
470
  }
2841
470
2842
470
  UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
2843
470
  SourceLocation TypenameLoc = TD ? 
TD->getTypenameLoc()106
:
SourceLocation()364
;
2844
470
2845
470
  NestedNameSpecifierLoc QualifierLoc
2846
470
    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2847
470
                                          TemplateArgs);
2848
470
  if (!QualifierLoc)
2849
7
    return nullptr;
2850
463
2851
463
  CXXScopeSpec SS;
2852
463
  SS.Adopt(QualifierLoc);
2853
463
2854
463
  DeclarationNameInfo NameInfo
2855
463
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2856
463
2857
463
  // Produce a pack expansion only if we're not instantiating a particular
2858
463
  // slice of a pack expansion.
2859
463
  bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
2860
463
                            
SemaRef.ArgumentPackSubstitutionIndex != -156
;
2861
463
  SourceLocation EllipsisLoc =
2862
463
      InstantiatingSlice ? 
SourceLocation()56
:
D->getEllipsisLoc()407
;
2863
463
2864
463
  NamedDecl *UD = SemaRef.BuildUsingDeclaration(
2865
463
      /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
2866
463
      /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
2867
463
      ParsedAttributesView(),
2868
463
      /*IsInstantiation*/ true);
2869
463
  if (UD)
2870
439
    SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
2871
463
2872
463
  return UD;
2873
463
}
clang::Decl* clang::TemplateDeclInstantiator::instantiateUnresolvedUsingDecl<clang::UnresolvedUsingTypenameDecl>(clang::UnresolvedUsingTypenameDecl*, bool)
Line
Count
Source
2780
116
    T *D, bool InstantiatingPackElement) {
2781
116
  // If this is a pack expansion, expand it now.
2782
116
  if (D->isPackExpansion() && 
!InstantiatingPackElement23
) {
2783
10
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2784
10
    SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
2785
10
    SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
2786
10
2787
10
    // Determine whether the set of unexpanded parameter packs can and should
2788
10
    // be expanded.
2789
10
    bool Expand = true;
2790
10
    bool RetainExpansion = false;
2791
10
    Optional<unsigned> NumExpansions;
2792
10
    if (SemaRef.CheckParameterPacksForExpansion(
2793
10
          D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
2794
10
            Expand, RetainExpansion, NumExpansions))
2795
0
      return nullptr;
2796
10
2797
10
    // This declaration cannot appear within a function template signature,
2798
10
    // so we can't have a partial argument list for a parameter pack.
2799
10
    assert(!RetainExpansion &&
2800
10
           "should never need to retain an expansion for UsingPackDecl");
2801
10
2802
10
    if (!Expand) {
2803
0
      // We cannot fully expand the pack expansion now, so substitute into the
2804
0
      // pattern and create a new pack expansion.
2805
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2806
0
      return instantiateUnresolvedUsingDecl(D, true);
2807
0
    }
2808
10
2809
10
    // Within a function, we don't have any normal way to check for conflicts
2810
10
    // between shadow declarations from different using declarations in the
2811
10
    // same pack expansion, but this is always ill-formed because all expansions
2812
10
    // must produce (conflicting) enumerators.
2813
10
    //
2814
10
    // Sadly we can't just reject this in the template definition because it
2815
10
    // could be valid if the pack is empty or has exactly one expansion.
2816
10
    if (D->getDeclContext()->isFunctionOrMethod() && 
*NumExpansions > 10
) {
2817
0
      SemaRef.Diag(D->getEllipsisLoc(),
2818
0
                   diag::err_using_decl_redeclaration_expansion);
2819
0
      return nullptr;
2820
0
    }
2821
10
2822
10
    // Instantiate the slices of this pack and build a UsingPackDecl.
2823
10
    SmallVector<NamedDecl*, 8> Expansions;
2824
23
    for (unsigned I = 0; I != *NumExpansions; 
++I13
) {
2825
13
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2826
13
      Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
2827
13
      if (!Slice)
2828
0
        return nullptr;
2829
13
      // Note that we can still get unresolved using declarations here, if we
2830
13
      // had arguments for all packs but the pattern also contained other
2831
13
      // template arguments (this only happens during partial substitution, eg
2832
13
      // into the body of a generic lambda in a function template).
2833
13
      Expansions.push_back(cast<NamedDecl>(Slice));
2834
13
    }
2835
10
2836
10
    auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2837
10
    if (isDeclWithinFunction(D))
2838
7
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2839
10
    return NewD;
2840
106
  }
2841
106
2842
106
  UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
2843
106
  SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : 
SourceLocation()0
;
2844
106
2845
106
  NestedNameSpecifierLoc QualifierLoc
2846
106
    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2847
106
                                          TemplateArgs);
2848
106
  if (!QualifierLoc)
2849
0
    return nullptr;
2850
106
2851
106
  CXXScopeSpec SS;
2852
106
  SS.Adopt(QualifierLoc);
2853
106
2854
106
  DeclarationNameInfo NameInfo
2855
106
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2856
106
2857
106
  // Produce a pack expansion only if we're not instantiating a particular
2858
106
  // slice of a pack expansion.
2859
106
  bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
2860
106
                            
SemaRef.ArgumentPackSubstitutionIndex != -113
;
2861
106
  SourceLocation EllipsisLoc =
2862
106
      InstantiatingSlice ? 
SourceLocation()13
:
D->getEllipsisLoc()93
;
2863
106
2864
106
  NamedDecl *UD = SemaRef.BuildUsingDeclaration(
2865
106
      /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
2866
106
      /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
2867
106
      ParsedAttributesView(),
2868
106
      /*IsInstantiation*/ true);
2869
106
  if (UD)
2870
106
    SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
2871
106
2872
106
  return UD;
2873
106
}
clang::Decl* clang::TemplateDeclInstantiator::instantiateUnresolvedUsingDecl<clang::UnresolvedUsingValueDecl>(clang::UnresolvedUsingValueDecl*, bool)
Line
Count
Source
2780
394
    T *D, bool InstantiatingPackElement) {
2781
394
  // If this is a pack expansion, expand it now.
2782
394
  if (D->isPackExpansion() && 
!InstantiatingPackElement73
) {
2783
30
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2784
30
    SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
2785
30
    SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
2786
30
2787
30
    // Determine whether the set of unexpanded parameter packs can and should
2788
30
    // be expanded.
2789
30
    bool Expand = true;
2790
30
    bool RetainExpansion = false;
2791
30
    Optional<unsigned> NumExpansions;
2792
30
    if (SemaRef.CheckParameterPacksForExpansion(
2793
30
          D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
2794
30
            Expand, RetainExpansion, NumExpansions))
2795
0
      return nullptr;
2796
30
2797
30
    // This declaration cannot appear within a function template signature,
2798
30
    // so we can't have a partial argument list for a parameter pack.
2799
30
    assert(!RetainExpansion &&
2800
30
           "should never need to retain an expansion for UsingPackDecl");
2801
30
2802
30
    if (!Expand) {
2803
0
      // We cannot fully expand the pack expansion now, so substitute into the
2804
0
      // pattern and create a new pack expansion.
2805
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2806
0
      return instantiateUnresolvedUsingDecl(D, true);
2807
0
    }
2808
30
2809
30
    // Within a function, we don't have any normal way to check for conflicts
2810
30
    // between shadow declarations from different using declarations in the
2811
30
    // same pack expansion, but this is always ill-formed because all expansions
2812
30
    // must produce (conflicting) enumerators.
2813
30
    //
2814
30
    // Sadly we can't just reject this in the template definition because it
2815
30
    // could be valid if the pack is empty or has exactly one expansion.
2816
30
    if (D->getDeclContext()->isFunctionOrMethod() && 
*NumExpansions > 16
) {
2817
2
      SemaRef.Diag(D->getEllipsisLoc(),
2818
2
                   diag::err_using_decl_redeclaration_expansion);
2819
2
      return nullptr;
2820
2
    }
2821
28
2822
28
    // Instantiate the slices of this pack and build a UsingPackDecl.
2823
28
    SmallVector<NamedDecl*, 8> Expansions;
2824
69
    for (unsigned I = 0; I != *NumExpansions; 
++I41
) {
2825
43
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2826
43
      Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
2827
43
      if (!Slice)
2828
2
        return nullptr;
2829
41
      // Note that we can still get unresolved using declarations here, if we
2830
41
      // had arguments for all packs but the pattern also contained other
2831
41
      // template arguments (this only happens during partial substitution, eg
2832
41
      // into the body of a generic lambda in a function template).
2833
41
      Expansions.push_back(cast<NamedDecl>(Slice));
2834
41
    }
2835
28
2836
28
    auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2837
26
    if (isDeclWithinFunction(D))
2838
9
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2839
26
    return NewD;
2840
364
  }
2841
364
2842
364
  UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
2843
364
  SourceLocation TypenameLoc = TD ? 
TD->getTypenameLoc()0
: SourceLocation();
2844
364
2845
364
  NestedNameSpecifierLoc QualifierLoc
2846
364
    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2847
364
                                          TemplateArgs);
2848
364
  if (!QualifierLoc)
2849
7
    return nullptr;
2850
357
2851
357
  CXXScopeSpec SS;
2852
357
  SS.Adopt(QualifierLoc);
2853
357
2854
357
  DeclarationNameInfo NameInfo
2855
357
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2856
357
2857
357
  // Produce a pack expansion only if we're not instantiating a particular
2858
357
  // slice of a pack expansion.
2859
357
  bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
2860
357
                            
SemaRef.ArgumentPackSubstitutionIndex != -143
;
2861
357
  SourceLocation EllipsisLoc =
2862
357
      InstantiatingSlice ? 
SourceLocation()43
:
D->getEllipsisLoc()314
;
2863
357
2864
357
  NamedDecl *UD = SemaRef.BuildUsingDeclaration(
2865
357
      /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
2866
357
      /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
2867
357
      ParsedAttributesView(),
2868
357
      /*IsInstantiation*/ true);
2869
357
  if (UD)
2870
333
    SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
2871
357
2872
357
  return UD;
2873
357
}
2874
2875
Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
2876
103
    UnresolvedUsingTypenameDecl *D) {
2877
103
  return instantiateUnresolvedUsingDecl(D);
2878
103
}
2879
2880
Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
2881
351
    UnresolvedUsingValueDecl *D) {
2882
351
  return instantiateUnresolvedUsingDecl(D);
2883
351
}
2884
2885
8
Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
2886
8
  SmallVector<NamedDecl*, 8> Expansions;
2887
10
  for (auto *UD : D->expansions()) {
2888
10
    if (NamedDecl *NewUD =
2889
10
            SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
2890
10
      Expansions.push_back(NewUD);
2891
0
    else
2892
0
      return nullptr;
2893
10
  }
2894
8
2895
8
  auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2896
8
  if (isDeclWithinFunction(D))
2897
8
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2898
8
  return NewD;
2899
8
}
2900
2901
Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2902
80
    ClassScopeFunctionSpecializationDecl *Decl) {
2903
80
  CXXMethodDecl *OldFD = Decl->getSpecialization();
2904
80
  return cast_or_null<CXXMethodDecl>(
2905
80
      VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
2906
80
}
2907
2908
Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2909
148
                                     OMPThreadPrivateDecl *D) {
2910
148
  SmallVector<Expr *, 5> Vars;
2911
172
  for (auto *I : D->varlists()) {
2912
172
    Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2913
172
    assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
2914
172
    Vars.push_back(Var);
2915
172
  }
2916
148
2917
148
  OMPThreadPrivateDecl *TD =
2918
148
    SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2919
148
2920
148
  TD->setAccess(AS_public);
2921
148
  Owner->addDecl(TD);
2922
148
2923
148
  return TD;
2924
148
}
2925
2926
58
Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
2927
58
  SmallVector<Expr *, 5> Vars;
2928
58
  for (auto *I : D->varlists()) {
2929
58
    Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2930
58
    assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
2931
58
    Vars.push_back(Var);
2932
58
  }
2933
58
  SmallVector<OMPClause *, 4> Clauses;
2934
58
  // Copy map clauses from the original mapper.
2935
58
  for (OMPClause *C : D->clauselists()) {
2936
42
    auto *AC = cast<OMPAllocatorClause>(C);
2937
42
    ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
2938
42
    if (!NewE.isUsable())
2939
0
      continue;
2940
42
    OMPClause *IC = SemaRef.ActOnOpenMPAllocatorClause(
2941
42
        NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
2942
42
    Clauses.push_back(IC);
2943
42
  }
2944
58
2945
58
  Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
2946
58
      D->getLocation(), Vars, Clauses, Owner);
2947
58
  if (Res.get().isNull())
2948
0
    return nullptr;
2949
58
  return Res.get().getSingleDecl();
2950
58
}
2951
2952
0
Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
2953
0
  llvm_unreachable(
2954
0
      "Requires directive cannot be instantiated within a dependent context");
2955
0
}
2956
2957
Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
2958
130
    OMPDeclareReductionDecl *D) {
2959
130
  // Instantiate type and check if it is allowed.
2960
130
  const bool RequiresInstantiation =
2961
130
      D->getType()->isDependentType() ||
2962
130
      
D->getType()->isInstantiationDependentType()18
||
2963
130
      
D->getType()->containsUnexpandedParameterPack()18
;
2964
130
  QualType SubstReductionType;
2965
130
  if (RequiresInstantiation) {
2966
112
    SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
2967
112
        D->getLocation(),
2968
112
        ParsedType::make(SemaRef.SubstType(
2969
112
            D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
2970
112
  } else {
2971
18
    SubstReductionType = D->getType();
2972
18
  }
2973
130
  if (SubstReductionType.isNull())
2974
12
    return nullptr;
2975
118
  bool IsCorrect = !SubstReductionType.isNull();
2976
118
  // Create instantiated copy.
2977
118
  std::pair<QualType, SourceLocation> ReductionTypes[] = {
2978
118
      std::make_pair(SubstReductionType, D->getLocation())};
2979
118
  auto *PrevDeclInScope = D->getPrevDeclInScope();
2980
118
  if (PrevDeclInScope && 
!PrevDeclInScope->isInvalidDecl()18
) {
2981
18
    PrevDeclInScope = cast<OMPDeclareReductionDecl>(
2982
18
        SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
2983
18
            ->get<Decl *>());
2984
18
  }
2985
118
  auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
2986
118
      /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
2987
118
      PrevDeclInScope);
2988
118
  auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
2989
118
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
2990
118
  if (!RequiresInstantiation) {
2991
18
    if (Expr *Combiner = D->getCombiner()) {
2992
18
      NewDRD->setCombinerData(D->getCombinerIn(), D->getCombinerOut());
2993
18
      NewDRD->setCombiner(Combiner);
2994
18
      if (Expr *Init = D->getInitializer()) {
2995
0
        NewDRD->setInitializerData(D->getInitOrig(), D->getInitPriv());
2996
0
        NewDRD->setInitializer(Init, D->getInitializerKind());
2997
0
      }
2998
18
    }
2999
18
    (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
3000
18
        /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3001
18
    return NewDRD;
3002
18
  }
3003
100
  Expr *SubstCombiner = nullptr;
3004
100
  Expr *SubstInitializer = nullptr;
3005
100
  // Combiners instantiation sequence.
3006
100
  if (D->getCombiner()) {
3007
100
    SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
3008
100
        /*S=*/nullptr, NewDRD);
3009
100
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3010
100
        cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3011
100
        cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3012
100
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3013
100
        cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3014
100
        cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3015
100
    auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3016
100
    Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3017
100
                                     ThisContext);
3018
100
    SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get();
3019
100
    SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
3020
100
    // Initializers instantiation sequence.
3021
100
    if (D->getInitializer()) {
3022
36
      VarDecl *OmpPrivParm =
3023
36
          SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
3024
36
              /*S=*/nullptr, NewDRD);
3025
36
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3026
36
          cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3027
36
          cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3028
36
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3029
36
          cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3030
36
          cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3031
36
      if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
3032
36
        SubstInitializer =
3033
36
            SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get();
3034
36
      } else {
3035
0
        IsCorrect = IsCorrect && OmpPrivParm->hasInit();
3036
0
      }
3037
36
      SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(
3038
36
          NewDRD, SubstInitializer, OmpPrivParm);
3039
36
    }
3040
100
    IsCorrect =
3041
100
        IsCorrect && SubstCombiner &&
3042
100
        
(98
!D->getInitializer()98
||
3043
98
         
(36
D->getInitializerKind() == OMPDeclareReductionDecl::CallInit36
&&
3044
36
          SubstInitializer) ||
3045
98
         
(0
D->getInitializerKind() != OMPDeclareReductionDecl::CallInit0
&&
3046
0
          !SubstInitializer && !SubstInitializer));
3047
100
  } else {
3048
0
    IsCorrect = false;
3049
0
  }
3050
100
3051
100
  (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD,
3052
100
                                                        IsCorrect);
3053
100
3054
100
  return NewDRD;
3055
100
}
3056
3057
Decl *
3058
30
TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3059
30
  // Instantiate type and check if it is allowed.
3060
30
  const bool RequiresInstantiation =
3061
30
      D->getType()->isDependentType() ||
3062
30
      
D->getType()->isInstantiationDependentType()18
||
3063
30
      
D->getType()->containsUnexpandedParameterPack()18
;
3064
30
  QualType SubstMapperTy;
3065
30
  DeclarationName VN = D->getVarName();
3066
30
  if (RequiresInstantiation) {
3067
12
    SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
3068
12
        D->getLocation(),
3069
12
        ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3070
12
                                           D->getLocation(), VN)));
3071
18
  } else {
3072
18
    SubstMapperTy = D->getType();
3073
18
  }
3074
30
  if (SubstMapperTy.isNull())
3075
0
    return nullptr;
3076
30
  // Create an instantiated copy of mapper.
3077
30
  auto *PrevDeclInScope = D->getPrevDeclInScope();
3078
30
  if (PrevDeclInScope && 
!PrevDeclInScope->isInvalidDecl()4
) {
3079
4
    PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3080
4
        SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3081
4
            ->get<Decl *>());
3082
4
  }
3083
30
  OMPDeclareMapperDecl *NewDMD = SemaRef.ActOnOpenMPDeclareMapperDirectiveStart(
3084
30
      /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3085
30
      VN, D->getAccess(), PrevDeclInScope);
3086
30
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3087
30
  SmallVector<OMPClause *, 6> Clauses;
3088
30
  bool IsCorrect = true;
3089
30
  if (!RequiresInstantiation) {
3090
18
    // Copy the mapper variable.
3091
18
    NewDMD->setMapperVarRef(D->getMapperVarRef());
3092
18
    // Copy map clauses from the original mapper.
3093
18
    for (OMPClause *C : D->clauselists())
3094
18
      Clauses.push_back(C);
3095
18
  } else {
3096
12
    // Instantiate the mapper variable.
3097
12
    DeclarationNameInfo DirName;
3098
12
    SemaRef.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, /*S=*/nullptr,
3099
12
                                (*D->clauselist_begin())->getBeginLoc());
3100
12
    SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3101
12
        NewDMD, /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3102
12
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3103
12
        cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3104
12
        cast<DeclRefExpr>(NewDMD->getMapperVarRef())->getDecl());
3105
12
    auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3106
12
    Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3107
12
                                     ThisContext);
3108
12
    // Instantiate map clauses.
3109
12
    for (OMPClause *C : D->clauselists()) {
3110
12
      auto *OldC = cast<OMPMapClause>(C);
3111
12
      SmallVector<Expr *, 4> NewVars;
3112
12
      for (Expr *OE : OldC->varlists()) {
3113
12
        Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3114
12
        if (!NE) {
3115
0
          IsCorrect = false;
3116
0
          break;
3117
0
        }
3118
12
        NewVars.push_back(NE);
3119
12
      }
3120
12
      if (!IsCorrect)
3121
0
        break;
3122
12
      NestedNameSpecifierLoc NewQualifierLoc =
3123
12
          SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3124
12
                                              TemplateArgs);
3125
12
      CXXScopeSpec SS;
3126
12
      SS.Adopt(NewQualifierLoc);
3127
12
      DeclarationNameInfo NewNameInfo = SemaRef.SubstDeclarationNameInfo(
3128
12
          OldC->getMapperIdInfo(), TemplateArgs);
3129
12
      OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3130
12
                           OldC->getEndLoc());
3131
12
      OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
3132
12
          OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS,
3133
12
          NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(),
3134
12
          OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs);
3135
12
      Clauses.push_back(NewC);
3136
12
    }
3137
12
    SemaRef.EndOpenMPDSABlock(nullptr);
3138
12
  }
3139
30
  (void)SemaRef.ActOnOpenMPDeclareMapperDirectiveEnd(NewDMD, /*S=*/nullptr,
3140
30
                                                     Clauses);
3141
30
  if (!IsCorrect)
3142
0
    return nullptr;
3143
30
  return NewDMD;
3144
30
}
3145
3146
Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3147
0
    OMPCapturedExprDecl * /*D*/) {
3148
0
  llvm_unreachable("Should not be met in templates");
3149
0
}
3150
3151
426k
Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
3152
426k
  return VisitFunctionDecl(D, nullptr);
3153
426k
}
3154
3155
Decl *
3156
266
TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3157
266
  Decl *Inst = VisitFunctionDecl(D, nullptr);
3158
266
  if (Inst && 
!D->getDescribedFunctionTemplate()258
)
3159
1
    Owner->addDecl(Inst);
3160
266
  return Inst;
3161
266
}
3162
3163
1.54M
Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
3164
1.54M
  return VisitCXXMethodDecl(D, nullptr);
3165
1.54M
}
3166
3167
0
Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3168
0
  llvm_unreachable("There are only CXXRecordDecls in C++");
3169
0
}
3170
3171
Decl *
3172
TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3173
39
    ClassTemplateSpecializationDecl *D) {
3174
39
  // As a MS extension, we permit class-scope explicit specialization
3175
39
  // of member class templates.
3176
39
  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3177
39
  assert(ClassTemplate->getDeclContext()->isRecord() &&
3178
39
         D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3179
39
         "can only instantiate an explicit specialization "
3180
39
         "for a member class template");
3181
39
3182
39
  // Lookup the already-instantiated declaration in the instantiation
3183
39
  // of the class template.
3184
39
  ClassTemplateDecl *InstClassTemplate =
3185
39
      cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3186
39
          D->getLocation(), ClassTemplate, TemplateArgs));
3187
39
  if (!InstClassTemplate)
3188
0
    return nullptr;
3189
39
3190
39
  // Substitute into the template arguments of the class template explicit
3191
39
  // specialization.
3192
39
  TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
3193
39
                                        castAs<TemplateSpecializationTypeLoc>();
3194
39
  TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
3195
39
                                            Loc.getRAngleLoc());
3196
39
  SmallVector<TemplateArgumentLoc, 4> ArgLocs;
3197
77
  for (unsigned I = 0; I != Loc.getNumArgs(); 
++I38
)
3198
38
    ArgLocs.push_back(Loc.getArgLoc(I));
3199
39
  if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
3200
39
                    InstTemplateArgs, TemplateArgs))
3201
0
    return nullptr;
3202
39
3203
39
  // Check that the template argument list is well-formed for this
3204
39
  // class template.
3205
39
  SmallVector<TemplateArgument, 4> Converted;
3206
39
  if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
3207
39
                                        D->getLocation(),
3208
39
                                        InstTemplateArgs,
3209
39
                                        false,
3210
39
                                        Converted))
3211
0
    return nullptr;
3212
39
3213
39
  // Figure out where to insert this class template explicit specialization
3214
39
  // in the member template's set of class template explicit specializations.
3215
39
  void *InsertPos = nullptr;
3216
39
  ClassTemplateSpecializationDecl *PrevDecl =
3217
39
      InstClassTemplate->findSpecialization(Converted, InsertPos);
3218
39
3219
39
  // Check whether we've already seen a conflicting instantiation of this
3220
39
  // declaration (for instance, if there was a prior implicit instantiation).
3221
39
  bool Ignored;
3222
39
  if (PrevDecl &&
3223
39
      SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3224
14
                                                     D->getSpecializationKind(),
3225
14
                                                     PrevDecl,
3226
14
                                                     PrevDecl->getSpecializationKind(),
3227
14
                                                     PrevDecl->getPointOfInstantiation(),
3228
14
                                                     Ignored))
3229
2
    return nullptr;
3230
37
3231
37
  // If PrevDecl was a definition and D is also a definition, diagnose.
3232
37
  // This happens in cases like:
3233
37
  //
3234
37
  //   template<typename T, typename U>
3235
37
  //   struct Outer {
3236
37
  //     template<typename X> struct Inner;
3237
37
  //     template<> struct Inner<T> {};
3238
37
  //     template<> struct Inner<U> {};
3239
37
  //   };
3240
37
  //
3241
37
  //   Outer<int, int> outer; // error: the explicit specializations of Inner
3242
37
  //                          // have the same signature.
3243
37
  if (PrevDecl && 
PrevDecl->getDefinition()12
&&
3244
37
      
D->isThisDeclarationADefinition()7
) {
3245
7
    SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3246
7
    SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3247
7
                 diag::note_previous_definition);
3248
7
    return nullptr;
3249
7
  }
3250
30
3251
30
  // Create the class template partial specialization declaration.
3252
30
  ClassTemplateSpecializationDecl *InstD =
3253
30
      ClassTemplateSpecializationDecl::Create(
3254
30
          SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3255
30
          D->getLocation(), InstClassTemplate, Converted, PrevDecl);
3256
30
3257
30
  // Add this partial specialization to the set of class template partial
3258
30
  // specializations.
3259
30
  if (!PrevDecl)
3260
25
    InstClassTemplate->AddSpecialization(InstD, InsertPos);
3261
30
3262
30
  // Substitute the nested name specifier, if any.
3263
30
  if (SubstQualifier(D, InstD))
3264
0
    return nullptr;
3265
30
3266
30
  // Build the canonical type that describes the converted template
3267
30
  // arguments of the class template explicit specialization.
3268
30
  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3269
30
      TemplateName(InstClassTemplate), Converted,
3270
30
      SemaRef.Context.getRecordType(InstD));
3271
30
3272
30
  // Build the fully-sugared type for this class template
3273
30
  // specialization as the user wrote in the specialization
3274
30
  // itself. This means that we'll pretty-print the type retrieved
3275
30
  // from the specialization's declaration the way that the user
3276
30
  // actually wrote the specialization, rather than formatting the
3277
30
  // name based on the "canonical" representation used to store the
3278
30
  // template arguments in the specialization.
3279
30
  TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3280
30
      TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
3281
30
      CanonType);
3282
30
3283
30
  InstD->setAccess(D->getAccess());
3284
30
  InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3285
30
  InstD->setSpecializationKind(D->getSpecializationKind());
3286
30
  InstD->setTypeAsWritten(WrittenTy);
3287
30
  InstD->setExternLoc(D->getExternLoc());
3288
30
  InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3289
30
3290
30
  Owner->addDecl(InstD);
3291
30
3292
30
  // Instantiate the members of the class-scope explicit specialization eagerly.
3293
30
  // We don't have support for lazy instantiation of an explicit specialization
3294
30
  // yet, and MSVC eagerly instantiates in this case.
3295
30
  // FIXME: This is wrong in standard C++.
3296
30
  if (D->isThisDeclarationADefinition() &&
3297
30
      SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3298
18
                               TSK_ImplicitInstantiation,
3299
18
                               /*Complain=*/true))
3300
0
    return nullptr;
3301
30
3302
30
  return InstD;
3303
30
}
3304
3305
Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3306
55
    VarTemplateSpecializationDecl *D) {
3307
55
3308
55
  TemplateArgumentListInfo VarTemplateArgsInfo;
3309
55
  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3310
55
  assert(VarTemplate &&
3311
55
         "A template specialization without specialized template?");
3312
55
3313
55
  VarTemplateDecl *InstVarTemplate =
3314
55
      cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
3315
55
          D->getLocation(), VarTemplate, TemplateArgs));
3316
55
  if (!InstVarTemplate)
3317
0
    return nullptr;
3318
55
3319
55
  // Substitute the current template arguments.
3320
55
  const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
3321
55
  VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
3322
55
  VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
3323
55
3324
55
  if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
3325
55
                    TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
3326
0
    return nullptr;
3327
55
3328
55
  // Check that the template argument list is well-formed for this template.
3329
55
  SmallVector<TemplateArgument, 4> Converted;
3330
55
  if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3331
55
                                        VarTemplateArgsInfo, false, Converted))
3332
0
    return nullptr;
3333
55
3334
55
  // Check whether we've already seen a declaration of this specialization.
3335
55
  void *InsertPos = nullptr;
3336
55
  VarTemplateSpecializationDecl *PrevDecl =
3337
55
      InstVarTemplate->findSpecialization(Converted, InsertPos);
3338
55
3339
55
  // Check whether we've already seen a conflicting instantiation of this
3340
55
  // declaration (for instance, if there was a prior implicit instantiation).
3341
55
  bool Ignored;
3342
55
  if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
3343
10
                      D->getLocation(), D->getSpecializationKind(), PrevDecl,
3344
10
                      PrevDecl->getSpecializationKind(),
3345
10
                      PrevDecl->getPointOfInstantiation(), Ignored))
3346
0
    return nullptr;
3347
55
3348
55
  return VisitVarTemplateSpecializationDecl(
3349
55
      InstVarTemplate, D, InsertPos, VarTemplateArgsInfo, Converted, PrevDecl);
3350
55
}
3351
3352
Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3353
    VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
3354
    const TemplateArgumentListInfo &TemplateArgsInfo,
3355
    ArrayRef<TemplateArgument> Converted,
3356
1.07k
    VarTemplateSpecializationDecl *PrevDecl) {
3357
1.07k
3358
1.07k
  // Do substitution on the type of the declaration
3359
1.07k
  TypeSourceInfo *DI =
3360
1.07k
      SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3361
1.07k
                        D->getTypeSpecStartLoc(), D->getDeclName());
3362
1.07k
  if (!DI)
3363
0
    return nullptr;
3364
1.07k
3365
1.07k
  if (DI->getType()->isFunctionType()) {
3366
0
    SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3367
0
        << D->isStaticDataMember() << DI->getType();
3368
0
    return nullptr;
3369
0
  }
3370
1.07k
3371
1.07k
  // Build the instantiated declaration
3372
1.07k
  VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3373
1.07k
      SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3374
1.07k
      VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
3375
1.07k
  Var->setTemplateArgsInfo(TemplateArgsInfo);
3376
1.07k
  if (InsertPos)
3377
944
    VarTemplate->AddSpecialization(Var, InsertPos);
3378
1.07k
3379
1.07k
  // Substitute the nested name specifier, if any.
3380
1.07k
  if (SubstQualifier(D, Var))
3381
0
    return nullptr;
3382
1.07k
3383
1.07k
  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
3384
1.07k
                                     StartingScope, false, PrevDecl);
3385
1.07k
3386
1.07k
  return Var;
3387
1.07k
}
3388
3389
0
Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3390
0
  llvm_unreachable("@defs is not supported in Objective-C++");
3391
0
}
3392
3393
0
Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3394
0
  // FIXME: We need to be able to instantiate FriendTemplateDecls.
3395
0
  unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3396
0
                                               DiagnosticsEngine::Error,
3397
0
                                               "cannot instantiate %0 yet");
3398
0
  SemaRef.Diag(D->getLocation(), DiagID)
3399
0
    << D->getDeclKindName();
3400
0
3401
0
  return nullptr;
3402
0
}
3403
3404
0
Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
3405
0
  llvm_unreachable("Concept definitions cannot reside inside a template");
3406
0
}
3407
3408
0
Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
3409
0
  llvm_unreachable("Unexpected decl");
3410
0
}
3411
3412
Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
3413
858k
                      const MultiLevelTemplateArgumentList &TemplateArgs) {
3414
858k
  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3415
858k
  if (D->isInvalidDecl())
3416
18
    return nullptr;
3417
858k
3418
858k
  return Instantiator.Visit(D);
3419
858k
}
3420
3421
/// Instantiates a nested template parameter list in the current
3422
/// instantiation context.
3423
///
3424
/// \param L The parameter list to instantiate
3425
///
3426
/// \returns NULL if there was an error
3427
TemplateParameterList *
3428
356k
TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
3429
356k
  // Get errors for all the parameters before bailing out.
3430
356k
  bool Invalid = false;
3431
356k
3432
356k
  unsigned N = L->size();
3433
356k
  typedef SmallVector<NamedDecl *, 8> ParamVector;
3434
356k
  ParamVector Params;
3435
356k
  Params.reserve(N);
3436
557k
  for (auto &P : *L) {
3437
557k
    NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
3438
557k
    Params.push_back(D);
3439
557k
    Invalid = Invalid || !D || 
D->isInvalidDecl()557k
;
3440
557k
  }
3441
356k
3442
356k
  // Clean up if we had an error.
3443
356k
  if (Invalid)
3444
9
    return nullptr;
3445
356k
3446
356k
  // Note: we substitute into associated constraints later
3447
356k
  Expr *const UninstantiatedRequiresClause = L->getRequiresClause();
3448
356k
3449
356k
  TemplateParameterList *InstL
3450
356k
    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
3451
356k
                                    L->getLAngleLoc(), Params,
3452
356k
                                    L->getRAngleLoc(),
3453
356k
                                    UninstantiatedRequiresClause);
3454
356k
  return InstL;
3455
356k
}
3456
3457
TemplateParameterList *
3458
Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
3459
26.7k
                          const MultiLevelTemplateArgumentList &TemplateArgs) {
3460
26.7k
  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3461
26.7k
  return Instantiator.SubstTemplateParams(Params);
3462
26.7k
}
3463
3464
/// Instantiate the declaration of a class template partial
3465
/// specialization.
3466
///
3467
/// \param ClassTemplate the (instantiated) class template that is partially
3468
// specialized by the instantiation of \p PartialSpec.
3469
///
3470
/// \param PartialSpec the (uninstantiated) class template partial
3471
/// specialization that we are instantiating.
3472
///
3473
/// \returns The instantiated partial specialization, if successful; otherwise,
3474
/// NULL to indicate an error.
3475
ClassTemplatePartialSpecializationDecl *
3476
TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
3477
                                            ClassTemplateDecl *ClassTemplate,
3478
4.20k
                          ClassTemplatePartialSpecializationDecl *PartialSpec) {
3479
4.20k
  // Create a local instantiation scope for this class template partial
3480
4.20k
  // specialization, which will contain the instantiations of the template
3481
4.20k
  // parameters.
3482
4.20k
  LocalInstantiationScope Scope(SemaRef);
3483
4.20k
3484
4.20k
  // Substitute into the template parameters of the class template partial
3485
4.20k
  // specialization.
3486
4.20k
  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3487
4.20k
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3488
4.20k
  if (!InstParams)
3489
0
    return nullptr;
3490
4.20k
3491
4.20k
  // Substitute into the template arguments of the class template partial
3492
4.20k
  // specialization.
3493
4.20k
  const ASTTemplateArgumentListInfo *TemplArgInfo
3494
4.20k
    = PartialSpec->getTemplateArgsAsWritten();
3495
4.20k
  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3496
4.20k
                                            TemplArgInfo->RAngleLoc);
3497
4.20k
  if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3498
4.20k
                    TemplArgInfo->NumTemplateArgs,
3499
4.20k
                    InstTemplateArgs, TemplateArgs))
3500
0
    return nullptr;
3501
4.20k
3502
4.20k
  // Check that the template argument list is well-formed for this
3503
4.20k
  // class template.
3504
4.20k
  SmallVector<TemplateArgument, 4> Converted;
3505
4.20k
  if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
3506
4.20k
                                        PartialSpec->getLocation(),
3507
4.20k
                                        InstTemplateArgs,
3508
4.20k
                                        false,
3509
4.20k
                                        Converted))
3510
0
    return nullptr;
3511
4.20k
3512
4.20k
  // Check these arguments are valid for a template partial specialization.
3513
4.20k
  if (SemaRef.CheckTemplatePartialSpecializationArgs(
3514
4.20k
          PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
3515
4.20k
          Converted))
3516
5
    return nullptr;
3517
4.20k
3518
4.20k
  // Figure out where to insert this class template partial specialization
3519
4.20k
  // in the member template's set of class template partial specializations.
3520
4.20k
  void *InsertPos = nullptr;
3521
4.20k
  ClassTemplateSpecializationDecl *PrevDecl
3522
4.20k
    = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
3523
4.20k
3524
4.20k
  // Build the canonical type that describes the converted template
3525
4.20k
  // arguments of the class template partial specialization.
3526
4.20k
  QualType CanonType
3527
4.20k
    = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
3528
4.20k
                                                    Converted);
3529
4.20k
3530
4.20k
  // Build the fully-sugared type for this class template
3531
4.20k
  // specialization as the user wrote in the specialization
3532
4.20k
  // itself. This means that we'll pretty-print the type retrieved
3533
4.20k
  // from the specialization's declaration the way that the user
3534
4.20k
  // actually wrote the specialization, rather than formatting the
3535
4.20k
  // name based on the "canonical" representation used to store the
3536
4.20k
  // template arguments in the specialization.
3537
4.20k
  TypeSourceInfo *WrittenTy
3538
4.20k
    = SemaRef.Context.getTemplateSpecializationTypeInfo(
3539
4.20k
                                                    TemplateName(ClassTemplate),
3540
4.20k
                                                    PartialSpec->getLocation(),
3541
4.20k
                                                    InstTemplateArgs,
3542
4.20k
                                                    CanonType);
3543
4.20k
3544
4.20k
  if (PrevDecl) {
3545
1
    // We've already seen a partial specialization with the same template
3546
1
    // parameters and template arguments. This can happen, for example, when
3547
1
    // substituting the outer template arguments ends up causing two
3548
1
    // class template partial specializations of a member class template
3549
1
    // to have identical forms, e.g.,
3550
1
    //
3551
1
    //   template<typename T, typename U>
3552
1
    //   struct Outer {
3553
1
    //     template<typename X, typename Y> struct Inner;
3554
1
    //     template<typename Y> struct Inner<T, Y>;
3555
1
    //     template<typename Y> struct Inner<U, Y>;
3556
1
    //   };
3557
1
    //
3558
1
    //   Outer<int, int> outer; // error: the partial specializations of Inner
3559
1
    //                          // have the same signature.
3560
1
    SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
3561
1
      << WrittenTy->getType();
3562
1
    SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
3563
1
      << SemaRef.Context.getTypeDeclType(PrevDecl);
3564
1
    return nullptr;
3565
1
  }
3566
4.20k
3567
4.20k
3568
4.20k
  // Create the class template partial specialization declaration.
3569
4.20k
  ClassTemplatePartialSpecializationDecl *InstPartialSpec =
3570
4.20k
      ClassTemplatePartialSpecializationDecl::Create(
3571
4.20k
          SemaRef.Context, PartialSpec->getTagKind(), Owner,
3572
4.20k
          PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
3573
4.20k
          ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr);
3574
4.20k
  // Substitute the nested name specifier, if any.
3575
4.20k
  if (SubstQualifier(PartialSpec, InstPartialSpec))
3576
0
    return nullptr;
3577
4.20k
3578
4.20k
  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3579
4.20k
  InstPartialSpec->setTypeAsWritten(WrittenTy);
3580
4.20k
3581
4.20k
  // Check the completed partial specialization.
3582
4.20k
  SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3583
4.20k
3584
4.20k
  // Add this partial specialization to the set of class template partial
3585
4.20k
  // specializations.
3586
4.20k
  ClassTemplate->AddPartialSpecialization(InstPartialSpec,
3587
4.20k
                                          /*InsertPos=*/nullptr);
3588
4.20k
  return InstPartialSpec;
3589
4.20k
}
3590
3591
/// Instantiate the declaration of a variable template partial
3592
/// specialization.
3593
///
3594
/// \param VarTemplate the (instantiated) variable template that is partially
3595
/// specialized by the instantiation of \p PartialSpec.
3596
///
3597
/// \param PartialSpec the (uninstantiated) variable template partial
3598
/// specialization that we are instantiating.
3599
///
3600
/// \returns The instantiated partial specialization, if successful; otherwise,
3601
/// NULL to indicate an error.
3602
VarTemplatePartialSpecializationDecl *
3603
TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
3604
    VarTemplateDecl *VarTemplate,
3605
48
    VarTemplatePartialSpecializationDecl *PartialSpec) {
3606
48
  // Create a local instantiation scope for this variable template partial
3607
48
  // specialization, which will contain the instantiations of the template
3608
48
  // parameters.
3609
48
  LocalInstantiationScope Scope(SemaRef);
3610
48
3611
48
  // Substitute into the template parameters of the variable template partial
3612
48
  // specialization.
3613
48
  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3614
48
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3615
48
  if (!InstParams)
3616
0
    return nullptr;
3617
48
3618
48
  // Substitute into the template arguments of the variable template partial
3619
48
  // specialization.
3620
48
  const ASTTemplateArgumentListInfo *TemplArgInfo
3621
48
    = PartialSpec->getTemplateArgsAsWritten();
3622
48
  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3623
48
                                            TemplArgInfo->RAngleLoc);
3624
48
  if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3625
48
                    TemplArgInfo->NumTemplateArgs,
3626
48
                    InstTemplateArgs, TemplateArgs))
3627
0
    return nullptr;
3628
48
3629
48
  // Check that the template argument list is well-formed for this
3630
48
  // class template.
3631
48
  SmallVector<TemplateArgument, 4> Converted;
3632
48
  if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
3633
48
                                        InstTemplateArgs, false, Converted))
3634
1
    return nullptr;
3635
47
3636
47
  // Check these arguments are valid for a template partial specialization.
3637
47
  if (SemaRef.CheckTemplatePartialSpecializationArgs(
3638
47
          PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
3639
47
          Converted))
3640
0
    return nullptr;
3641
47
3642
47
  // Figure out where to insert this variable template partial specialization
3643
47
  // in the member template's set of variable template partial specializations.
3644
47
  void *InsertPos = nullptr;
3645
47
  VarTemplateSpecializationDecl *PrevDecl =
3646
47
      VarTemplate->findPartialSpecialization(Converted, InsertPos);
3647
47
3648
47
  // Build the canonical type that describes the converted template
3649
47
  // arguments of the variable template partial specialization.
3650
47
  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3651
47
      TemplateName(VarTemplate), Converted);
3652
47
3653
47
  // Build the fully-sugared type for this variable template
3654
47
  // specialization as the user wrote in the specialization
3655
47
  // itself. This means that we'll pretty-print the type retrieved
3656
47
  // from the specialization's declaration the way that the user
3657
47
  // actually wrote the specialization, rather than formatting the
3658
47
  // name based on the "canonical" representation used to store the
3659
47
  // template arguments in the specialization.
3660
47
  TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3661
47
      TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
3662
47
      CanonType);
3663
47
3664
47
  if (PrevDecl) {
3665
0
    // We've already seen a partial specialization with the same template
3666
0
    // parameters and template arguments. This can happen, for example, when
3667
0
    // substituting the outer template arguments ends up causing two
3668
0
    // variable template partial specializations of a member variable template
3669
0
    // to have identical forms, e.g.,
3670
0
    //
3671
0
    //   template<typename T, typename U>
3672
0
    //   struct Outer {
3673
0
    //     template<typename X, typename Y> pair<X,Y> p;
3674
0
    //     template<typename Y> pair<T, Y> p;
3675
0
    //     template<typename Y> pair<U, Y> p;
3676
0
    //   };
3677
0
    //
3678
0
    //   Outer<int, int> outer; // error: the partial specializations of Inner
3679
0
    //                          // have the same signature.
3680
0
    SemaRef.Diag(PartialSpec->getLocation(),
3681
0
                 diag::err_var_partial_spec_redeclared)
3682
0
        << WrittenTy->getType();
3683
0
    SemaRef.Diag(PrevDecl->getLocation(),
3684
0
                 diag::note_var_prev_partial_spec_here);
3685
0
    return nullptr;
3686
0
  }
3687
47
3688
47
  // Do substitution on the type of the declaration
3689
47
  TypeSourceInfo *DI = SemaRef.SubstType(
3690
47
      PartialSpec->getTypeSourceInfo(), TemplateArgs,
3691
47
      PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
3692
47
  if (!DI)
3693
0
    return nullptr;
3694
47
3695
47
  if (DI->getType()->isFunctionType()) {
3696
0
    SemaRef.Diag(PartialSpec->getLocation(),
3697
0
                 diag::err_variable_instantiates_to_function)
3698
0
        << PartialSpec->isStaticDataMember() << DI->getType();
3699
0
    return nullptr;
3700
0
  }
3701
47
3702
47
  // Create the variable template partial specialization declaration.
3703
47
  VarTemplatePartialSpecializationDecl *InstPartialSpec =
3704
47
      VarTemplatePartialSpecializationDecl::Create(
3705
47
          SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
3706
47
          PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
3707
47
          DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
3708
47
3709
47
  // Substitute the nested name specifier, if any.
3710
47
  if (SubstQualifier(PartialSpec, InstPartialSpec))
3711
0
    return nullptr;
3712
47
3713
47
  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3714
47
  InstPartialSpec->setTypeAsWritten(WrittenTy);
3715
47
3716
47
  // Check the completed partial specialization.
3717
47
  SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3718
47
3719
47
  // Add this partial specialization to the set of variable template partial
3720
47
  // specializations. The instantiation of the initializer is not necessary.
3721
47
  VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
3722
47
3723
47
  SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
3724
47
                                     LateAttrs, Owner, StartingScope);
3725
47
3726
47
  return InstPartialSpec;
3727
47
}
3728
3729
TypeSourceInfo*
3730
TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
3731
1.93M
                              SmallVectorImpl<ParmVarDecl *> &Params) {
3732
1.93M
  TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
3733
1.93M
  assert(OldTInfo && "substituting function without type source info");
3734
1.93M
  assert(Params.empty() && "parameter vector is non-empty at start");
3735
1.93M
3736
1.93M
  CXXRecordDecl *ThisContext = nullptr;
3737
1.93M
  Qualifiers ThisTypeQuals;
3738
1.93M
  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
3739
1.70M
    ThisContext = cast<CXXRecordDecl>(Owner);
3740
1.70M
    ThisTypeQuals = Method->getMethodQualifiers();
3741
1.70M
  }
3742
1.93M
3743
1.93M
  TypeSourceInfo *NewTInfo
3744
1.93M
    = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
3745
1.93M
                                    D->getTypeSpecStartLoc(),
3746
1.93M
                                    D->getDeclName(),
3747
1.93M
                                    ThisContext, ThisTypeQuals);
3748
1.93M
  if (!NewTInfo)
3749
83.0k
    return nullptr;
3750
1.85M
3751
1.85M
  TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
3752
1.85M
  if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
3753
1.85M
    if (NewTInfo != OldTInfo) {
3754
1.55M
      // Get parameters from the new type info.
3755
1.55M
      TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
3756
1.55M
      FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
3757
1.55M
      unsigned NewIdx = 0;
3758
1.55M
      for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
3759
3.77M
           OldIdx != NumOldParams; 
++OldIdx2.21M
) {
3760
2.21M
        ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
3761
2.21M
        LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
3762
2.21M
3763
2.21M
        Optional<unsigned> NumArgumentsInExpansion;
3764
2.21M
        if (OldParam->isParameterPack())
3765
37.3k
          NumArgumentsInExpansion =
3766
37.3k
              SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3767
37.3k
                                                 TemplateArgs);
3768
2.21M
        if (!NumArgumentsInExpansion) {
3769
2.20M
          // Simple case: normal parameter, or a parameter pack that's
3770
2.20M
          // instantiated to a (still-dependent) parameter pack.
3771
2.20M
          ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3772
2.20M
          Params.push_back(NewParam);
3773
2.20M
          Scope->InstantiatedLocal(OldParam, NewParam);
3774
2.20M
        } else {
3775
12.5k
          // Parameter pack expansion: make the instantiation an argument pack.
3776
12.5k
          Scope->MakeInstantiatedLocalArgPack(OldParam);
3777
29.1k
          for (unsigned I = 0; I != *NumArgumentsInExpansion; 
++I16.5k
) {
3778
16.5k
            ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3779
16.5k
            Params.push_back(NewParam);
3780
16.5k
            Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3781
16.5k
          }
3782
12.5k
        }
3783
2.21M
      }
3784
1.55M
    } else {
3785
302k
      // The function type itself was not dependent and therefore no
3786
302k
      // substitution occurred. However, we still need to instantiate
3787
302k
      // the function parameters themselves.
3788
302k
      const FunctionProtoType *OldProto =
3789
302k
          cast<FunctionProtoType>(OldProtoLoc.getType());
3790
302k
      for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3791
302k
           
++i2
) {
3792
2
        ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
3793
2
        if (!OldParam) {
3794
2
          Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
3795
2
              D, D->getLocation(), OldProto->getParamType(i)));
3796
2
          continue;
3797
2
        }
3798
0
3799
0
        ParmVarDecl *Parm =
3800
0
            cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
3801
0
        if (!Parm)
3802
0
          return nullptr;
3803
0
        Params.push_back(Parm);
3804
0
      }
3805
302k
    }
3806
1.85M
  } else {
3807
62
    // If the type of this function, after ignoring parentheses, is not
3808
62
    // *directly* a function type, then we're instantiating a function that
3809
62
    // was declared via a typedef or with attributes, e.g.,
3810
62
    //
3811
62
    //   typedef int functype(int, int);
3812
62
    //   functype func;
3813
62
    //   int __cdecl meth(int, int);
3814
62
    //
3815
62
    // In this case, we'll just go instantiate the ParmVarDecls that we
3816
62
    // synthesized in the method declaration.
3817
62
    SmallVector<QualType, 4> ParamTypes;
3818
62
    Sema::ExtParameterInfoBuilder ExtParamInfos;
3819
62
    if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
3820
62
                               TemplateArgs, ParamTypes, &Params,
3821
62
                               ExtParamInfos))
3822
0
      return nullptr;
3823
1.85M
  }
3824
1.85M
3825
1.85M
  return NewTInfo;
3826
1.85M
}
3827
3828
/// Introduce the instantiated function parameters into the local
3829
/// instantiation scope, and set the parameter names to those used
3830
/// in the template.
3831
static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
3832
                                             const FunctionDecl *PatternDecl,
3833
                                             LocalInstantiationScope &Scope,
3834
329k
                           const MultiLevelTemplateArgumentList &TemplateArgs) {
3835
329k
  unsigned FParamIdx = 0;
3836
652k
  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; 
++I323k
) {
3837
323k
    const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3838
323k
    if (!PatternParam->isParameterPack()) {
3839
315k
      // Simple case: not a parameter pack.
3840
315k
      assert(FParamIdx < Function->getNumParams());
3841
315k
      ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3842
315k
      FunctionParam->setDeclName(PatternParam->getDeclName());
3843
315k
      // If the parameter's type is not dependent, update it to match the type
3844
315k
      // in the pattern. They can differ in top-level cv-qualifiers, and we want
3845
315k
      // the pattern's type here. If the type is dependent, they can't differ,
3846
315k
      // per core issue 1668. Substitute into the type from the pattern, in case
3847
315k
      // it's instantiation-dependent.
3848
315k
      // FIXME: Updating the type to work around this is at best fragile.
3849
315k
      if (!PatternDecl->getType()->isDependentType()) {
3850
27.6k
        QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3851
27.6k
                                 FunctionParam->getLocation(),
3852
27.6k
                                 FunctionParam->getDeclName());
3853
27.6k
        if (T.isNull())
3854
0
          return true;
3855
27.6k
        FunctionParam->setType(T);
3856
27.6k
      }
3857
315k
3858
315k
      Scope.InstantiatedLocal(PatternParam, FunctionParam);
3859
315k
      ++FParamIdx;
3860
315k
      continue;
3861
7.67k
    }
3862
7.67k
3863
7.67k
    // Expand the parameter pack.
3864
7.67k
    Scope.MakeInstantiatedLocalArgPack(PatternParam);
3865
7.67k
    Optional<unsigned> NumArgumentsInExpansion
3866
7.67k
      = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
3867
7.67k
    if (NumArgumentsInExpansion) {
3868
7.67k
      QualType PatternType =
3869
7.67k
          PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
3870
18.7k
      for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; 
++Arg11.0k
) {
3871
11.0k
        ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3872
11.0k
        FunctionParam->setDeclName(PatternParam->getDeclName());
3873
11.0k
        if (!PatternDecl->getType()->isDependentType()) {
3874
6
          Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3875
6
          QualType T = S.SubstType(PatternType, TemplateArgs,
3876
6
                                   FunctionParam->getLocation(),
3877
6
                                   FunctionParam->getDeclName());
3878
6
          if (T.isNull())
3879
0
            return true;
3880
6
          FunctionParam->setType(T);
3881
6
        }
3882
11.0k
3883
11.0k
        Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3884
11.0k
        ++FParamIdx;
3885
11.0k
      }
3886
7.67k
    }
3887
7.67k
  }
3888
329k
3889
329k
  return false;
3890
329k
}
3891
3892
void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3893
8.47k
                                    FunctionDecl *Decl) {
3894
8.47k
  const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3895
8.47k
  if (Proto->getExceptionSpecType() != EST_Uninstantiated)
3896
0
    return;
3897
8.47k
3898
8.47k
  InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3899
8.47k
                             InstantiatingTemplate::ExceptionSpecification());
3900
8.47k
  if (Inst.isInvalid()) {
3901
0
    // We hit the instantiation depth limit. Clear the exception specification
3902
0
    // so that our callers don't have to cope with EST_Uninstantiated.
3903
0
    UpdateExceptionSpec(Decl, EST_None);
3904
0
    return;
3905
0
  }
3906
8.47k
  if (Inst.isAlreadyInstantiating()) {
3907
10
    // This exception specification indirectly depends on itself. Reject.
3908
10
    // FIXME: Corresponding rule in the standard?
3909
10
    Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
3910
10
    UpdateExceptionSpec(Decl, EST_None);
3911
10
    return;
3912
10
  }
3913
8.46k
3914
8.46k
  // Enter the scope of this instantiation. We don't use
3915
8.46k
  // PushDeclContext because we don't have a scope.
3916
8.46k
  Sema::ContextRAII savedContext(*this, Decl);
3917
8.46k
  LocalInstantiationScope Scope(*this);
3918
8.46k
3919
8.46k
  MultiLevelTemplateArgumentList TemplateArgs =
3920
8.46k
    getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
3921
8.46k
3922
8.46k
  FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3923
8.46k
  if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3924
8.46k
                                       TemplateArgs)) {
3925
0
    UpdateExceptionSpec(Decl, EST_None);
3926
0
    return;
3927
0
  }
3928
8.46k
3929
8.46k
  SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
3930
8.46k
                     TemplateArgs);
3931
8.46k
}
3932
3933
/// Initializes the common fields of an instantiation function
3934
/// declaration (New) from the corresponding fields of its template (Tmpl).
3935
///
3936
/// \returns true if there was an error
3937
bool
3938
TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
3939
1.85M
                                                    FunctionDecl *Tmpl) {
3940
1.85M
  if (Tmpl->isDeleted())
3941
21.5k
    New->setDeletedAsWritten();
3942
1.85M
3943
1.85M
  New->setImplicit(Tmpl->isImplicit());
3944
1.85M
3945
1.85M
  // Forward the mangling number from the template to the instantiated decl.
3946
1.85M
  SemaRef.Context.setManglingNumber(New,
3947
1.85M
                                    SemaRef.Context.getManglingNumber(Tmpl));
3948
1.85M
3949
1.85M
  // If we are performing substituting explicitly-specified template arguments
3950
1.85M
  // or deduced template arguments into a function template and we reach this
3951
1.85M
  // point, we are now past the point where SFINAE applies and have committed
3952
1.85M
  // to keeping the new function template specialization. We therefore
3953
1.85M
  // convert the active template instantiation for the function template
3954
1.85M
  // into a template instantiation for this specific function template
3955
1.85M
  // specialization, which is not a SFINAE context, so that we diagnose any
3956
1.85M
  // further errors in the declaration itself.
3957
1.85M
  typedef Sema::CodeSynthesisContext ActiveInstType;
3958
1.85M
  ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
3959
1.85M
  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3960
1.85M
      
ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution1.85M
) {
3961
296k
    if (FunctionTemplateDecl *FunTmpl
3962
296k
          = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
3963
296k
      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
3964
296k
             "Deduction from the wrong function template?");
3965
296k
      (void) FunTmpl;
3966
296k
      atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
3967
296k
      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
3968
296k
      ActiveInst.Entity = New;
3969
296k
      atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
3970
296k
    }
3971
296k
  }
3972
1.85M
3973
1.85M
  const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3974
1.85M
  assert(Proto && "Function template without prototype?");
3975
1.85M
3976
1.85M
  if (Proto->hasExceptionSpec() || 
Proto->getNoReturnAttr()1.38M
) {
3977
473k
    FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3978
473k
3979
473k
    // DR1330: In C++11, defer instantiation of a non-trivial
3980
473k
    // exception specification.
3981
473k
    // DR1484: Local classes and their members are instantiated along with the
3982
473k
    // containing function.
3983
473k
    if (SemaRef.getLangOpts().CPlusPlus11 &&
3984
473k
        
EPI.ExceptionSpec.Type != EST_None471k
&&
3985
473k
        
EPI.ExceptionSpec.Type != EST_DynamicNone471k
&&
3986
473k
        
EPI.ExceptionSpec.Type != EST_BasicNoexcept471k
&&
3987
473k
        
!Tmpl->isLexicallyWithinFunctionOrMethod()59.3k
) {
3988
59.3k
      FunctionDecl *ExceptionSpecTemplate = Tmpl;
3989
59.3k
      if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
3990
4.68k
        ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
3991
59.3k
      ExceptionSpecificationType NewEST = EST_Uninstantiated;
3992
59.3k
      if (EPI.ExceptionSpec.Type == EST_Unevaluated)
3993
0
        NewEST = EST_Unevaluated;
3994
59.3k
3995
59.3k
      // Mark the function has having an uninstantiated exception specification.
3996
59.3k
      const FunctionProtoType *NewProto
3997
59.3k
        = New->getType()->getAs<FunctionProtoType>();
3998
59.3k
      assert(NewProto && "Template instantiation without function prototype?");
3999
59.3k
      EPI = NewProto->getExtProtoInfo();
4000
59.3k
      EPI.ExceptionSpec.Type = NewEST;
4001
59.3k
      EPI.ExceptionSpec.SourceDecl = New;
4002
59.3k
      EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4003
59.3k
      New->setType(SemaRef.Context.getFunctionType(
4004
59.3k
          NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4005
413k
    } else {
4006
413k
      Sema::ContextRAII SwitchContext(SemaRef, New);
4007
413k
      SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4008
413k
    }
4009
473k
  }
4010
1.85M
4011
1.85M
  // Get the definition. Leaves the variable unchanged if undefined.
4012
1.85M
  const FunctionDecl *Definition = Tmpl;
4013
1.85M
  Tmpl->isDefined(Definition);
4014
1.85M
4015
1.85M
  SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4016
1.85M
                           LateAttrs, StartingScope);
4017
1.85M
4018
1.85M
  return false;
4019
1.85M
}
4020
4021
/// Initializes common fields of an instantiated method
4022
/// declaration (New) from the corresponding fields of its template
4023
/// (Tmpl).
4024
///
4025
/// \returns true if there was an error
4026
bool
4027
TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
4028
1.65M
                                                  CXXMethodDecl *Tmpl) {
4029
1.65M
  if (InitFunctionInstantiation(New, Tmpl))
4030
0
    return true;
4031
1.65M
4032
1.65M
  if (isa<CXXDestructorDecl>(New) && 
SemaRef.getLangOpts().CPlusPlus1130.0k
)
4033
29.4k
    SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4034
1.65M
4035
1.65M
  New->setAccess(Tmpl->getAccess());
4036
1.65M
  if (Tmpl->isVirtualAsWritten())
4037
46.7k
    New->setVirtualAsWritten(true);
4038
1.65M
4039
1.65M
  // FIXME: New needs a pointer to Tmpl
4040
1.65M
  return false;
4041
1.65M
}
4042
4043
/// Instantiate (or find existing instantiation of) a function template with a
4044
/// given set of template arguments.
4045
///
4046
/// Usually this should not be used, and template argument deduction should be
4047
/// used in its place.
4048
FunctionDecl *
4049
Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
4050
                                     const TemplateArgumentList *Args,
4051
612
                                     SourceLocation Loc) {
4052
612
  FunctionDecl *FD = FTD->getTemplatedDecl();
4053
612
4054
612
  sema::TemplateDeductionInfo Info(Loc);
4055
612
  InstantiatingTemplate Inst(
4056
612
      *this, Loc, FTD, Args->asArray(),
4057
612
      CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
4058
612
  if (Inst.isInvalid())
4059
0
    return nullptr;
4060
612
4061
612
  ContextRAII SavedContext(*this, FD);
4062
612
  MultiLevelTemplateArgumentList MArgs(*Args);
4063
612
4064
612
  return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4065
612
}
4066
4067
/// In the MS ABI, we need to instantiate default arguments of dllexported
4068
/// default constructors along with the constructor definition. This allows IR
4069
/// gen to emit a constructor closure which calls the default constructor with
4070
/// its default arguments.
4071
static void InstantiateDefaultCtorDefaultArgs(Sema &S,
4072
174
                                              CXXConstructorDecl *Ctor) {
4073
174
  assert(S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4074
174
         Ctor->isDefaultConstructor());
4075
174
  unsigned NumParams = Ctor->getNumParams();
4076
174
  if (NumParams == 0)
4077
162
    return;
4078
12
  DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
4079
12
  if (!Attr)
4080
0
    return;
4081
24
  
for (unsigned I = 0; 12
I != NumParams;
++I12
) {
4082
12
    (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
4083
12
                                   Ctor->getParamDecl(I));
4084
12
    S.DiscardCleanupsInEvaluationContext();
4085
12
  }
4086
12
}
4087
4088
/// Instantiate the definition of the given function from its
4089
/// template.
4090
///
4091
/// \param PointOfInstantiation the point at which the instantiation was
4092
/// required. Note that this is not precisely a "point of instantiation"
4093
/// for the function, but it's close.
4094
///
4095
/// \param Function the already-instantiated declaration of a
4096
/// function template specialization or member function of a class template
4097
/// specialization.
4098
///
4099
/// \param Recursive if true, recursively instantiates any functions that
4100
/// are required by this instantiation.
4101
///
4102
/// \param DefinitionRequired if true, then we are performing an explicit
4103
/// instantiation where the body of the function is required. Complain if
4104
/// there is no such body.
4105
void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4106
                                         FunctionDecl *Function,
4107
                                         bool Recursive,
4108
                                         bool DefinitionRequired,
4109
343k
                                         bool AtEndOfTU) {
4110
343k
  if (Function->isInvalidDecl() || 
Function->isDefined()343k
||
4111
343k
      
isa<CXXDeductionGuideDecl>(Function)329k
)
4112
13.8k
    return;
4113
329k
4114
329k
  // Never instantiate an explicit specialization except if it is a class scope
4115
329k
  // explicit specialization.
4116
329k
  TemplateSpecializationKind TSK =
4117
329k
      Function->getTemplateSpecializationKindForInstantiation();
4118
329k
  if (TSK == TSK_ExplicitSpecialization)
4119
0
    return;
4120
329k
4121
329k
  // Find the function body that we'll be substituting.
4122
329k
  const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
4123
329k
  assert(PatternDecl && "instantiating a non-template");
4124
329k
4125
329k
  const FunctionDecl *PatternDef = PatternDecl->getDefinition();
4126
329k
  Stmt *Pattern = nullptr;
4127
329k
  if (PatternDef) {
4128
320k
    Pattern = PatternDef->getBody(PatternDef);
4129
320k
    PatternDecl = PatternDef;
4130
320k
    if (PatternDef->willHaveBody())
4131
121
      PatternDef = nullptr;
4132
320k
  }
4133
329k
4134
329k
  // FIXME: We need to track the instantiation stack in order to know which
4135
329k
  // definitions should be visible within this instantiation.
4136
329k
  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
4137
329k
                                Function->getInstantiatedFromMemberFunction(),
4138
329k
                                     PatternDecl, PatternDef, TSK,
4139
329k
                                     /*Complain*/DefinitionRequired)) {
4140
8.94k
    if (DefinitionRequired)
4141
7
      Function->setInvalidDecl();
4142
8.93k
    else if (TSK == TSK_ExplicitInstantiationDefinition) {
4143
20
      // Try again at the end of the translation unit (at which point a
4144
20
      // definition will be required).
4145
20
      assert(!Recursive);
4146
20
      Function->setInstantiationIsPending(true);
4147
20
      PendingInstantiations.push_back(
4148
20
        std::make_pair(Function, PointOfInstantiation));
4149
8.91k
    } else if (TSK == TSK_ImplicitInstantiation) {
4150
8.89k
      if (AtEndOfTU && 
!getDiagnostics().hasErrorOccurred()8.75k
&&
4151
8.89k
          
!getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())2.27k
) {
4152
1.98k
        Diag(PointOfInstantiation, diag::warn_func_template_missing)
4153
1.98k
          << Function;
4154
1.98k
        Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4155
1.98k
        if (getLangOpts().CPlusPlus11)
4156
1.93k
          Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
4157
1.93k
            << Function;
4158
1.98k
      }
4159
8.89k
    }
4160
8.94k
4161
8.94k
    return;
4162
8.94k
  }
4163
320k
4164
320k
  // Postpone late parsed template instantiations.
4165
320k
  if (PatternDecl->isLateTemplateParsed() &&
4166
320k
      
!LateTemplateParser364
) {
4167
79
    Function->setInstantiationIsPending(true);
4168
79
    LateParsedInstantiations.push_back(
4169
79
        std::make_pair(Function, PointOfInstantiation));
4170
79
    return;
4171
79
  }
4172
320k
4173
320k
  llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
4174
0
    std::string Name;
4175
0
    llvm::raw_string_ostream OS(Name);
4176
0
    Function->getNameForDiagnostic(OS, getPrintingPolicy(),
4177
0
                                   /*Qualified=*/true);
4178
0
    return Name;
4179
0
  });
4180
320k
4181
320k
  // If we're performing recursive template instantiation, create our own
4182
320k
  // queue of pending implicit instantiations that we will instantiate later,
4183
320k
  // while we're still within our own instantiation context.
4184
320k
  // This has to happen before LateTemplateParser below is called, so that
4185
320k
  // it marks vtables used in late parsed templates as used.
4186
320k
  GlobalEagerInstantiationScope GlobalInstantiations(*this,
4187
320k
                                                     /*Enabled=*/Recursive);
4188
320k
  LocalEagerInstantiationScope LocalInstantiations(*this);
4189
320k
4190
320k
  // Call the LateTemplateParser callback if there is a need to late parse
4191
320k
  // a templated function definition.
4192
320k
  if (!Pattern && 
PatternDecl->isLateTemplateParsed()292
&&
4193
320k
      
LateTemplateParser285
) {
4194
285
    // FIXME: Optimize to allow individual templates to be deserialized.
4195
285
    if (PatternDecl->isFromASTFile())
4196
32
      ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
4197
285
4198
285
    auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
4199
285
    assert(LPTIter != LateParsedTemplateMap.end() &&
4200
285
           "missing LateParsedTemplate");
4201
285
    LateTemplateParser(OpaqueParser, *LPTIter->second);
4202
285
    Pattern = PatternDecl->getBody(PatternDecl);
4203
285
  }
4204
320k
4205
320k
  // Note, we should never try to instantiate a deleted function template.
4206
320k
  assert((Pattern || PatternDecl->isDefaulted() ||
4207
320k
          PatternDecl->hasSkippedBody()) &&
4208
320k
         "unexpected kind of function template definition");
4209
320k
4210
320k
  // C++1y [temp.explicit]p10:
4211
320k
  //   Except for inline functions, declarations with types deduced from their
4212
320k
  //   initializer or return value, and class template specializations, other
4213
320k
  //   explicit instantiation declarations have the effect of suppressing the
4214
320k
  //   implicit instantiation of the entity to which they refer.
4215
320k
  if (TSK == TSK_ExplicitInstantiationDeclaration &&
4216
320k
      
!PatternDecl->isInlined()1.16k
&&
4217
320k
      
!PatternDecl->getReturnType()->getContainedAutoType()9
)
4218
0
    return;
4219
320k
4220
320k
  if (PatternDecl->isInlined()) {
4221
279k
    // Function, and all later redeclarations of it (from imported modules,
4222
279k
    // for instance), are now implicitly inline.
4223
279k
    for (auto *D = Function->getMostRecentDecl(); /**/;
4224
279k
         
D = D->getPreviousDecl()24
) {
4225
279k
      D->setImplicitlyInline();
4226
279k
      if (D == Function)
4227
279k
        break;
4228
279k
    }
4229
279k
  }
4230
320k
4231
320k
  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
4232
320k
  if (Inst.isInvalid() || 
Inst.isAlreadyInstantiating()320k
)
4233
44
    return;
4234
320k
  PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
4235
320k
                                      "instantiating function definition");
4236
320k
4237
320k
  // The instantiation is visible here, even if it was first declared in an
4238
320k
  // unimported module.
4239
320k
  Function->setVisibleDespiteOwningModule();
4240
320k
4241
320k
  // Copy the inner loc start from the pattern.
4242
320k
  Function->setInnerLocStart(PatternDecl->getInnerLocStart());
4243
320k
4244
320k
  EnterExpressionEvaluationContext EvalContext(
4245
320k
      *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4246
320k
4247
320k
  // Introduce a new scope where local variable instantiations will be
4248
320k
  // recorded, unless we're actually a member function within a local
4249
320k
  // class, in which case we need to merge our results with the parent
4250
320k
  // scope (of the enclosing function).
4251
320k
  bool MergeWithParentScope = false;
4252
320k
  if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
4253
245k
    MergeWithParentScope = Rec->isLocalClass();
4254
320k
4255
320k
  LocalInstantiationScope Scope(*this, MergeWithParentScope);
4256
320k
4257
320k
  if (PatternDecl->isDefaulted())
4258
2
    SetDeclDefaulted(Function, PatternDecl->getLocation());
4259
320k
  else {
4260
320k
    MultiLevelTemplateArgumentList TemplateArgs =
4261
320k
      getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
4262
320k
4263
320k
    // Substitute into the qualifier; we can get a substitution failure here
4264
320k
    // through evil use of alias templates.
4265
320k
    // FIXME: Is CurContext correct for this? Should we go to the (instantiation
4266
320k
    // of the) lexical context of the pattern?
4267
320k
    SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
4268
320k
4269
320k
    ActOnStartOfFunctionDef(nullptr, Function);
4270
320k
4271
320k
    // Enter the scope of this instantiation. We don't use
4272
320k
    // PushDeclContext because we don't have a scope.
4273
320k
    Sema::ContextRAII savedContext(*this, Function);
4274
320k
4275
320k
    if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
4276
320k
                                         TemplateArgs))
4277
0
      return;
4278
320k
4279
320k
    StmtResult Body;
4280
320k
    if (PatternDecl->hasSkippedBody()) {
4281
5
      ActOnSkippedFunctionBody(Function);
4282
5
      Body = nullptr;
4283
320k
    } else {
4284
320k
      if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
4285
44.9k
        // If this is a constructor, instantiate the member initializers.
4286
44.9k
        InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
4287
44.9k
                                   TemplateArgs);
4288
44.9k
4289
44.9k
        // If this is an MS ABI dllexport default constructor, instantiate any
4290
44.9k
        // default arguments.
4291
44.9k
        if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4292
44.9k
            
Ctor->isDefaultConstructor()186
) {
4293
174
          InstantiateDefaultCtorDefaultArgs(*this, Ctor);
4294
174
        }
4295
44.9k
      }
4296
320k
4297
320k
      // Instantiate the function body.
4298
320k
      Body = SubstStmt(Pattern, TemplateArgs);
4299
320k
4300
320k
      if (Body.isInvalid())
4301
2.23k
        Function->setInvalidDecl();
4302
320k
    }
4303
320k
    // FIXME: finishing the function body while in an expression evaluation
4304
320k
    // context seems wrong. Investigate more.
4305
320k
    ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
4306
320k
4307
320k
    PerformDependentDiagnostics(PatternDecl, TemplateArgs);
4308
320k
4309
320k
    if (auto *Listener = getASTMutationListener())
4310
106
      Listener->FunctionDefinitionInstantiated(Function);
4311
320k
4312
320k
    savedContext.pop();
4313
320k
  }
4314
320k
4315
320k
  DeclGroupRef DG(Function);
4316
320k
  Consumer.HandleTopLevelDecl(DG);
4317
320k
4318
320k
  // This class may have local implicit instantiations that need to be
4319
320k
  // instantiation within this scope.
4320
320k
  LocalInstantiations.perform();
4321
320k
  Scope.Exit();
4322
320k
  GlobalInstantiations.perform();
4323
320k
}
4324
4325
VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
4326
    VarTemplateDecl *VarTemplate, VarDecl *FromVar,
4327
    const TemplateArgumentList &TemplateArgList,
4328
    const TemplateArgumentListInfo &TemplateArgsInfo,
4329
    SmallVectorImpl<TemplateArgument> &Converted,
4330
    SourceLocation PointOfInstantiation, void *InsertPos,
4331
    LateInstantiatedAttrVec *LateAttrs,
4332
899
    LocalInstantiationScope *StartingScope) {
4333
899
  if (FromVar->isInvalidDecl())
4334
0
    return nullptr;
4335
899
4336
899
  InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
4337
899
  if (Inst.isInvalid())
4338
0
    return nullptr;
4339
899
4340
899
  MultiLevelTemplateArgumentList TemplateArgLists;
4341
899
  TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
4342
899
4343
899
  // Instantiate the first declaration of the variable template: for a partial
4344
899
  // specialization of a static data member template, the first declaration may
4345
899
  // or may not be the declaration in the class; if it's in the class, we want
4346
899
  // to instantiate a member in the class (a declaration), and if it's outside,
4347
899
  // we want to instantiate a definition.
4348
899
  //
4349
899
  // If we're instantiating an explicitly-specialized member template or member
4350
899
  // partial specialization, don't do this. The member specialization completely
4351
899
  // replaces the original declaration in this case.
4352
899
  bool IsMemberSpec = false;
4353
899
  if (VarTemplatePartialSpecializationDecl *PartialSpec =
4354
155
          dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
4355
155
    IsMemberSpec = PartialSpec->isMemberSpecialization();
4356
744
  else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
4357
744
    IsMemberSpec = FromTemplate->isMemberSpecialization();
4358
899
  if (!IsMemberSpec)
4359
880
    FromVar = FromVar->getFirstDecl();
4360
899
4361
899
  MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
4362
899
  TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
4363
899
                                        MultiLevelList);
4364
899
4365
899
  // TODO: Set LateAttrs and StartingScope ...
4366
899
4367
899
  return cast_or_null<VarTemplateSpecializationDecl>(
4368
899
      Instantiator.VisitVarTemplateSpecializationDecl(
4369
899
          VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
4370
899
}
4371
4372
/// Instantiates a variable template specialization by completing it
4373
/// with appropriate type information and initializer.
4374
VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
4375
    VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
4376
449
    const MultiLevelTemplateArgumentList &TemplateArgs) {
4377
449
  assert(PatternDecl->isThisDeclarationADefinition() &&
4378
449
         "don't have a definition to instantiate from");
4379
449
4380
449
  // Do substitution on the type of the declaration
4381
449
  TypeSourceInfo *DI =
4382
449
      SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
4383
449
                PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
4384
449
  if (!DI)
4385
0
    return nullptr;
4386
449
4387
449
  // Update the type of this variable template specialization.
4388
449
  VarSpec->setType(DI->getType());
4389
449
4390
449
  // Convert the declaration into a definition now.
4391
449
  VarSpec->setCompleteDefinition();
4392
449
4393
449
  // Instantiate the initializer.
4394
449
  InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
4395
449
4396
449
  return VarSpec;
4397
449
}
4398
4399
/// BuildVariableInstantiation - Used after a new variable has been created.
4400
/// Sets basic variable data and decides whether to postpone the
4401
/// variable instantiation.
4402
void Sema::BuildVariableInstantiation(
4403
    VarDecl *NewVar, VarDecl *OldVar,
4404
    const MultiLevelTemplateArgumentList &TemplateArgs,
4405
    LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
4406
    LocalInstantiationScope *StartingScope,
4407
    bool InstantiatingVarTemplate,
4408
352k
    VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
4409
352k
  // Instantiating a partial specialization to produce a partial
4410
352k
  // specialization.
4411
352k
  bool InstantiatingVarTemplatePartialSpec =
4412
352k
      isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
4413
352k
      
isa<VarTemplatePartialSpecializationDecl>(NewVar)230
;
4414
352k
  // Instantiating from a variable template (or partial specialization) to
4415
352k
  // produce a variable template specialization.
4416
352k
  bool InstantiatingSpecFromTemplate =
4417
352k
      isa<VarTemplateSpecializationDecl>(NewVar) &&
4418
352k
      
(1.12k
OldVar->getDescribedVarTemplate()1.12k
||
4419
1.12k
       
isa<VarTemplatePartialSpecializationDecl>(OldVar)285
);
4420
352k
4421
352k
  // If we are instantiating a local extern declaration, the
4422
352k
  // instantiation belongs lexically to the containing function.
4423
352k
  // If we are instantiating a static data member defined
4424
352k
  // out-of-line, the instantiation will have the same lexical
4425
352k
  // context (which will be a namespace scope) as the template.
4426
352k
  if (OldVar->isLocalExternDecl()) {
4427
78
    NewVar->setLocalExternDecl();
4428
78
    NewVar->setLexicalDeclContext(Owner);
4429
352k
  } else if (OldVar->isOutOfLine())
4430
6.64k
    NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
4431
352k
  NewVar->setTSCSpec(OldVar->getTSCSpec());
4432
352k
  NewVar->setInitStyle(OldVar->getInitStyle());
4433
352k
  NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
4434
352k
  NewVar->setObjCForDecl(OldVar->isObjCForDecl());
4435
352k
  NewVar->setConstexpr(OldVar->isConstexpr());
4436
352k
  NewVar->setInitCapture(OldVar->isInitCapture());
4437
352k
  NewVar->setPreviousDeclInSameBlockScope(
4438
352k
      OldVar->isPreviousDeclInSameBlockScope());
4439
352k
  NewVar->setAccess(OldVar->getAccess());
4440
352k
4441
352k
  if (!OldVar->isStaticDataMember()) {
4442
159k
    if (OldVar->isUsed(false))
4443
27.0k
      NewVar->setIsUsed();
4444
159k
    NewVar->setReferenced(OldVar->isReferenced());
4445
159k
  }
4446
352k
4447
352k
  InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
4448
352k
4449
352k
  LookupResult Previous(
4450
352k
      *this, NewVar->getDeclName(), NewVar->getLocation(),
4451
352k
      NewVar->isLocalExternDecl() ? 
Sema::LookupRedeclarationWithLinkage78
4452
352k
                                  : 
Sema::LookupOrdinaryName352k
,
4453
352k
      NewVar->isLocalExternDecl() ? 
Sema::ForExternalRedeclaration78
4454
352k
                                  : 
forRedeclarationInCurContext()352k
);
4455
352k
4456
352k
  if (NewVar->isLocalExternDecl() && 
OldVar->getPreviousDecl()78
&&
4457
352k
      
(28
!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext()28
||
4458
28
       
OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext()25
)) {
4459
24
    // We have a previous declaration. Use that one, so we merge with the
4460
24
    // right type.
4461
24
    if (NamedDecl *NewPrev = FindInstantiatedDecl(
4462
24
            NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
4463
24
      Previous.addDecl(NewPrev);
4464
352k
  } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
4465
352k
             
OldVar->hasLinkage()351k
) {
4466
192k
    LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
4467
192k
  } else 
if (160k
PrevDeclForVarTemplateSpecialization160k
) {
4468
10
    Previous.addDecl(PrevDeclForVarTemplateSpecialization);
4469
10
  }
4470
352k
  CheckVariableDeclaration(NewVar, Previous);
4471
352k
4472
352k
  if (!InstantiatingVarTemplate) {
4473
352k
    NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
4474
352k
    if (!NewVar->isLocalExternDecl() || 
!NewVar->getPreviousDecl()78
)
4475
352k
      NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
4476
352k
  }
4477
352k
4478
352k
  if (!OldVar->isOutOfLine()) {
4479
345k
    if (NewVar->getDeclContext()->isFunctionOrMethod())
4480
158k
      CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
4481
345k
  }
4482
352k
4483
352k
  // Link instantiations of static data members back to the template from
4484
352k
  // which they were instantiated.
4485
352k
  //
4486
352k
  // Don't do this when instantiating a template (we link the template itself
4487
352k
  // back in that case) nor when instantiating a static data member template
4488
352k
  // (that's not a member specialization).
4489
352k
  if (NewVar->isStaticDataMember() && 
!InstantiatingVarTemplate192k
&&
4490
352k
      
!InstantiatingSpecFromTemplate192k
)
4491
192k
    NewVar->setInstantiationOfStaticDataMember(OldVar,
4492
192k
                                               TSK_ImplicitInstantiation);
4493
352k
4494
352k
  // If the pattern is an (in-class) explicit specialization, then the result
4495
352k
  // is also an explicit specialization.
4496
352k
  if (VarTemplateSpecializationDecl *OldVTSD =
4497
285
          dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
4498
285
    if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
4499
285
        !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
4500
55
      cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
4501
55
          TSK_ExplicitSpecialization);
4502
285
  }
4503
352k
4504
352k
  // Forward the mangling number from the template to the instantiated decl.
4505
352k
  Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
4506
352k
  Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
4507
352k
4508
352k
  // Figure out whether to eagerly instantiate the initializer.
4509
352k
  if (InstantiatingVarTemplate || 
InstantiatingVarTemplatePartialSpec352k
) {
4510
227
    // We're producing a template. Don't instantiate the initializer yet.
4511
352k
  } else if (NewVar->getType()->isUndeducedType()) {
4512
2.24k
    // We need the type to complete the declaration of the variable.
4513
2.24k
    InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4514
349k
  } else if (InstantiatingSpecFromTemplate ||
4515
349k
             
(348k
OldVar->isInline()348k
&&
OldVar->isThisDeclarationADefinition()135
&&
4516
348k
              
!NewVar->isThisDeclarationADefinition()135
)) {
4517
1.12k
    // Delay instantiation of the initializer for variable template
4518
1.12k
    // specializations or inline static data members until a definition of the
4519
1.12k
    // variable is needed.
4520
348k
  } else {
4521
348k
    InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4522
348k
  }
4523
352k
4524
352k
  // Diagnose unused local variables with dependent types, where the diagnostic
4525
352k
  // will have been deferred.
4526
352k
  if (!NewVar->isInvalidDecl() &&
4527
352k
      
NewVar->getDeclContext()->isFunctionOrMethod()352k
&&
4528
352k
      
OldVar->getType()->isDependentType()158k
)
4529
71.2k
    DiagnoseUnusedDecl(NewVar);
4530
352k
}
4531
4532
/// Instantiate the initializer of a variable.
4533
void Sema::InstantiateVariableInitializer(
4534
    VarDecl *Var, VarDecl *OldVar,
4535
351k
    const MultiLevelTemplateArgumentList &TemplateArgs) {
4536
351k
  if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4537
193
    L->VariableDefinitionInstantiated(Var);
4538
351k
4539
351k
  // We propagate the 'inline' flag with the initializer, because it
4540
351k
  // would otherwise imply that the variable is a definition for a
4541
351k
  // non-static data member.
4542
351k
  if (OldVar->isInlineSpecified())
4543
53
    Var->setInlineSpecified();
4544
351k
  else if (OldVar->isInline())
4545
85
    Var->setImplicitlyInline();
4546
351k
4547
351k
  if (OldVar->getInit()) {
4548
319k
    EnterExpressionEvaluationContext Evaluated(
4549
319k
        *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
4550
319k
4551
319k
    // Instantiate the initializer.
4552
319k
    ExprResult Init;
4553
319k
4554
319k
    {
4555
319k
      ContextRAII SwitchContext(*this, Var->getDeclContext());
4556
319k
      Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
4557
319k
                              OldVar->getInitStyle() == VarDecl::CallInit);
4558
319k
    }
4559
319k
4560
319k
    if (!Init.isInvalid()) {
4561
319k
      Expr *InitExpr = Init.get();
4562
319k
4563
319k
      if (Var->hasAttr<DLLImportAttr>() &&
4564
319k
          
(40
!InitExpr40
||
4565
40
           
!InitExpr->isConstantInitializer(getASTContext(), false)36
)) {
4566
12
        // Do not dynamically initialize dllimport variables.
4567
318k
      } else if (InitExpr) {
4568
318k
        bool DirectInit = OldVar->isDirectInit();
4569
318k
        AddInitializerToDecl(Var, InitExpr, DirectInit);
4570
318k
      } else
4571
799
        ActOnUninitializedDecl(Var);
4572
319k
    } else {
4573
114
      // FIXME: Not too happy about invalidating the declaration
4574
114
      // because of a bogus initializer.
4575
114
      Var->setInvalidDecl();
4576
114
    }
4577
319k
  } else {
4578
32.7k
    // `inline` variables are a definition and declaration all in one; we won't
4579
32.7k
    // pick up an initializer from anywhere else.
4580
32.7k
    if (Var->isStaticDataMember() && 
!Var->isInline()11.4k
) {
4581
11.4k
      if (!Var->isOutOfLine())
4582
5.32k
        return;
4583
6.12k
4584
6.12k
      // If the declaration inside the class had an initializer, don't add
4585
6.12k
      // another one to the out-of-line definition.
4586
6.12k
      if (OldVar->getFirstDecl()->hasInit())
4587
6.02k
        return;
4588
21.4k
    }
4589
21.4k
4590
21.4k
    // We'll add an initializer to a for-range declaration later.
4591
21.4k
    if (Var->isCXXForRangeDecl() || 
Var->isObjCForDecl()21.3k
)
4592
91
      return;
4593
21.3k
4594
21.3k
    ActOnUninitializedDecl(Var);
4595
21.3k
  }
4596
351k
4597
351k
  
if (340k
getLangOpts().CUDA340k
)
4598
78
    checkAllowedCUDAInitializer(Var);
4599
340k
}
4600
4601
/// Instantiate the definition of the given variable from its
4602
/// template.
4603
///
4604
/// \param PointOfInstantiation the point at which the instantiation was
4605
/// required. Note that this is not precisely a "point of instantiation"
4606
/// for the variable, but it's close.
4607
///
4608
/// \param Var the already-instantiated declaration of a templated variable.
4609
///
4610
/// \param Recursive if true, recursively instantiates any functions that
4611
/// are required by this instantiation.
4612
///
4613
/// \param DefinitionRequired if true, then we are performing an explicit
4614
/// instantiation where a definition of the variable is required. Complain
4615
/// if there is no such definition.
4616
void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
4617
                                         VarDecl *Var, bool Recursive,
4618
1.05M
                                      bool DefinitionRequired, bool AtEndOfTU) {
4619
1.05M
  if (Var->isInvalidDecl())
4620
0
    return;
4621
1.05M
4622
1.05M
  // Never instantiate an explicitly-specialized entity.
4623
1.05M
  TemplateSpecializationKind TSK =
4624
1.05M
      Var->getTemplateSpecializationKindForInstantiation();
4625
1.05M
  if (TSK == TSK_ExplicitSpecialization)
4626
0
    return;
4627
1.05M
4628
1.05M
  // Find the pattern and the arguments to substitute into it.
4629
1.05M
  VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
4630
1.05M
  assert(PatternDecl && "no pattern for templated variable");
4631
1.05M
  MultiLevelTemplateArgumentList TemplateArgs =
4632
1.05M
      getTemplateInstantiationArgs(Var);
4633
1.05M
4634
1.05M
  VarTemplateSpecializationDecl *VarSpec =
4635
1.05M
      dyn_cast<VarTemplateSpecializationDecl>(Var);
4636
1.05M
  if (VarSpec) {
4637
1.11k
    // If this is a variable template specialization, make sure that it is
4638
1.11k
    // non-dependent.
4639
1.11k
    bool InstantiationDependent = false;
4640
1.11k
    assert(!TemplateSpecializationType::anyDependentTemplateArguments(
4641
1.11k
               VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
4642
1.11k
           "Only instantiate variable template specializations that are "
4643
1.11k
           "not type-dependent");
4644
1.11k
    (void)InstantiationDependent;
4645
1.11k
4646
1.11k
    // If this is a static data member template, there might be an
4647
1.11k
    // uninstantiated initializer on the declaration. If so, instantiate
4648
1.11k
    // it now.
4649
1.11k
    //
4650
1.11k
    // FIXME: This largely duplicates what we would do below. The difference
4651
1.11k
    // is that along this path we may instantiate an initializer from an
4652
1.11k
    // in-class declaration of the template and instantiate the definition
4653
1.11k
    // from a separate out-of-class definition.
4654
1.11k
    if (PatternDecl->isStaticDataMember() &&
4655
1.11k
        
(PatternDecl = PatternDecl->getFirstDecl())->hasInit()362
&&
4656
1.11k
        
!Var->hasInit()238
) {
4657
195
      // FIXME: Factor out the duplicated instantiation context setup/tear down
4658
195
      // code here.
4659
195
      InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4660
195
      if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4661
0
        return;
4662
195
      PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
4663
195
                                          "instantiating variable initializer");
4664
195
4665
195
      // The instantiation is visible here, even if it was first declared in an
4666
195
      // unimported module.
4667
195
      Var->setVisibleDespiteOwningModule();