Coverage Report

Created: 2020-09-22 08:39

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