Coverage Report

Created: 2022-07-16 07:03

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