Coverage Report

Created: 2020-02-18 08:44

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