Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Sema/SemaLambda.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
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
//
9
//  This file implements semantic analysis for C++ lambda expressions.
10
//
11
//===----------------------------------------------------------------------===//
12
#include "clang/Sema/DeclSpec.h"
13
#include "TypeLocBuilder.h"
14
#include "clang/AST/ASTLambda.h"
15
#include "clang/AST/ExprCXX.h"
16
#include "clang/Basic/TargetInfo.h"
17
#include "clang/Sema/Initialization.h"
18
#include "clang/Sema/Lookup.h"
19
#include "clang/Sema/Scope.h"
20
#include "clang/Sema/ScopeInfo.h"
21
#include "clang/Sema/SemaInternal.h"
22
#include "clang/Sema/SemaLambda.h"
23
#include "llvm/ADT/STLExtras.h"
24
using namespace clang;
25
using namespace sema;
26
27
/// Examines the FunctionScopeInfo stack to determine the nearest
28
/// enclosing lambda (to the current lambda) that is 'capture-ready' for
29
/// the variable referenced in the current lambda (i.e. \p VarToCapture).
30
/// If successful, returns the index into Sema's FunctionScopeInfo stack
31
/// of the capture-ready lambda's LambdaScopeInfo.
32
///
33
/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
34
/// lambda - is on top) to determine the index of the nearest enclosing/outer
35
/// lambda that is ready to capture the \p VarToCapture being referenced in
36
/// the current lambda.
37
/// As we climb down the stack, we want the index of the first such lambda -
38
/// that is the lambda with the highest index that is 'capture-ready'.
39
///
40
/// A lambda 'L' is capture-ready for 'V' (var or this) if:
41
///  - its enclosing context is non-dependent
42
///  - and if the chain of lambdas between L and the lambda in which
43
///    V is potentially used (i.e. the lambda at the top of the scope info
44
///    stack), can all capture or have already captured V.
45
/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
46
///
47
/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
48
/// for whether it is 'capture-capable' (see
49
/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
50
/// capture.
51
///
52
/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
53
///  LambdaScopeInfo inherits from).  The current/deepest/innermost lambda
54
///  is at the top of the stack and has the highest index.
55
/// \param VarToCapture - the variable to capture.  If NULL, capture 'this'.
56
///
57
/// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
58
/// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
59
/// which is capture-ready.  If the return value evaluates to 'false' then
60
/// no lambda is capture-ready for \p VarToCapture.
61
62
static inline Optional<unsigned>
63
getStackIndexOfNearestEnclosingCaptureReadyLambda(
64
    ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
65
767
    VarDecl *VarToCapture) {
66
767
  // Label failure to capture.
67
767
  const Optional<unsigned> NoLambdaIsCaptureReady;
68
767
69
767
  // Ignore all inner captured regions.
70
767
  unsigned CurScopeIndex = FunctionScopes.size() - 1;
71
772
  while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
72
772
                                  FunctionScopes[CurScopeIndex]))
73
5
    --CurScopeIndex;
74
767
  assert(
75
767
      isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
76
767
      "The function on the top of sema's function-info stack must be a lambda");
77
767
78
767
  // If VarToCapture is null, we are attempting to capture 'this'.
79
767
  const bool IsCapturingThis = !VarToCapture;
80
767
  const bool IsCapturingVariable = !IsCapturingThis;
81
767
82
767
  // Start with the current lambda at the top of the stack (highest index).
83
767
  DeclContext *EnclosingDC =
84
767
      cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
85
767
86
1.07k
  do {
87
1.07k
    const clang::sema::LambdaScopeInfo *LSI =
88
1.07k
        cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
89
1.07k
    // IF we have climbed down to an intervening enclosing lambda that contains
90
1.07k
    // the variable declaration - it obviously can/must not capture the
91
1.07k
    // variable.
92
1.07k
    // Since its enclosing DC is dependent, all the lambdas between it and the
93
1.07k
    // innermost nested lambda are dependent (otherwise we wouldn't have
94
1.07k
    // arrived here) - so we don't yet have a lambda that can capture the
95
1.07k
    // variable.
96
1.07k
    if (IsCapturingVariable &&
97
1.07k
        
VarToCapture->getDeclContext()->Equals(EnclosingDC)998
)
98
124
      return NoLambdaIsCaptureReady;
99
954
100
954
    // For an enclosing lambda to be capture ready for an entity, all
101
954
    // intervening lambda's have to be able to capture that entity. If even
102
954
    // one of the intervening lambda's is not capable of capturing the entity
103
954
    // then no enclosing lambda can ever capture that entity.
104
954
    // For e.g.
105
954
    // const int x = 10;
106
954
    // [=](auto a) {    #1
107
954
    //   [](auto b) {   #2 <-- an intervening lambda that can never capture 'x'
108
954
    //    [=](auto c) { #3
109
954
    //       f(x, c);  <-- can not lead to x's speculative capture by #1 or #2
110
954
    //    }; }; };
111
954
    // If they do not have a default implicit capture, check to see
112
954
    // if the entity has already been explicitly captured.
113
954
    // If even a single dependent enclosing lambda lacks the capability
114
954
    // to ever capture this variable, there is no further enclosing
115
954
    // non-dependent lambda that can capture this variable.
116
954
    if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
117
170
      if (IsCapturingVariable && 
!LSI->isCaptured(VarToCapture)144
)
118
91
        return NoLambdaIsCaptureReady;
119
79
      if (IsCapturingThis && 
!LSI->isCXXThisCaptured()26
)
120
24
        return NoLambdaIsCaptureReady;
121
839
    }
122
839
    EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
123
839
124
839
    assert(CurScopeIndex);
125
839
    --CurScopeIndex;
126
839
  } while (!EnclosingDC->isTranslationUnit() &&
127
839
           EnclosingDC->isDependentContext() &&
128
839
           
isLambdaCallOperator(EnclosingDC)634
);
129
767
130
767
  assert(CurScopeIndex < (FunctionScopes.size() - 1));
131
528
  // If the enclosingDC is not dependent, then the immediately nested lambda
132
528
  // (one index above) is capture-ready.
133
528
  if (!EnclosingDC->isDependentContext())
134
205
    return CurScopeIndex + 1;
135
323
  return NoLambdaIsCaptureReady;
136
323
}
137
138
/// Examines the FunctionScopeInfo stack to determine the nearest
139
/// enclosing lambda (to the current lambda) that is 'capture-capable' for
140
/// the variable referenced in the current lambda (i.e. \p VarToCapture).
141
/// If successful, returns the index into Sema's FunctionScopeInfo stack
142
/// of the capture-capable lambda's LambdaScopeInfo.
143
///
144
/// Given the current stack of lambdas being processed by Sema and
145
/// the variable of interest, to identify the nearest enclosing lambda (to the
146
/// current lambda at the top of the stack) that can truly capture
147
/// a variable, it has to have the following two properties:
148
///  a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
149
///     - climb down the stack (i.e. starting from the innermost and examining
150
///       each outer lambda step by step) checking if each enclosing
151
///       lambda can either implicitly or explicitly capture the variable.
152
///       Record the first such lambda that is enclosed in a non-dependent
153
///       context. If no such lambda currently exists return failure.
154
///  b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
155
///  capture the variable by checking all its enclosing lambdas:
156
///     - check if all outer lambdas enclosing the 'capture-ready' lambda
157
///       identified above in 'a' can also capture the variable (this is done
158
///       via tryCaptureVariable for variables and CheckCXXThisCapture for
159
///       'this' by passing in the index of the Lambda identified in step 'a')
160
///
161
/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
162
/// LambdaScopeInfo inherits from).  The current/deepest/innermost lambda
163
/// is at the top of the stack.
164
///
165
/// \param VarToCapture - the variable to capture.  If NULL, capture 'this'.
166
///
167
///
168
/// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
169
/// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
170
/// which is capture-capable.  If the return value evaluates to 'false' then
171
/// no lambda is capture-capable for \p VarToCapture.
172
173
Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
174
    ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
175
767
    VarDecl *VarToCapture, Sema &S) {
176
767
177
767
  const Optional<unsigned> NoLambdaIsCaptureCapable;
178
767
179
767
  const Optional<unsigned> OptionalStackIndex =
180
767
      getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
181
767
                                                        VarToCapture);
182
767
  if (!OptionalStackIndex)
183
562
    return NoLambdaIsCaptureCapable;
184
205
185
205
  const unsigned IndexOfCaptureReadyLambda = OptionalStackIndex.getValue();
186
205
  assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
187
205
          S.getCurGenericLambda()) &&
188
205
         "The capture ready lambda for a potential capture can only be the "
189
205
         "current lambda if it is a generic lambda");
190
205
191
205
  const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
192
205
      cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
193
205
194
205
  // If VarToCapture is null, we are attempting to capture 'this'
195
205
  const bool IsCapturingThis = !VarToCapture;
196
205
  const bool IsCapturingVariable = !IsCapturingThis;
197
205
198
205
  if (IsCapturingVariable) {
199
195
    // Check if the capture-ready lambda can truly capture the variable, by
200
195
    // checking whether all enclosing lambdas of the capture-ready lambda allow
201
195
    // the capture - i.e. make sure it is capture-capable.
202
195
    QualType CaptureType, DeclRefType;
203
195
    const bool CanCaptureVariable =
204
195
        !S.tryCaptureVariable(VarToCapture,
205
195
                              /*ExprVarIsUsedInLoc*/ SourceLocation(),
206
195
                              clang::Sema::TryCapture_Implicit,
207
195
                              /*EllipsisLoc*/ SourceLocation(),
208
195
                              /*BuildAndDiagnose*/ false, CaptureType,
209
195
                              DeclRefType, &IndexOfCaptureReadyLambda);
210
195
    if (!CanCaptureVariable)
211
14
      return NoLambdaIsCaptureCapable;
212
10
  } else {
213
10
    // Check if the capture-ready lambda can truly capture 'this' by checking
214
10
    // whether all enclosing lambdas of the capture-ready lambda can capture
215
10
    // 'this'.
216
10
    const bool CanCaptureThis =
217
10
        !S.CheckCXXThisCapture(
218
10
             CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
219
10
             /*Explicit*/ false, /*BuildAndDiagnose*/ false,
220
10
             &IndexOfCaptureReadyLambda);
221
10
    if (!CanCaptureThis)
222
2
      return NoLambdaIsCaptureCapable;
223
189
  }
224
189
  return IndexOfCaptureReadyLambda;
225
189
}
226
227
static inline TemplateParameterList *
228
13.5k
getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
229
13.5k
  if (!LSI->GLTemplateParameterList && 
!LSI->TemplateParams.empty()11.0k
) {
230
1.01k
    LSI->GLTemplateParameterList = TemplateParameterList::Create(
231
1.01k
        SemaRef.Context,
232
1.01k
        /*Template kw loc*/ SourceLocation(),
233
1.01k
        /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(),
234
1.01k
        LSI->TemplateParams,
235
1.01k
        /*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(),
236
1.01k
        nullptr);
237
1.01k
  }
238
13.5k
  return LSI->GLTemplateParameterList;
239
13.5k
}
240
241
CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
242
                                             TypeSourceInfo *Info,
243
                                             bool KnownDependent,
244
6.75k
                                             LambdaCaptureDefault CaptureDefault) {
245
6.75k
  DeclContext *DC = CurContext;
246
6.76k
  while (!(DC->isFunctionOrMethod() || 
DC->isRecord()644
||
DC->isFileContext()355
))
247
6
    DC = DC->getParent();
248
6.75k
  bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
249
6.75k
                                                               *this);
250
6.75k
  // Start constructing the lambda class.
251
6.75k
  CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
252
6.75k
                                                     IntroducerRange.getBegin(),
253
6.75k
                                                     KnownDependent,
254
6.75k
                                                     IsGenericLambda,
255
6.75k
                                                     CaptureDefault);
256
6.75k
  DC->addDecl(Class);
257
6.75k
258
6.75k
  return Class;
259
6.75k
}
260
261
/// Determine whether the given context is or is enclosed in an inline
262
/// function.
263
1.03M
static bool isInInlineFunction(const DeclContext *DC) {
264
1.16M
  while (!DC->isFileContext()) {
265
139k
    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
266
19.4k
      if (FD->isInlined())
267
10.5k
        return true;
268
129k
269
129k
    DC = DC->getLexicalParent();
270
129k
  }
271
1.03M
272
1.03M
  
return false1.02M
;
273
1.03M
}
274
275
MangleNumberingContext *
276
Sema::getCurrentMangleNumberContext(const DeclContext *DC,
277
1.05M
                                    Decl *&ManglingContextDecl) {
278
1.05M
  // Compute the context for allocating mangling numbers in the current
279
1.05M
  // expression, if the ABI requires them.
280
1.05M
  ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
281
1.05M
282
1.05M
  enum ContextKind {
283
1.05M
    Normal,
284
1.05M
    DefaultArgument,
285
1.05M
    DataMember,
286
1.05M
    StaticDataMember,
287
1.05M
    InlineVariable,
288
1.05M
    VariableTemplate
289
1.05M
  } Kind = Normal;
290
1.05M
291
1.05M
  // Default arguments of member function parameters that appear in a class
292
1.05M
  // definition, as well as the initializers of data members, receive special
293
1.05M
  // treatment. Identify them.
294
1.05M
  if (ManglingContextDecl) {
295
1.23k
    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
296
159
      if (const DeclContext *LexicalDC
297
129
          = Param->getDeclContext()->getLexicalParent())
298
129
        if (LexicalDC->isRecord())
299
96
          Kind = DefaultArgument;
300
1.07k
    } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
301
950
      if (Var->getDeclContext()->isRecord())
302
21
        Kind = StaticDataMember;
303
929
      else if (Var->getMostRecentDecl()->isInline())
304
2
        Kind = InlineVariable;
305
927
      else if (Var->getDescribedVarTemplate())
306
7
        Kind = VariableTemplate;
307
920
      else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
308
5
        if (!VTS->isExplicitSpecialization())
309
5
          Kind = VariableTemplate;
310
5
      }
311
950
    } else 
if (128
isa<FieldDecl>(ManglingContextDecl)128
) {
312
128
      Kind = DataMember;
313
128
    }
314
1.23k
  }
315
1.05M
316
1.05M
  // Itanium ABI [5.1.7]:
317
1.05M
  //   In the following contexts [...] the one-definition rule requires closure
318
1.05M
  //   types in different translation units to "correspond":
319
1.05M
  bool IsInNonspecializedTemplate =
320
1.05M
      inTemplateInstantiation() || 
CurContext->isDependentContext()1.05M
;
321
1.05M
  switch (Kind) {
322
1.05M
  case Normal: {
323
1.05M
    //  -- the bodies of non-exported nonspecialized template functions
324
1.05M
    //  -- the bodies of inline functions
325
1.05M
    if ((IsInNonspecializedTemplate &&
326
1.05M
         
!(18.3k
ManglingContextDecl18.3k
&&
isa<ParmVarDecl>(ManglingContextDecl)626
)) ||
327
1.05M
        
isInInlineFunction(CurContext)1.03M
) {
328
28.8k
      ManglingContextDecl = nullptr;
329
30.7k
      while (auto *CD = dyn_cast<CapturedDecl>(DC))
330
1.86k
        DC = CD->getParent();
331
28.8k
      return &Context.getManglingNumberContext(DC);
332
28.8k
    }
333
1.02M
334
1.02M
    ManglingContextDecl = nullptr;
335
1.02M
    return nullptr;
336
1.02M
  }
337
1.02M
338
1.02M
  case StaticDataMember:
339
21
    //  -- the initializers of nonspecialized static members of template classes
340
21
    if (!IsInNonspecializedTemplate) {
341
2
      ManglingContextDecl = nullptr;
342
2
      return nullptr;
343
2
    }
344
19
    // Fall through to get the current context.
345
19
    LLVM_FALLTHROUGH;
346
19
347
257
  case DataMember:
348
257
    //  -- the in-class initializers of class members
349
257
  case DefaultArgument:
350
257
    //  -- default arguments appearing in class definitions
351
257
  case InlineVariable:
352
257
    //  -- the initializers of inline variables
353
257
  case VariableTemplate:
354
257
    //  -- the initializers of templated variables
355
257
    return &ExprEvalContexts.back().getMangleNumberingContext(Context);
356
0
  }
357
0
358
0
  llvm_unreachable("unexpected context");
359
0
}
360
361
MangleNumberingContext &
362
Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext(
363
257
    ASTContext &Ctx) {
364
257
  assert(ManglingContextDecl && "Need to have a context declaration");
365
257
  if (!MangleNumbering)
366
244
    MangleNumbering = Ctx.createMangleNumberingContext();
367
257
  return *MangleNumbering;
368
257
}
369
370
CXXMethodDecl *Sema::startLambdaDefinition(
371
    CXXRecordDecl *Class, SourceRange IntroducerRange,
372
    TypeSourceInfo *MethodTypeInfo, SourceLocation EndLoc,
373
    ArrayRef<ParmVarDecl *> Params, ConstexprSpecKind ConstexprKind,
374
6.75k
    Optional<std::pair<unsigned, Decl *>> Mangling) {
375
6.75k
  QualType MethodType = MethodTypeInfo->getType();
376
6.75k
  TemplateParameterList *TemplateParams =
377
6.75k
            getGenericLambdaTemplateParameterList(getCurLambda(), *this);
378
6.75k
  // If a lambda appears in a dependent context or is a generic lambda (has
379
6.75k
  // template parameters) and has an 'auto' return type, deduce it to a
380
6.75k
  // dependent type.
381
6.75k
  if (Class->isDependentContext() || 
TemplateParams5.20k
) {
382
2.66k
    const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
383
2.66k
    QualType Result = FPT->getReturnType();
384
2.66k
    if (Result->isUndeducedType()) {
385
1.79k
      Result = SubstAutoType(Result, Context.DependentTy);
386
1.79k
      MethodType = Context.getFunctionType(Result, FPT->getParamTypes(),
387
1.79k
                                           FPT->getExtProtoInfo());
388
1.79k
    }
389
2.66k
  }
390
6.75k
391
6.75k
  // C++11 [expr.prim.lambda]p5:
392
6.75k
  //   The closure type for a lambda-expression has a public inline function
393
6.75k
  //   call operator (13.5.4) whose parameters and return type are described by
394
6.75k
  //   the lambda-expression's parameter-declaration-clause and
395
6.75k
  //   trailing-return-type respectively.
396
6.75k
  DeclarationName MethodName
397
6.75k
    = Context.DeclarationNames.getCXXOperatorName(OO_Call);
398
6.75k
  DeclarationNameLoc MethodNameLoc;
399
6.75k
  MethodNameLoc.CXXOperatorName.BeginOpNameLoc
400
6.75k
    = IntroducerRange.getBegin().getRawEncoding();
401
6.75k
  MethodNameLoc.CXXOperatorName.EndOpNameLoc
402
6.75k
    = IntroducerRange.getEnd().getRawEncoding();
403
6.75k
  CXXMethodDecl *Method = CXXMethodDecl::Create(
404
6.75k
      Context, Class, EndLoc,
405
6.75k
      DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
406
6.75k
                          MethodNameLoc),
407
6.75k
      MethodType, MethodTypeInfo, SC_None,
408
6.75k
      /*isInline=*/true, ConstexprKind, EndLoc);
409
6.75k
  Method->setAccess(AS_public);
410
6.75k
411
6.75k
  // Temporarily set the lexical declaration context to the current
412
6.75k
  // context, so that the Scope stack matches the lexical nesting.
413
6.75k
  Method->setLexicalDeclContext(CurContext);
414
6.75k
  // Create a function template if we have a template parameter list
415
6.75k
  FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
416
1.73k
            FunctionTemplateDecl::Create(Context, Class,
417
1.73k
                                         Method->getLocation(), MethodName,
418
1.73k
                                         TemplateParams,
419
5.02k
                                         Method) : nullptr;
420
6.75k
  if (TemplateMethod) {
421
1.73k
    TemplateMethod->setLexicalDeclContext(CurContext);
422
1.73k
    TemplateMethod->setAccess(AS_public);
423
1.73k
    Method->setDescribedFunctionTemplate(TemplateMethod);
424
1.73k
  }
425
6.75k
426
6.75k
  // Add parameters.
427
6.75k
  if (!Params.empty()) {
428
3.27k
    Method->setParams(Params);
429
3.27k
    CheckParmsForFunctionDef(Params,
430
3.27k
                             /*CheckParameterNames=*/false);
431
3.27k
432
3.27k
    for (auto P : Method->parameters())
433
3.82k
      P->setOwningFunction(Method);
434
3.27k
  }
435
6.75k
436
6.75k
  if (Mangling) {
437
5
    Class->setLambdaMangling(Mangling->first, Mangling->second);
438
6.75k
  } else {
439
6.75k
    Decl *ManglingContextDecl;
440
6.75k
    if (MangleNumberingContext *MCtx =
441
4.28k
            getCurrentMangleNumberContext(Class->getDeclContext(),
442
4.28k
                                          ManglingContextDecl)) {
443
4.28k
      unsigned ManglingNumber = MCtx->getManglingNumber(Method);
444
4.28k
      Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
445
4.28k
    }
446
6.75k
  }
447
6.75k
448
6.75k
  return Method;
449
6.75k
}
450
451
void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
452
                                        CXXMethodDecl *CallOperator,
453
                                        SourceRange IntroducerRange,
454
                                        LambdaCaptureDefault CaptureDefault,
455
                                        SourceLocation CaptureDefaultLoc,
456
                                        bool ExplicitParams,
457
                                        bool ExplicitResultType,
458
6.75k
                                        bool Mutable) {
459
6.75k
  LSI->CallOperator = CallOperator;
460
6.75k
  CXXRecordDecl *LambdaClass = CallOperator->getParent();
461
6.75k
  LSI->Lambda = LambdaClass;
462
6.75k
  if (CaptureDefault == LCD_ByCopy)
463
719
    LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
464
6.03k
  else if (CaptureDefault == LCD_ByRef)
465
2.08k
    LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
466
6.75k
  LSI->CaptureDefaultLoc = CaptureDefaultLoc;
467
6.75k
  LSI->IntroducerRange = IntroducerRange;
468
6.75k
  LSI->ExplicitParams = ExplicitParams;
469
6.75k
  LSI->Mutable = Mutable;
470
6.75k
471
6.75k
  if (ExplicitResultType) {
472
913
    LSI->ReturnType = CallOperator->getReturnType();
473
913
474
913
    if (!LSI->ReturnType->isDependentType() &&
475
913
        
!LSI->ReturnType->isVoidType()701
) {
476
452
      if (RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
477
452
                              diag::err_lambda_incomplete_result)) {
478
2
        // Do nothing.
479
2
      }
480
452
    }
481
5.84k
  } else {
482
5.84k
    LSI->HasImplicitReturnType = true;
483
5.84k
  }
484
6.75k
}
485
486
6.75k
void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
487
6.75k
  LSI->finishedExplicitCaptures();
488
6.75k
}
489
490
void Sema::ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
491
                                                    ArrayRef<NamedDecl *> TParams,
492
23
                                                    SourceLocation RAngleLoc) {
493
23
  LambdaScopeInfo *LSI = getCurLambda();
494
23
  assert(LSI && "Expected a lambda scope");
495
23
  assert(LSI->NumExplicitTemplateParams == 0 &&
496
23
         "Already acted on explicit template parameters");
497
23
  assert(LSI->TemplateParams.empty() &&
498
23
         "Explicit template parameters should come "
499
23
         "before invented (auto) ones");
500
23
  assert(!TParams.empty() &&
501
23
         "No template parameters to act on");
502
23
  LSI->TemplateParams.append(TParams.begin(), TParams.end());
503
23
  LSI->NumExplicitTemplateParams = TParams.size();
504
23
  LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
505
23
}
506
507
void Sema::addLambdaParameters(
508
    ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
509
5.26k
    CXXMethodDecl *CallOperator, Scope *CurScope) {
510
5.26k
  // Introduce our parameters into the function scope
511
5.26k
  for (unsigned p = 0, NumParams = CallOperator->getNumParams();
512
7.60k
       p < NumParams; 
++p2.34k
) {
513
2.34k
    ParmVarDecl *Param = CallOperator->getParamDecl(p);
514
2.34k
515
2.34k
    // If this has an identifier, add it to the scope stack.
516
2.34k
    if (CurScope && Param->getIdentifier()) {
517
2.25k
      bool Error = false;
518
2.25k
      // Resolution of CWG 2211 in C++17 renders shadowing ill-formed, but we
519
2.25k
      // retroactively apply it.
520
2.25k
      for (const auto &Capture : Captures) {
521
230
        if (Capture.Id == Param->getIdentifier()) {
522
11
          Error = true;
523
11
          Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
524
11
          Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
525
11
              << Capture.Id << true;
526
11
        }
527
230
      }
528
2.25k
      if (!Error)
529
2.24k
        CheckShadow(CurScope, Param);
530
2.25k
531
2.25k
      PushOnScopeChains(Param, CurScope);
532
2.25k
    }
533
2.34k
  }
534
5.26k
}
535
536
/// If this expression is an enumerator-like expression of some type
537
/// T, return the type T; otherwise, return null.
538
///
539
/// Pointer comparisons on the result here should always work because
540
/// it's derived from either the parent of an EnumConstantDecl
541
/// (i.e. the definition) or the declaration returned by
542
/// EnumType::getDecl() (i.e. the definition).
543
377
static EnumDecl *findEnumForBlockReturn(Expr *E) {
544
377
  // An expression is an enumerator-like expression of type T if,
545
377
  // ignoring parens and parens-like expressions:
546
377
  E = E->IgnoreParens();
547
377
548
377
  //  - it is an enumerator whose enum type is T or
549
377
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
550
27
    if (EnumConstantDecl *D
551
27
          = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
552
27
      return cast<EnumDecl>(D->getDeclContext());
553
27
    }
554
0
    return nullptr;
555
0
  }
556
350
557
350
  //  - it is a comma expression whose RHS is an enumerator-like
558
350
  //    expression of type T or
559
350
  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
560
23
    if (BO->getOpcode() == BO_Comma)
561
1
      return findEnumForBlockReturn(BO->getRHS());
562
22
    return nullptr;
563
22
  }
564
327
565
327
  //  - it is a statement-expression whose value expression is an
566
327
  //    enumerator-like expression of type T or
567
327
  if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
568
1
    if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
569
1
      return findEnumForBlockReturn(last);
570
0
    return nullptr;
571
0
  }
572
326
573
326
  //   - it is a ternary conditional operator (not the GNU ?:
574
326
  //     extension) whose second and third operands are
575
326
  //     enumerator-like expressions of type T or
576
326
  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
577
3
    if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
578
3
      if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
579
3
        return ED;
580
0
    return nullptr;
581
0
  }
582
323
583
323
  // (implicitly:)
584
323
  //   - it is an implicit integral conversion applied to an
585
323
  //     enumerator-like expression of type T or
586
323
  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
587
133
    // We can sometimes see integral conversions in valid
588
133
    // enumerator-like expressions.
589
133
    if (ICE->getCastKind() == CK_IntegralCast)
590
3
      return findEnumForBlockReturn(ICE->getSubExpr());
591
320
592
320
    // Otherwise, just rely on the type.
593
320
  }
594
320
595
320
  //   - it is an expression of that formal enum type.
596
320
  if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
597
15
    return ET->getDecl();
598
15
  }
599
305
600
305
  // Otherwise, nope.
601
305
  return nullptr;
602
305
}
603
604
/// Attempt to find a type T for which the returned expression of the
605
/// given statement is an enumerator-like expression of that type.
606
457
static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
607
457
  if (Expr *retValue = ret->getRetValue())
608
366
    return findEnumForBlockReturn(retValue);
609
91
  return nullptr;
610
91
}
611
612
/// Attempt to find a common type T for which all of the returned
613
/// expressions in a block are enumerator-like expressions of that
614
/// type.
615
442
static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
616
442
  ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
617
442
618
442
  // Try to find one for the first return.
619
442
  EnumDecl *ED = findEnumForBlockReturn(*i);
620
442
  if (!ED) 
return nullptr416
;
621
26
622
26
  // Check that the rest of the returns have the same enum.
623
39
  
for (++i; 26
i != e;
++i13
) {
624
15
    if (findEnumForBlockReturn(*i) != ED)
625
2
      return nullptr;
626
15
  }
627
26
628
26
  // Never infer an anonymous enum type.
629
26
  
if (24
!ED->hasNameForLinkage()24
)
return nullptr3
;
630
21
631
21
  return ED;
632
21
}
633
634
/// Adjust the given return statements so that they formally return
635
/// the given type.  It should require, at most, an IntegralCast.
636
static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
637
21
                                     QualType returnType) {
638
21
  for (ArrayRef<ReturnStmt*>::iterator
639
55
         i = returns.begin(), e = returns.end(); i != e; 
++i34
) {
640
34
    ReturnStmt *ret = *i;
641
34
    Expr *retValue = ret->getRetValue();
642
34
    if (S.Context.hasSameType(retValue->getType(), returnType))
643
14
      continue;
644
20
645
20
    // Right now we only support integral fixup casts.
646
20
    assert(returnType->isIntegralOrUnscopedEnumerationType());
647
20
    assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
648
20
649
20
    ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
650
20
651
20
    Expr *E = (cleanups ? 
cleanups->getSubExpr()0
: retValue);
652
20
    E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
653
20
                                 E, /*base path*/ nullptr, VK_RValue);
654
20
    if (cleanups) {
655
0
      cleanups->setSubExpr(E);
656
20
    } else {
657
20
      ret->setRetValue(E);
658
20
    }
659
20
  }
660
21
}
661
662
5.41k
void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
663
5.41k
  assert(CSI.HasImplicitReturnType);
664
5.41k
  // If it was ever a placeholder, it had to been deduced to DependentTy.
665
5.41k
  assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
666
5.41k
  assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
667
5.41k
         "lambda expressions use auto deduction in C++14 onwards");
668
5.41k
669
5.41k
  // C++ core issue 975:
670
5.41k
  //   If a lambda-expression does not include a trailing-return-type,
671
5.41k
  //   it is as if the trailing-return-type denotes the following type:
672
5.41k
  //     - if there are no return statements in the compound-statement,
673
5.41k
  //       or all return statements return either an expression of type
674
5.41k
  //       void or no expression or braced-init-list, the type void;
675
5.41k
  //     - otherwise, if all return statements return an expression
676
5.41k
  //       and the types of the returned expressions after
677
5.41k
  //       lvalue-to-rvalue conversion (4.1 [conv.lval]),
678
5.41k
  //       array-to-pointer conversion (4.2 [conv.array]), and
679
5.41k
  //       function-to-pointer conversion (4.3 [conv.func]) are the
680
5.41k
  //       same, that common type;
681
5.41k
  //     - otherwise, the program is ill-formed.
682
5.41k
  //
683
5.41k
  // C++ core issue 1048 additionally removes top-level cv-qualifiers
684
5.41k
  // from the types of returned expressions to match the C++14 auto
685
5.41k
  // deduction rules.
686
5.41k
  //
687
5.41k
  // In addition, in blocks in non-C++ modes, if all of the return
688
5.41k
  // statements are enumerator-like expressions of some type T, where
689
5.41k
  // T has a name for linkage, then we infer the return type of the
690
5.41k
  // block to be that type.
691
5.41k
692
5.41k
  // First case: no return statements, implicit void return type.
693
5.41k
  ASTContext &Ctx = getASTContext();
694
5.41k
  if (CSI.Returns.empty()) {
695
4.19k
    // It's possible there were simply no /valid/ return statements.
696
4.19k
    // In this case, the first one we found may have at least given us a type.
697
4.19k
    if (CSI.ReturnType.isNull())
698
4.19k
      CSI.ReturnType = Ctx.VoidTy;
699
4.19k
    return;
700
4.19k
  }
701
1.22k
702
1.22k
  // Second case: at least one return statement has dependent type.
703
1.22k
  // Delay type checking until instantiation.
704
1.22k
  assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
705
1.22k
  if (CSI.ReturnType->isDependentType())
706
57
    return;
707
1.16k
708
1.16k
  // Try to apply the enum-fuzz rule.
709
1.16k
  if (!getLangOpts().CPlusPlus) {
710
442
    assert(isa<BlockScopeInfo>(CSI));
711
442
    const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
712
442
    if (ED) {
713
21
      CSI.ReturnType = Context.getTypeDeclType(ED);
714
21
      adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
715
21
      return;
716
21
    }
717
1.14k
  }
718
1.14k
719
1.14k
  // Third case: only one return statement. Don't bother doing extra work!
720
1.14k
  if (CSI.Returns.size() == 1)
721
1.08k
    return;
722
64
723
64
  // General case: many return statements.
724
64
  // Check that they all have compatible return types.
725
64
726
64
  // We require the return types to strictly match here.
727
64
  // Note that we've already done the required promotions as part of
728
64
  // processing the return statement.
729
175
  
for (const ReturnStmt *RS : CSI.Returns)64
{
730
175
    const Expr *RetE = RS->getRetValue();
731
175
732
175
    QualType ReturnType =
733
175
        (RetE ? 
RetE->getType()152
:
Context.VoidTy23
).getUnqualifiedType();
734
175
    if (Context.getCanonicalFunctionResultType(ReturnType) ==
735
175
          Context.getCanonicalFunctionResultType(CSI.ReturnType)) {
736
166
      // Use the return type with the strictest possible nullability annotation.
737
166
      auto RetTyNullability = ReturnType->getNullability(Ctx);
738
166
      auto BlockNullability = CSI.ReturnType->getNullability(Ctx);
739
166
      if (BlockNullability &&
740
166
          
(0
!RetTyNullability0
||
741
0
           hasWeakerNullability(*RetTyNullability, *BlockNullability)))
742
0
        CSI.ReturnType = ReturnType;
743
166
      continue;
744
166
    }
745
9
746
9
    // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
747
9
    // TODO: It's possible that the *first* return is the divergent one.
748
9
    Diag(RS->getBeginLoc(),
749
9
         diag::err_typecheck_missing_return_type_incompatible)
750
9
        << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
751
9
    // Continue iterating so that we keep emitting diagnostics.
752
9
  }
753
64
}
754
755
QualType Sema::buildLambdaInitCaptureInitialization(
756
    SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
757
    Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool IsDirectInit,
758
449
    Expr *&Init) {
759
449
  // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
760
449
  // deduce against.
761
449
  QualType DeductType = Context.getAutoDeductType();
762
449
  TypeLocBuilder TLB;
763
449
  TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
764
449
  if (ByRef) {
765
103
    DeductType = BuildReferenceType(DeductType, true, Loc, Id);
766
103
    assert(!DeductType.isNull() && "can't build reference to auto");
767
103
    TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
768
103
  }
769
449
  if (EllipsisLoc.isValid()) {
770
51
    if (Init->containsUnexpandedParameterPack()) {
771
50
      Diag(EllipsisLoc, getLangOpts().CPlusPlus2a
772
50
                            ? 
diag::warn_cxx17_compat_init_capture_pack27
773
50
                            : 
diag::ext_init_capture_pack23
);
774
50
      DeductType = Context.getPackExpansionType(DeductType, NumExpansions);
775
50
      TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
776
50
    } else {
777
1
      // Just ignore the ellipsis for now and form a non-pack variable. We'll
778
1
      // diagnose this later when we try to capture it.
779
1
    }
780
51
  }
781
449
  TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
782
449
783
449
  // Deduce the type of the init capture.
784
449
  QualType DeducedType = deduceVarTypeFromInitializer(
785
449
      /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
786
449
      SourceRange(Loc, Loc), IsDirectInit, Init);
787
449
  if (DeducedType.isNull())
788
35
    return QualType();
789
414
790
414
  // Are we a non-list direct initialization?
791
414
  ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
792
414
793
414
  // Perform initialization analysis and ensure any implicit conversions
794
414
  // (such as lvalue-to-rvalue) are enforced.
795
414
  InitializedEntity Entity =
796
414
      InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
797
414
  InitializationKind Kind =
798
414
      IsDirectInit
799
414
          ? 
(CXXDirectInit 143
? InitializationKind::CreateDirect(
800
126
                                 Loc, Init->getBeginLoc(), Init->getEndLoc())
801
143
                           : 
InitializationKind::CreateDirectList(Loc)17
)
802
414
          : 
InitializationKind::CreateCopy(Loc, Init->getBeginLoc())271
;
803
414
804
414
  MultiExprArg Args = Init;
805
414
  if (CXXDirectInit)
806
126
    Args =
807
126
        MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
808
414
  QualType DclT;
809
414
  InitializationSequence InitSeq(*this, Entity, Kind, Args);
810
414
  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
811
414
812
414
  if (Result.isInvalid())
813
3
    return QualType();
814
411
815
411
  Init = Result.getAs<Expr>();
816
411
  return DeducedType;
817
411
}
818
819
VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
820
                                              QualType InitCaptureType,
821
                                              SourceLocation EllipsisLoc,
822
                                              IdentifierInfo *Id,
823
411
                                              unsigned InitStyle, Expr *Init) {
824
411
  // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
825
411
  // rather than reconstructing it here.
826
411
  TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
827
411
  if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
828
50
    PETL.setEllipsisLoc(EllipsisLoc);
829
411
830
411
  // Create a dummy variable representing the init-capture. This is not actually
831
411
  // used as a variable, and only exists as a way to name and refer to the
832
411
  // init-capture.
833
411
  // FIXME: Pass in separate source locations for '&' and identifier.
834
411
  VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
835
411
                                   Loc, Id, InitCaptureType, TSI, SC_Auto);
836
411
  NewVD->setInitCapture(true);
837
411
  NewVD->setReferenced(true);
838
411
  // FIXME: Pass in a VarDecl::InitializationStyle.
839
411
  NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
840
411
  NewVD->markUsed(Context);
841
411
  NewVD->setInit(Init);
842
411
  return NewVD;
843
411
}
844
845
409
void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var) {
846
409
  assert(Var->isInitCapture() && "init capture flag should be set");
847
409
  LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
848
409
                  /*isNested*/false, Var->getLocation(), SourceLocation(),
849
409
                  Var->getType(), /*Invalid*/false);
850
409
}
851
852
void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
853
                                        Declarator &ParamInfo,
854
5.26k
                                        Scope *CurScope) {
855
5.26k
  LambdaScopeInfo *const LSI = getCurLambda();
856
5.26k
  assert(LSI && "LambdaScopeInfo should be on stack!");
857
5.26k
858
5.26k
  // Determine if we're within a context where we know that the lambda will
859
5.26k
  // be dependent, because there are template parameters in scope.
860
5.26k
  bool KnownDependent;
861
5.26k
  if (LSI->NumExplicitTemplateParams > 0) {
862
23
    auto *TemplateParamScope = CurScope->getTemplateParamParent();
863
23
    assert(TemplateParamScope &&
864
23
           "Lambda with explicit template param list should establish a "
865
23
           "template param scope");
866
23
    assert(TemplateParamScope->getParent());
867
23
    KnownDependent = TemplateParamScope->getParent()
868
23
                                       ->getTemplateParamParent() != nullptr;
869
5.23k
  } else {
870
5.23k
    KnownDependent = CurScope->getTemplateParamParent() != nullptr;
871
5.23k
  }
872
5.26k
873
5.26k
  // Determine the signature of the call operator.
874
5.26k
  TypeSourceInfo *MethodTyInfo;
875
5.26k
  bool ExplicitParams = true;
876
5.26k
  bool ExplicitResultType = true;
877
5.26k
  bool ContainsUnexpandedParameterPack = false;
878
5.26k
  SourceLocation EndLoc;
879
5.26k
  SmallVector<ParmVarDecl *, 8> Params;
880
5.26k
  if (ParamInfo.getNumTypeObjects() == 0) {
881
1.22k
    // C++11 [expr.prim.lambda]p4:
882
1.22k
    //   If a lambda-expression does not include a lambda-declarator, it is as
883
1.22k
    //   if the lambda-declarator were ().
884
1.22k
    FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
885
1.22k
        /*IsVariadic=*/false, /*IsCXXMethod=*/true));
886
1.22k
    EPI.HasTrailingReturn = true;
887
1.22k
    EPI.TypeQuals.addConst();
888
1.22k
    // C++1y [expr.prim.lambda]:
889
1.22k
    //   The lambda return type is 'auto', which is replaced by the
890
1.22k
    //   trailing-return type if provided and/or deduced from 'return'
891
1.22k
    //   statements
892
1.22k
    // We don't do this before C++1y, because we don't support deduced return
893
1.22k
    // types there.
894
1.22k
    QualType DefaultTypeForNoTrailingReturn =
895
1.22k
        getLangOpts().CPlusPlus14 ? 
Context.getAutoDeductType()685
896
1.22k
                                  : 
Context.DependentTy540
;
897
1.22k
    QualType MethodTy =
898
1.22k
        Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
899
1.22k
    MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
900
1.22k
    ExplicitParams = false;
901
1.22k
    ExplicitResultType = false;
902
1.22k
    EndLoc = Intro.Range.getEnd();
903
4.03k
  } else {
904
4.03k
    assert(ParamInfo.isFunctionDeclarator() &&
905
4.03k
           "lambda-declarator is a function");
906
4.03k
    DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
907
4.03k
908
4.03k
    // C++11 [expr.prim.lambda]p5:
909
4.03k
    //   This function call operator is declared const (9.3.1) if and only if
910
4.03k
    //   the lambda-expression's parameter-declaration-clause is not followed
911
4.03k
    //   by mutable. It is neither virtual nor declared volatile. [...]
912
4.03k
    if (!FTI.hasMutableQualifier()) {
913
3.90k
      FTI.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const,
914
3.90k
                                                    SourceLocation());
915
3.90k
    }
916
4.03k
917
4.03k
    MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
918
4.03k
    assert(MethodTyInfo && "no type from lambda-declarator");
919
4.03k
    EndLoc = ParamInfo.getSourceRange().getEnd();
920
4.03k
921
4.03k
    ExplicitResultType = FTI.hasTrailingReturnType();
922
4.03k
923
4.03k
    if (FTIHasNonVoidParameters(FTI)) {
924
2.13k
      Params.reserve(FTI.NumParams);
925
4.48k
      for (unsigned i = 0, e = FTI.NumParams; i != e; 
++i2.34k
)
926
2.34k
        Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param));
927
2.13k
    }
928
4.03k
929
4.03k
    // Check for unexpanded parameter packs in the method type.
930
4.03k
    if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
931
10
      ContainsUnexpandedParameterPack = true;
932
4.03k
  }
933
5.26k
934
5.26k
  CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
935
5.26k
                                                 KnownDependent, Intro.Default);
936
5.26k
937
5.26k
  CXXMethodDecl *Method =
938
5.26k
      startLambdaDefinition(Class, Intro.Range, MethodTyInfo, EndLoc, Params,
939
5.26k
                            ParamInfo.getDeclSpec().getConstexprSpecifier());
940
5.26k
  if (ExplicitParams)
941
4.03k
    CheckCXXDefaultArguments(Method);
942
5.26k
943
5.26k
  // This represents the function body for the lambda function, check if we
944
5.26k
  // have to apply optnone due to a pragma.
945
5.26k
  AddRangeBasedOptnone(Method);
946
5.26k
947
5.26k
  // code_seg attribute on lambda apply to the method.
948
5.26k
  if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
949
2
    Method->addAttr(A);
950
5.26k
951
5.26k
  // Attributes on the lambda apply to the method.
952
5.26k
  ProcessDeclAttributes(CurScope, Method, ParamInfo);
953
5.26k
954
5.26k
  // CUDA lambdas get implicit attributes based on the scope in which they're
955
5.26k
  // declared.
956
5.26k
  if (getLangOpts().CUDA)
957
82
    CUDASetLambdaAttrs(Method);
958
5.26k
959
5.26k
  // Introduce the function call operator as the current declaration context.
960
5.26k
  PushDeclContext(CurScope, Method);
961
5.26k
962
5.26k
  // Build the lambda scope.
963
5.26k
  buildLambdaScope(LSI, Method, Intro.Range, Intro.Default, Intro.DefaultLoc,
964
5.26k
                   ExplicitParams, ExplicitResultType, !Method->isConst());
965
5.26k
966
5.26k
  // C++11 [expr.prim.lambda]p9:
967
5.26k
  //   A lambda-expression whose smallest enclosing scope is a block scope is a
968
5.26k
  //   local lambda expression; any other lambda expression shall not have a
969
5.26k
  //   capture-default or simple-capture in its lambda-introducer.
970
5.26k
  //
971
5.26k
  // For simple-captures, this is covered by the check below that any named
972
5.26k
  // entity is a variable that can be captured.
973
5.26k
  //
974
5.26k
  // For DR1632, we also allow a capture-default in any context where we can
975
5.26k
  // odr-use 'this' (in particular, in a default initializer for a non-static
976
5.26k
  // data member).
977
5.26k
  if (Intro.Default != LCD_None && 
!Class->getParent()->isFunctionOrMethod()2.44k
&&
978
5.26k
      
(20
getCurrentThisType().isNull()20
||
979
20
       CheckCXXThisCapture(SourceLocation(), /*Explicit*/true,
980
16
                           /*BuildAndDiagnose*/false)))
981
4
    Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
982
5.26k
983
5.26k
  // Distinct capture names, for diagnostics.
984
5.26k
  llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
985
5.26k
986
5.26k
  // Handle explicit captures.
987
5.26k
  SourceLocation PrevCaptureLoc
988
5.26k
    = Intro.Default == LCD_None? 
Intro.Range.getBegin()2.81k
:
Intro.DefaultLoc2.44k
;
989
6.50k
  for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
990
5.26k
       
PrevCaptureLoc = C->Loc, ++C1.24k
) {
991
1.24k
    if (C->Kind == LCK_This || 
C->Kind == LCK_StarThis1.03k
) {
992
316
      if (C->Kind == LCK_StarThis)
993
106
        Diag(C->Loc, !getLangOpts().CPlusPlus17
994
106
                             ? 
diag::ext_star_this_lambda_capture_cxx171
995
106
                             : 
diag::warn_cxx14_compat_star_this_lambda_capture105
);
996
316
997
316
      // C++11 [expr.prim.lambda]p8:
998
316
      //   An identifier or this shall not appear more than once in a
999
316
      //   lambda-capture.
1000
316
      if (LSI->isCXXThisCaptured()) {
1001
5
        Diag(C->Loc, diag::err_capture_more_than_once)
1002
5
            << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1003
5
            << FixItHint::CreateRemoval(
1004
5
                   SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1005
5
        continue;
1006
5
      }
1007
311
1008
311
      // C++2a [expr.prim.lambda]p8:
1009
311
      //  If a lambda-capture includes a capture-default that is =,
1010
311
      //  each simple-capture of that lambda-capture shall be of the form
1011
311
      //  "&identifier", "this", or "* this". [ Note: The form [&,this] is
1012
311
      //  redundant but accepted for compatibility with ISO C++14. --end note ]
1013
311
      if (Intro.Default == LCD_ByCopy && 
C->Kind != LCK_StarThis9
)
1014
5
        Diag(C->Loc, !getLangOpts().CPlusPlus2a
1015
5
                         ? 
diag::ext_equals_this_lambda_capture_cxx2a3
1016
5
                         : 
diag::warn_cxx17_compat_equals_this_lambda_capture2
);
1017
311
1018
311
      // C++11 [expr.prim.lambda]p12:
1019
311
      //   If this is captured by a local lambda expression, its nearest
1020
311
      //   enclosing function shall be a non-static member function.
1021
311
      QualType ThisCaptureType = getCurrentThisType();
1022
311
      if (ThisCaptureType.isNull()) {
1023
3
        Diag(C->Loc, diag::err_this_capture) << true;
1024
3
        continue;
1025
3
      }
1026
308
1027
308
      CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1028
308
                          /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1029
308
                          C->Kind == LCK_StarThis);
1030
308
      if (!LSI->Captures.empty())
1031
307
        LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1032
308
      continue;
1033
308
    }
1034
930
1035
930
    assert(C->Id && "missing identifier for capture");
1036
930
1037
930
    if (C->Init.isInvalid())
1038
4
      continue;
1039
926
1040
926
    VarDecl *Var = nullptr;
1041
926
    if (C->Init.isUsable()) {
1042
324
      Diag(C->Loc, getLangOpts().CPlusPlus14
1043
324
                       ? 
diag::warn_cxx11_compat_init_capture276
1044
324
                       : 
diag::ext_init_capture48
);
1045
324
1046
324
      // If the initializer expression is usable, but the InitCaptureType
1047
324
      // is not, then an error has occurred - so ignore the capture for now.
1048
324
      // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1049
324
      // FIXME: we should create the init capture variable and mark it invalid
1050
324
      // in this case.
1051
324
      if (C->InitCaptureType.get().isNull())
1052
30
        continue;
1053
294
1054
294
      if (C->Init.get()->containsUnexpandedParameterPack() &&
1055
294
          
!C->InitCaptureType.get()->getAs<PackExpansionType>()66
)
1056
16
        ContainsUnexpandedParameterPack = true;
1057
294
1058
294
      unsigned InitStyle;
1059
294
      switch (C->InitKind) {
1060
294
      case LambdaCaptureInitKind::NoInit:
1061
0
        llvm_unreachable("not an init-capture?");
1062
294
      case LambdaCaptureInitKind::CopyInit:
1063
196
        InitStyle = VarDecl::CInit;
1064
196
        break;
1065
294
      case LambdaCaptureInitKind::DirectInit:
1066
82
        InitStyle = VarDecl::CallInit;
1067
82
        break;
1068
294
      case LambdaCaptureInitKind::ListInit:
1069
16
        InitStyle = VarDecl::ListInit;
1070
16
        break;
1071
294
      }
1072
294
      Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1073
294
                                           C->EllipsisLoc, C->Id, InitStyle,
1074
294
                                           C->Init.get());
1075
294
      // C++1y [expr.prim.lambda]p11:
1076
294
      //   An init-capture behaves as if it declares and explicitly
1077
294
      //   captures a variable [...] whose declarative region is the
1078
294
      //   lambda-expression's compound-statement
1079
294
      if (Var)
1080
294
        PushOnScopeChains(Var, CurScope, false);
1081
602
    } else {
1082
602
      assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1083
602
             "init capture has valid but null init?");
1084
602
1085
602
      // C++11 [expr.prim.lambda]p8:
1086
602
      //   If a lambda-capture includes a capture-default that is &, the
1087
602
      //   identifiers in the lambda-capture shall not be preceded by &.
1088
602
      //   If a lambda-capture includes a capture-default that is =, [...]
1089
602
      //   each identifier it contains shall be preceded by &.
1090
602
      if (C->Kind == LCK_ByRef && 
Intro.Default == LCD_ByRef175
) {
1091
6
        Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1092
6
            << FixItHint::CreateRemoval(
1093
6
                SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1094
6
        continue;
1095
596
      } else if (C->Kind == LCK_ByCopy && 
Intro.Default == LCD_ByCopy427
) {
1096
1
        Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1097
1
            << FixItHint::CreateRemoval(
1098
1
                SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1099
1
        continue;
1100
1
      }
1101
595
1102
595
      // C++11 [expr.prim.lambda]p10:
1103
595
      //   The identifiers in a capture-list are looked up using the usual
1104
595
      //   rules for unqualified name lookup (3.4.1)
1105
595
      DeclarationNameInfo Name(C->Id, C->Loc);
1106
595
      LookupResult R(*this, Name, LookupOrdinaryName);
1107
595
      LookupName(R, CurScope);
1108
595
      if (R.isAmbiguous())
1109
1
        continue;
1110
594
      if (R.empty()) {
1111
1
        // FIXME: Disable corrections that would add qualification?
1112
1
        CXXScopeSpec ScopeSpec;
1113
1
        DeclFilterCCC<VarDecl> Validator{};
1114
1
        if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1115
0
          continue;
1116
594
      }
1117
594
1118
594
      Var = R.getAsSingle<VarDecl>();
1119
594
      if (Var && 
DiagnoseUseOfDecl(Var, C->Loc)588
)
1120
1
        continue;
1121
887
    }
1122
887
1123
887
    // C++11 [expr.prim.lambda]p8:
1124
887
    //   An identifier or this shall not appear more than once in a
1125
887
    //   lambda-capture.
1126
887
    if (!CaptureNames.insert(C->Id).second) {
1127
9
      if (Var && LSI->isCaptured(Var)) {
1128
7
        Diag(C->Loc, diag::err_capture_more_than_once)
1129
7
            << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
1130
7
            << FixItHint::CreateRemoval(
1131
7
                   SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1132
7
      } else
1133
2
        // Previous capture captured something different (one or both was
1134
2
        // an init-cpature): no fixit.
1135
2
        Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1136
9
      continue;
1137
9
    }
1138
878
1139
878
    // C++11 [expr.prim.lambda]p10:
1140
878
    //   [...] each such lookup shall find a variable with automatic storage
1141
878
    //   duration declared in the reaching scope of the local lambda expression.
1142
878
    // Note that the 'reaching scope' check happens in tryCaptureVariable().
1143
878
    if (!Var) {
1144
6
      Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1145
6
      continue;
1146
6
    }
1147
872
1148
872
    // Ignore invalid decls; they'll just confuse the code later.
1149
872
    if (Var->isInvalidDecl())
1150
3
      continue;
1151
869
1152
869
    if (!Var->hasLocalStorage()) {
1153
2
      Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1154
2
      Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1155
2
      continue;
1156
2
    }
1157
867
1158
867
    // C++11 [expr.prim.lambda]p23:
1159
867
    //   A capture followed by an ellipsis is a pack expansion (14.5.3).
1160
867
    SourceLocation EllipsisLoc;
1161
867
    if (C->EllipsisLoc.isValid()) {
1162
113
      if (Var->isParameterPack()) {
1163
109
        EllipsisLoc = C->EllipsisLoc;
1164
109
      } else {
1165
4
        Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1166
4
            << (C->Init.isUsable() ? 
C->Init.get()->getSourceRange()1
1167
4
                                   : 
SourceRange(C->Loc)3
);
1168
4
1169
4
        // Just ignore the ellipsis.
1170
4
      }
1171
754
    } else if (Var->isParameterPack()) {
1172
10
      ContainsUnexpandedParameterPack = true;
1173
10
    }
1174
867
1175
867
    if (C->Init.isUsable()) {
1176
292
      addInitCapture(LSI, Var);
1177
575
    } else {
1178
575
      TryCaptureKind Kind = C->Kind == LCK_ByRef ? 
TryCapture_ExplicitByRef165
:
1179
575
                                                   
TryCapture_ExplicitByVal410
;
1180
575
      tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1181
575
    }
1182
867
    if (!LSI->Captures.empty())
1183
863
      LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1184
867
  }
1185
5.26k
  finishLambdaExplicitCaptures(LSI);
1186
5.26k
1187
5.26k
  LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1188
5.26k
1189
5.26k
  // Add lambda parameters into scope.
1190
5.26k
  addLambdaParameters(Intro.Captures, Method, CurScope);
1191
5.26k
1192
5.26k
  // Enter a new evaluation context to insulate the lambda from any
1193
5.26k
  // cleanups from the enclosing full-expression.
1194
5.26k
  PushExpressionEvaluationContext(
1195
5.26k
      ExpressionEvaluationContext::PotentiallyEvaluated);
1196
5.26k
}
1197
1198
void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
1199
44
                            bool IsInstantiation) {
1200
44
  LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
1201
44
1202
44
  // Leave the expression-evaluation context.
1203
44
  DiscardCleanupsInEvaluationContext();
1204
44
  PopExpressionEvaluationContext();
1205
44
1206
44
  // Leave the context of the lambda.
1207
44
  if (!IsInstantiation)
1208
28
    PopDeclContext();
1209
44
1210
44
  // Finalize the lambda.
1211
44
  CXXRecordDecl *Class = LSI->Lambda;
1212
44
  Class->setInvalidDecl();
1213
44
  SmallVector<Decl*, 4> Fields(Class->fields());
1214
44
  ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1215
44
              SourceLocation(), ParsedAttributesView());
1216
44
  CheckCompletedCXXClass(Class);
1217
44
1218
44
  PopFunctionScopeInfo();
1219
44
}
1220
1221
QualType Sema::getLambdaConversionFunctionResultType(
1222
3.01k
    const FunctionProtoType *CallOpProto) {
1223
3.01k
  // The function type inside the pointer type is the same as the call
1224
3.01k
  // operator with some tweaks. The calling convention is the default free
1225
3.01k
  // function convention, and the type qualifications are lost.
1226
3.01k
  const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1227
3.01k
      CallOpProto->getExtProtoInfo();
1228
3.01k
  FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1229
3.01k
  CallingConv CC = Context.getDefaultCallingConvention(
1230
3.01k
      CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1231
3.01k
  InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1232
3.01k
  InvokerExtInfo.TypeQuals = Qualifiers();
1233
3.01k
  assert(InvokerExtInfo.RefQualifier == RQ_None &&
1234
3.01k
      "Lambda's call operator should not have a reference qualifier");
1235
3.01k
  return Context.getFunctionType(CallOpProto->getReturnType(),
1236
3.01k
                                 CallOpProto->getParamTypes(), InvokerExtInfo);
1237
3.01k
}
1238
1239
/// Add a lambda's conversion to function pointer, as described in
1240
/// C++11 [expr.prim.lambda]p6.
1241
static void addFunctionPointerConversion(Sema &S,
1242
                                         SourceRange IntroducerRange,
1243
                                         CXXRecordDecl *Class,
1244
2.76k
                                         CXXMethodDecl *CallOperator) {
1245
2.76k
  // This conversion is explicitly disabled if the lambda's function has
1246
2.76k
  // pass_object_size attributes on any of its parameters.
1247
2.76k
  auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1248
2.45k
    return P->hasAttr<PassObjectSizeAttr>();
1249
2.45k
  };
1250
2.76k
  if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
1251
2
    return;
1252
2.76k
1253
2.76k
  // Add the conversion to function pointer.
1254
2.76k
  QualType InvokerFunctionTy = S.getLambdaConversionFunctionResultType(
1255
2.76k
      CallOperator->getType()->castAs<FunctionProtoType>());
1256
2.76k
  QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1257
2.76k
1258
2.76k
  // Create the type of the conversion function.
1259
2.76k
  FunctionProtoType::ExtProtoInfo ConvExtInfo(
1260
2.76k
      S.Context.getDefaultCallingConvention(
1261
2.76k
      /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1262
2.76k
  // The conversion function is always const and noexcept.
1263
2.76k
  ConvExtInfo.TypeQuals = Qualifiers();
1264
2.76k
  ConvExtInfo.TypeQuals.addConst();
1265
2.76k
  ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1266
2.76k
  QualType ConvTy =
1267
2.76k
      S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
1268
2.76k
1269
2.76k
  SourceLocation Loc = IntroducerRange.getBegin();
1270
2.76k
  DeclarationName ConversionName
1271
2.76k
    = S.Context.DeclarationNames.getCXXConversionFunctionName(
1272
2.76k
        S.Context.getCanonicalType(PtrToFunctionTy));
1273
2.76k
  DeclarationNameLoc ConvNameLoc;
1274
2.76k
  // Construct a TypeSourceInfo for the conversion function, and wire
1275
2.76k
  // all the parameters appropriately for the FunctionProtoTypeLoc
1276
2.76k
  // so that everything works during transformation/instantiation of
1277
2.76k
  // generic lambdas.
1278
2.76k
  // The main reason for wiring up the parameters of the conversion
1279
2.76k
  // function with that of the call operator is so that constructs
1280
2.76k
  // like the following work:
1281
2.76k
  // auto L = [](auto b) {                <-- 1
1282
2.76k
  //   return [](auto a) -> decltype(a) { <-- 2
1283
2.76k
  //      return a;
1284
2.76k
  //   };
1285
2.76k
  // };
1286
2.76k
  // int (*fp)(int) = L(5);
1287
2.76k
  // Because the trailing return type can contain DeclRefExprs that refer
1288
2.76k
  // to the original call operator's variables, we hijack the call
1289
2.76k
  // operators ParmVarDecls below.
1290
2.76k
  TypeSourceInfo *ConvNamePtrToFunctionTSI =
1291
2.76k
      S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1292
2.76k
  ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI;
1293
2.76k
1294
2.76k
  // The conversion function is a conversion to a pointer-to-function.
1295
2.76k
  TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1296
2.76k
  FunctionProtoTypeLoc ConvTL =
1297
2.76k
      ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1298
2.76k
  // Get the result of the conversion function which is a pointer-to-function.
1299
2.76k
  PointerTypeLoc PtrToFunctionTL =
1300
2.76k
      ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1301
2.76k
  // Do the same for the TypeSourceInfo that is used to name the conversion
1302
2.76k
  // operator.
1303
2.76k
  PointerTypeLoc ConvNamePtrToFunctionTL =
1304
2.76k
      ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1305
2.76k
1306
2.76k
  // Get the underlying function types that the conversion function will
1307
2.76k
  // be converting to (should match the type of the call operator).
1308
2.76k
  FunctionProtoTypeLoc CallOpConvTL =
1309
2.76k
      PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1310
2.76k
  FunctionProtoTypeLoc CallOpConvNameTL =
1311
2.76k
    ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1312
2.76k
1313
2.76k
  // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1314
2.76k
  // These parameter's are essentially used to transform the name and
1315
2.76k
  // the type of the conversion operator.  By using the same parameters
1316
2.76k
  // as the call operator's we don't have to fix any back references that
1317
2.76k
  // the trailing return type of the call operator's uses (such as
1318
2.76k
  // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1319
2.76k
  // - we can simply use the return type of the call operator, and
1320
2.76k
  // everything should work.
1321
2.76k
  SmallVector<ParmVarDecl *, 4> InvokerParams;
1322
5.22k
  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; 
++I2.45k
) {
1323
2.45k
    ParmVarDecl *From = CallOperator->getParamDecl(I);
1324
2.45k
1325
2.45k
    InvokerParams.push_back(ParmVarDecl::Create(
1326
2.45k
        S.Context,
1327
2.45k
        // Temporarily add to the TU. This is set to the invoker below.
1328
2.45k
        S.Context.getTranslationUnitDecl(), From->getBeginLoc(),
1329
2.45k
        From->getLocation(), From->getIdentifier(), From->getType(),
1330
2.45k
        From->getTypeSourceInfo(), From->getStorageClass(),
1331
2.45k
        /*DefArg=*/nullptr));
1332
2.45k
    CallOpConvTL.setParam(I, From);
1333
2.45k
    CallOpConvNameTL.setParam(I, From);
1334
2.45k
  }
1335
2.76k
1336
2.76k
  CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1337
2.76k
      S.Context, Class, Loc,
1338
2.76k
      DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
1339
2.76k
      /*isInline=*/true, ExplicitSpecifier(),
1340
2.76k
      S.getLangOpts().CPlusPlus17 ? 
CSK_constexpr452
:
CSK_unspecified2.31k
,
1341
2.76k
      CallOperator->getBody()->getEndLoc());
1342
2.76k
  Conversion->setAccess(AS_public);
1343
2.76k
  Conversion->setImplicit(true);
1344
2.76k
1345
2.76k
  if (Class->isGenericLambda()) {
1346
1.22k
    // Create a template version of the conversion operator, using the template
1347
1.22k
    // parameter list of the function call operator.
1348
1.22k
    FunctionTemplateDecl *TemplateCallOperator =
1349
1.22k
            CallOperator->getDescribedFunctionTemplate();
1350
1.22k
    FunctionTemplateDecl *ConversionTemplate =
1351
1.22k
                  FunctionTemplateDecl::Create(S.Context, Class,
1352
1.22k
                                      Loc, ConversionName,
1353
1.22k
                                      TemplateCallOperator->getTemplateParameters(),
1354
1.22k
                                      Conversion);
1355
1.22k
    ConversionTemplate->setAccess(AS_public);
1356
1.22k
    ConversionTemplate->setImplicit(true);
1357
1.22k
    Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1358
1.22k
    Class->addDecl(ConversionTemplate);
1359
1.22k
  } else
1360
1.54k
    Class->addDecl(Conversion);
1361
2.76k
  // Add a non-static member function that will be the result of
1362
2.76k
  // the conversion with a certain unique ID.
1363
2.76k
  DeclarationName InvokerName = &S.Context.Idents.get(
1364
2.76k
                                                 getLambdaStaticInvokerName());
1365
2.76k
  // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1366
2.76k
  // we should get a prebuilt TrivialTypeSourceInfo from Context
1367
2.76k
  // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1368
2.76k
  // then rewire the parameters accordingly, by hoisting up the InvokeParams
1369
2.76k
  // loop below and then use its Params to set Invoke->setParams(...) below.
1370
2.76k
  // This would avoid the 'const' qualifier of the calloperator from
1371
2.76k
  // contaminating the type of the invoker, which is currently adjusted
1372
2.76k
  // in SemaTemplateDeduction.cpp:DeduceTemplateArguments.  Fixing the
1373
2.76k
  // trailing return type of the invoker would require a visitor to rebuild
1374
2.76k
  // the trailing return type and adjusting all back DeclRefExpr's to refer
1375
2.76k
  // to the new static invoker parameters - not the call operator's.
1376
2.76k
  CXXMethodDecl *Invoke = CXXMethodDecl::Create(
1377
2.76k
      S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
1378
2.76k
      InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
1379
2.76k
      /*isInline=*/true, CSK_unspecified, CallOperator->getBody()->getEndLoc());
1380
5.22k
  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; 
++I2.45k
)
1381
2.45k
    InvokerParams[I]->setOwningFunction(Invoke);
1382
2.76k
  Invoke->setParams(InvokerParams);
1383
2.76k
  Invoke->setAccess(AS_private);
1384
2.76k
  Invoke->setImplicit(true);
1385
2.76k
  if (Class->isGenericLambda()) {
1386
1.22k
    FunctionTemplateDecl *TemplateCallOperator =
1387
1.22k
            CallOperator->getDescribedFunctionTemplate();
1388
1.22k
    FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
1389
1.22k
                          S.Context, Class, Loc, InvokerName,
1390
1.22k
                          TemplateCallOperator->getTemplateParameters(),
1391
1.22k
                          Invoke);
1392
1.22k
    StaticInvokerTemplate->setAccess(AS_private);
1393
1.22k
    StaticInvokerTemplate->setImplicit(true);
1394
1.22k
    Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1395
1.22k
    Class->addDecl(StaticInvokerTemplate);
1396
1.22k
  } else
1397
1.54k
    Class->addDecl(Invoke);
1398
2.76k
}
1399
1400
/// Add a lambda's conversion to block pointer.
1401
static void addBlockPointerConversion(Sema &S,
1402
                                      SourceRange IntroducerRange,
1403
                                      CXXRecordDecl *Class,
1404
126
                                      CXXMethodDecl *CallOperator) {
1405
126
  QualType FunctionTy = S.getLambdaConversionFunctionResultType(
1406
126
      CallOperator->getType()->castAs<FunctionProtoType>());
1407
126
  QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1408
126
1409
126
  FunctionProtoType::ExtProtoInfo ConversionEPI(
1410
126
      S.Context.getDefaultCallingConvention(
1411
126
          /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1412
126
  ConversionEPI.TypeQuals = Qualifiers();
1413
126
  ConversionEPI.TypeQuals.addConst();
1414
126
  QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ConversionEPI);
1415
126
1416
126
  SourceLocation Loc = IntroducerRange.getBegin();
1417
126
  DeclarationName Name
1418
126
    = S.Context.DeclarationNames.getCXXConversionFunctionName(
1419
126
        S.Context.getCanonicalType(BlockPtrTy));
1420
126
  DeclarationNameLoc NameLoc;
1421
126
  NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
1422
126
  CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1423
126
      S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
1424
126
      S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1425
126
      /*isInline=*/true, ExplicitSpecifier(), CSK_unspecified,
1426
126
      CallOperator->getBody()->getEndLoc());
1427
126
  Conversion->setAccess(AS_public);
1428
126
  Conversion->setImplicit(true);
1429
126
  Class->addDecl(Conversion);
1430
126
}
1431
1432
ExprResult Sema::BuildCaptureInit(const Capture &Cap,
1433
                                  SourceLocation ImplicitCaptureLoc,
1434
229k
                                  bool IsOpenMPMapping) {
1435
229k
  // VLA captures don't have a stored initialization expression.
1436
229k
  if (Cap.isVLATypeCapture())
1437
5.58k
    return ExprResult();
1438
224k
1439
224k
  // An init-capture is initialized directly from its stored initializer.
1440
224k
  if (Cap.isInitCapture())
1441
405
    return Cap.getVariable()->getInit();
1442
223k
1443
223k
  // For anything else, build an initialization expression. For an implicit
1444
223k
  // capture, the capture notionally happens at the capture-default, so use
1445
223k
  // that location here.
1446
223k
  SourceLocation Loc =
1447
223k
      ImplicitCaptureLoc.isValid() ? 
ImplicitCaptureLoc222k
:
Cap.getLocation()1.06k
;
1448
223k
1449
223k
  // C++11 [expr.prim.lambda]p21:
1450
223k
  //   When the lambda-expression is evaluated, the entities that
1451
223k
  //   are captured by copy are used to direct-initialize each
1452
223k
  //   corresponding non-static data member of the resulting closure
1453
223k
  //   object. (For array members, the array elements are
1454
223k
  //   direct-initialized in increasing subscript order.) These
1455
223k
  //   initializations are performed in the (unspecified) order in
1456
223k
  //   which the non-static data members are declared.
1457
223k
1458
223k
  // C++ [expr.prim.lambda]p12:
1459
223k
  //   An entity captured by a lambda-expression is odr-used (3.2) in
1460
223k
  //   the scope containing the lambda-expression.
1461
223k
  ExprResult Init;
1462
223k
  IdentifierInfo *Name = nullptr;
1463
223k
  if (Cap.isThisCapture()) {
1464
7.99k
    QualType ThisTy = getCurrentThisType();
1465
7.99k
    Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
1466
7.99k
    if (Cap.isCopyCapture())
1467
122
      Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1468
7.87k
    else
1469
7.87k
      Init = This;
1470
215k
  } else {
1471
215k
    assert(Cap.isVariableCapture() && "unknown kind of capture");
1472
215k
    VarDecl *Var = Cap.getVariable();
1473
215k
    Name = Var->getIdentifier();
1474
215k
    Init = BuildDeclarationNameExpr(
1475
215k
      CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
1476
215k
  }
1477
223k
1478
223k
  // In OpenMP, the capture kind doesn't actually describe how to capture:
1479
223k
  // variables are "mapped" onto the device in a process that does not formally
1480
223k
  // make a copy, even for a "copy capture".
1481
223k
  if (IsOpenMPMapping)
1482
218k
    return Init;
1483
4.98k
1484
4.98k
  if (Init.isInvalid())
1485
0
    return ExprError();
1486
4.98k
1487
4.98k
  Expr *InitExpr = Init.get();
1488
4.98k
  InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1489
4.98k
      Name, Cap.getCaptureType(), Loc);
1490
4.98k
  InitializationKind InitKind =
1491
4.98k
      InitializationKind::CreateDirect(Loc, Loc, Loc);
1492
4.98k
  InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
1493
4.98k
  return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
1494
4.98k
}
1495
1496
ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
1497
5.23k
                                 Scope *CurScope) {
1498
5.23k
  LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
1499
5.23k
  ActOnFinishFunctionBody(LSI.CallOperator, Body);
1500
5.23k
  return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
1501
5.23k
}
1502
1503
static LambdaCaptureDefault
1504
6.71k
mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {
1505
6.71k
  switch (ICS) {
1506
6.71k
  case CapturingScopeInfo::ImpCap_None:
1507
3.91k
    return LCD_None;
1508
6.71k
  case CapturingScopeInfo::ImpCap_LambdaByval:
1509
719
    return LCD_ByCopy;
1510
6.71k
  case CapturingScopeInfo::ImpCap_CapturedRegion:
1511
2.07k
  case CapturingScopeInfo::ImpCap_LambdaByref:
1512
2.07k
    return LCD_ByRef;
1513
2.07k
  case CapturingScopeInfo::ImpCap_Block:
1514
0
    llvm_unreachable("block capture in lambda");
1515
0
  }
1516
0
  llvm_unreachable("Unknown implicit capture style");
1517
0
}
1518
1519
526
bool Sema::CaptureHasSideEffects(const Capture &From) {
1520
526
  if (From.isInitCapture()) {
1521
150
    Expr *Init = From.getVariable()->getInit();
1522
150
    if (Init && Init->HasSideEffects(Context))
1523
38
      return true;
1524
488
  }
1525
488
1526
488
  if (!From.isCopyCapture())
1527
124
    return false;
1528
364
1529
364
  const QualType T = From.isThisCapture()
1530
364
                         ? 
getCurrentThisType()->getPointeeType()31
1531
364
                         : 
From.getCaptureType()333
;
1532
364
1533
364
  if (T.isVolatileQualified())
1534
2
    return true;
1535
362
1536
362
  const Type *BaseT = T->getBaseElementTypeUnsafe();
1537
362
  if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
1538
75
    return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
1539
75
           
!RD->hasTrivialDestructor()43
;
1540
287
1541
287
  return false;
1542
287
}
1543
1544
bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
1545
526
                                       const Capture &From) {
1546
526
  if (CaptureHasSideEffects(From))
1547
75
    return false;
1548
451
1549
451
  if (From.isVLATypeCapture())
1550
11
    return false;
1551
440
1552
440
  auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
1553
440
  if (From.isThisCapture())
1554
71
    diag << "'this'";
1555
369
  else
1556
369
    diag << From.getVariable();
1557
440
  diag << From.isNonODRUsed();
1558
440
  diag << FixItHint::CreateRemoval(CaptureRange);
1559
440
  return true;
1560
440
}
1561
1562
/// Create a field within the lambda class or captured statement record for the
1563
/// given capture.
1564
FieldDecl *Sema::BuildCaptureField(RecordDecl *RD,
1565
229k
                                   const sema::Capture &Capture) {
1566
229k
  SourceLocation Loc = Capture.getLocation();
1567
229k
  QualType FieldType = Capture.getCaptureType();
1568
229k
1569
229k
  TypeSourceInfo *TSI = nullptr;
1570
229k
  if (Capture.isVariableCapture()) {
1571
216k
    auto *Var = Capture.getVariable();
1572
216k
    if (Var->isInitCapture())
1573
443
      TSI = Capture.getVariable()->getTypeSourceInfo();
1574
216k
  }
1575
229k
1576
229k
  // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
1577
229k
  // appropriate, at least for an implicit capture.
1578
229k
  if (!TSI)
1579
229k
    TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
1580
229k
1581
229k
  // Build the non-static data member.
1582
229k
  FieldDecl *Field =
1583
229k
      FieldDecl::Create(Context, RD, Loc, Loc, nullptr, FieldType, TSI, nullptr,
1584
229k
                        false, ICIS_NoInit);
1585
229k
  // If the variable being captured has an invalid type, mark the class as
1586
229k
  // invalid as well.
1587
229k
  if (!FieldType->isDependentType()) {
1588
226k
    if (RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) {
1589
1
      RD->setInvalidDecl();
1590
1
      Field->setInvalidDecl();
1591
226k
    } else {
1592
226k
      NamedDecl *Def;
1593
226k
      FieldType->isIncompleteType(&Def);
1594
226k
      if (Def && 
Def->isInvalidDecl()238
) {
1595
2
        RD->setInvalidDecl();
1596
2
        Field->setInvalidDecl();
1597
2
      }
1598
226k
    }
1599
226k
  }
1600
229k
  Field->setImplicit(true);
1601
229k
  Field->setAccess(AS_private);
1602
229k
  RD->addDecl(Field);
1603
229k
1604
229k
  if (Capture.isVLATypeCapture())
1605
5.58k
    Field->setCapturedVLAType(Capture.getCapturedVLAType());
1606
229k
1607
229k
  return Field;
1608
229k
}
1609
1610
ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1611
6.71k
                                 LambdaScopeInfo *LSI) {
1612
6.71k
  // Collect information from the lambda scope.
1613
6.71k
  SmallVector<LambdaCapture, 4> Captures;
1614
6.71k
  SmallVector<Expr *, 4> CaptureInits;
1615
6.71k
  SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
1616
6.71k
  LambdaCaptureDefault CaptureDefault =
1617
6.71k
      mapImplicitCaptureStyle(LSI->ImpCaptureStyle);
1618
6.71k
  CXXRecordDecl *Class;
1619
6.71k
  CXXMethodDecl *CallOperator;
1620
6.71k
  SourceRange IntroducerRange;
1621
6.71k
  bool ExplicitParams;
1622
6.71k
  bool ExplicitResultType;
1623
6.71k
  CleanupInfo LambdaCleanup;
1624
6.71k
  bool ContainsUnexpandedParameterPack;
1625
6.71k
  bool IsGenericLambda;
1626
6.71k
  {
1627
6.71k
    CallOperator = LSI->CallOperator;
1628
6.71k
    Class = LSI->Lambda;
1629
6.71k
    IntroducerRange = LSI->IntroducerRange;
1630
6.71k
    ExplicitParams = LSI->ExplicitParams;
1631
6.71k
    ExplicitResultType = !LSI->HasImplicitReturnType;
1632
6.71k
    LambdaCleanup = LSI->Cleanup;
1633
6.71k
    ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
1634
6.71k
    IsGenericLambda = Class->isGenericLambda();
1635
6.71k
1636
6.71k
    CallOperator->setLexicalDeclContext(Class);
1637
6.71k
    Decl *TemplateOrNonTemplateCallOperatorDecl =
1638
6.71k
        CallOperator->getDescribedFunctionTemplate()
1639
6.71k
        ? 
CallOperator->getDescribedFunctionTemplate()1.72k
1640
6.71k
        : 
cast<Decl>(CallOperator)4.98k
;
1641
6.71k
1642
6.71k
    TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1643
6.71k
    Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
1644
6.71k
1645
6.71k
    PopExpressionEvaluationContext();
1646
6.71k
1647
6.71k
    // True if the current capture has a used capture or default before it.
1648
6.71k
    bool CurHasPreviousCapture = CaptureDefault != LCD_None;
1649
6.71k
    SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
1650
3.91k
        
CaptureDefaultLoc2.79k
: IntroducerRange.getBegin();
1651
6.71k
1652
12.0k
    for (unsigned I = 0, N = LSI->Captures.size(); I != N; 
++I5.33k
) {
1653
5.34k
      const Capture &From = LSI->Captures[I];
1654
5.34k
1655
5.34k
      if (From.isInvalid())
1656
15
        return ExprError();
1657
5.33k
1658
5.33k
      assert(!From.isBlockCapture() && "Cannot capture __block variables");
1659
5.33k
      bool IsImplicit = I >= LSI->NumExplicitCaptures;
1660
5.33k
      SourceLocation ImplicitCaptureLoc =
1661
5.33k
          IsImplicit ? 
CaptureDefaultLoc3.84k
:
SourceLocation()1.48k
;
1662
5.33k
1663
5.33k
      // Use source ranges of explicit captures for fixits where available.
1664
5.33k
      SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
1665
5.33k
1666
5.33k
      // Warn about unused explicit captures.
1667
5.33k
      bool IsCaptureUsed = true;
1668
5.33k
      if (!CurContext->isDependentContext() && 
!IsImplicit4.86k
&&
1669
5.33k
          
!From.isODRUsed()1.14k
) {
1670
529
        // Initialized captures that are non-ODR used may not be eliminated.
1671
529
        // FIXME: Where did the IsGenericLambda here come from?
1672
529
        bool NonODRUsedInitCapture =
1673
529
            IsGenericLambda && 
From.isNonODRUsed()20
&&
From.isInitCapture()4
;
1674
529
        if (!NonODRUsedInitCapture) {
1675
526
          bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
1676
526
          SourceRange FixItRange;
1677
526
          if (CaptureRange.isValid()) {
1678
400
            if (!CurHasPreviousCapture && 
!IsLast335
) {
1679
67
              // If there are no captures preceding this capture, remove the
1680
67
              // following comma.
1681
67
              FixItRange = SourceRange(CaptureRange.getBegin(),
1682
67
                                       getLocForEndOfToken(CaptureRange.getEnd()));
1683
333
            } else {
1684
333
              // Otherwise, remove the comma since the last used capture.
1685
333
              FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
1686
333
                                       CaptureRange.getEnd());
1687
333
            }
1688
400
          }
1689
526
1690
526
          IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
1691
526
        }
1692
529
      }
1693
5.33k
1694
5.33k
      if (CaptureRange.isValid()) {
1695
1.15k
        CurHasPreviousCapture |= IsCaptureUsed;
1696
1.15k
        PrevCaptureLoc = CaptureRange.getEnd();
1697
1.15k
      }
1698
5.33k
1699
5.33k
      // Map the capture to our AST representation.
1700
5.33k
      LambdaCapture Capture = [&] {
1701
5.33k
        if (From.isThisCapture()) {
1702
676
          // Capturing 'this' implicitly with a default of '[=]' is deprecated,
1703
676
          // because it results in a reference capture. Don't warn prior to
1704
676
          // C++2a; there's nothing that can be done about it before then.
1705
676
          if (getLangOpts().CPlusPlus2a && 
IsImplicit31
&&
1706
676
              
CaptureDefault == LCD_ByCopy22
) {
1707
20
            Diag(From.getLocation(), diag::warn_deprecated_this_capture);
1708
20
            Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
1709
20
                << FixItHint::CreateInsertion(
1710
20
                       getLocForEndOfToken(CaptureDefaultLoc), ", this");
1711
20
          }
1712
676
          return LambdaCapture(From.getLocation(), IsImplicit,
1713
676
                               From.isCopyCapture() ? 
LCK_StarThis122
:
LCK_This554
);
1714
4.65k
        } else if (From.isVLATypeCapture()) {
1715
39
          return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
1716
4.61k
        } else {
1717
4.61k
          assert(From.isVariableCapture() && "unknown kind of capture");
1718
4.61k
          VarDecl *Var = From.getVariable();
1719
4.61k
          LambdaCaptureKind Kind =
1720
4.61k
              From.isCopyCapture() ? 
LCK_ByCopy1.09k
:
LCK_ByRef3.51k
;
1721
4.61k
          return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
1722
4.61k
                               From.getEllipsisLoc());
1723
4.61k
        }
1724
5.33k
      }();
1725
5.33k
1726
5.33k
      // Form the initializer for the capture field.
1727
5.33k
      ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
1728
5.33k
1729
5.33k
      // FIXME: Skip this capture if the capture is not used, the initializer
1730
5.33k
      // has no side-effects, the type of the capture is trivial, and the
1731
5.33k
      // lambda is not externally visible.
1732
5.33k
1733
5.33k
      // Add a FieldDecl for the capture and form its initializer.
1734
5.33k
      BuildCaptureField(Class, From);
1735
5.33k
      Captures.push_back(Capture);
1736
5.33k
      CaptureInits.push_back(Init.get());
1737
5.33k
    }
1738
6.71k
1739
6.71k
    // C++11 [expr.prim.lambda]p6:
1740
6.71k
    //   The closure type for a lambda-expression with no lambda-capture
1741
6.71k
    //   has a public non-virtual non-explicit const conversion function
1742
6.71k
    //   to pointer to function having the same parameter and return
1743
6.71k
    //   types as the closure type's function call operator.
1744
6.71k
    
if (6.69k
Captures.empty()6.69k
&&
CaptureDefault == LCD_None3.58k
)
1745
2.76k
      addFunctionPointerConversion(*this, IntroducerRange, Class,
1746
2.76k
                                   CallOperator);
1747
6.69k
1748
6.69k
    // Objective-C++:
1749
6.69k
    //   The closure type for a lambda-expression has a public non-virtual
1750
6.69k
    //   non-explicit const conversion function to a block pointer having the
1751
6.69k
    //   same parameter and return types as the closure type's function call
1752
6.69k
    //   operator.
1753
6.69k
    // FIXME: Fix generic lambda to block conversions.
1754
6.69k
    if (getLangOpts().Blocks && 
getLangOpts().ObjC3.59k
&&
!IsGenericLambda132
)
1755
126
      addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1756
6.69k
1757
6.69k
    // Finalize the lambda class.
1758
6.69k
    SmallVector<Decl*, 4> Fields(Class->fields());
1759
6.69k
    ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1760
6.69k
                SourceLocation(), ParsedAttributesView());
1761
6.69k
    CheckCompletedCXXClass(Class);
1762
6.69k
  }
1763
6.69k
1764
6.69k
  Cleanup.mergeFrom(LambdaCleanup);
1765
6.69k
1766
6.69k
  LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
1767
6.69k
                                          CaptureDefault, CaptureDefaultLoc,
1768
6.69k
                                          Captures,
1769
6.69k
                                          ExplicitParams, ExplicitResultType,
1770
6.69k
                                          CaptureInits, EndLoc,
1771
6.69k
                                          ContainsUnexpandedParameterPack);
1772
6.69k
  // If the lambda expression's call operator is not explicitly marked constexpr
1773
6.69k
  // and we are not in a dependent context, analyze the call operator to infer
1774
6.69k
  // its constexpr-ness, suppressing diagnostics while doing so.
1775
6.69k
  if (getLangOpts().CPlusPlus17 && 
!CallOperator->isInvalidDecl()1.41k
&&
1776
6.69k
      
!CallOperator->isConstexpr()1.41k
&&
1777
6.69k
      
!isa<CoroutineBodyStmt>(CallOperator->getBody())1.33k
&&
1778
6.69k
      
!Class->getDeclContext()->isDependentContext()1.33k
) {
1779
902
    TentativeAnalysisScope DiagnosticScopeGuard(*this);
1780
902
    CallOperator->setConstexprKind(
1781
902
        (CheckConstexprFunctionDecl(CallOperator) &&
1782
902
         
CheckConstexprFunctionBody(CallOperator, CallOperator->getBody())900
)
1783
902
            ? 
CSK_constexpr874
1784
902
            : 
CSK_unspecified28
);
1785
902
  }
1786
6.69k
1787
6.69k
  // Emit delayed shadowing warnings now that the full capture list is known.
1788
6.69k
  DiagnoseShadowingLambdaDecls(LSI);
1789
6.69k
1790
6.69k
  if (!CurContext->isDependentContext()) {
1791
5.17k
    switch (ExprEvalContexts.back().Context) {
1792
5.17k
    // C++11 [expr.prim.lambda]p2:
1793
5.17k
    //   A lambda-expression shall not appear in an unevaluated operand
1794
5.17k
    //   (Clause 5).
1795
5.17k
    case ExpressionEvaluationContext::Unevaluated:
1796
109
    case ExpressionEvaluationContext::UnevaluatedList:
1797
109
    case ExpressionEvaluationContext::UnevaluatedAbstract:
1798
109
    // C++1y [expr.const]p2:
1799
109
    //   A conditional-expression e is a core constant expression unless the
1800
109
    //   evaluation of e, following the rules of the abstract machine, would
1801
109
    //   evaluate [...] a lambda-expression.
1802
109
    //
1803
109
    // This is technically incorrect, there are some constant evaluated contexts
1804
109
    // where this should be allowed.  We should probably fix this when DR1607 is
1805
109
    // ratified, it lays out the exact set of conditions where we shouldn't
1806
109
    // allow a lambda-expression.
1807
109
    case ExpressionEvaluationContext::ConstantEvaluated:
1808
109
      // We don't actually diagnose this case immediately, because we
1809
109
      // could be within a context where we might find out later that
1810
109
      // the expression is potentially evaluated (e.g., for typeid).
1811
109
      ExprEvalContexts.back().Lambdas.push_back(Lambda);
1812
109
      break;
1813
109
1814
5.06k
    case ExpressionEvaluationContext::DiscardedStatement:
1815
5.06k
    case ExpressionEvaluationContext::PotentiallyEvaluated:
1816
5.06k
    case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
1817
5.06k
      break;
1818
6.69k
    }
1819
6.69k
  }
1820
6.69k
1821
6.69k
  return MaybeBindToTemporary(Lambda);
1822
6.69k
}
1823
1824
ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1825
                                               SourceLocation ConvLocation,
1826
                                               CXXConversionDecl *Conv,
1827
31
                                               Expr *Src) {
1828
31
  // Make sure that the lambda call operator is marked used.
1829
31
  CXXRecordDecl *Lambda = Conv->getParent();
1830
31
  CXXMethodDecl *CallOperator
1831
31
    = cast<CXXMethodDecl>(
1832
31
        Lambda->lookup(
1833
31
          Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
1834
31
  CallOperator->setReferenced();
1835
31
  CallOperator->markUsed(Context);
1836
31
1837
31
  ExprResult Init = PerformCopyInitialization(
1838
31
      InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType(),
1839
31
                                                 /*NRVO=*/false),
1840
31
      CurrentLocation, Src);
1841
31
  if (!Init.isInvalid())
1842
31
    Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
1843
31
1844
31
  if (Init.isInvalid())
1845
0
    return ExprError();
1846
31
1847
31
  // Create the new block to be returned.
1848
31
  BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1849
31
1850
31
  // Set the type information.
1851
31
  Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1852
31
  Block->setIsVariadic(CallOperator->isVariadic());
1853
31
  Block->setBlockMissingReturnType(false);
1854
31
1855
31
  // Add parameters.
1856
31
  SmallVector<ParmVarDecl *, 4> BlockParams;
1857
42
  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; 
++I11
) {
1858
11
    ParmVarDecl *From = CallOperator->getParamDecl(I);
1859
11
    BlockParams.push_back(ParmVarDecl::Create(
1860
11
        Context, Block, From->getBeginLoc(), From->getLocation(),
1861
11
        From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
1862
11
        From->getStorageClass(),
1863
11
        /*DefArg=*/nullptr));
1864
11
  }
1865
31
  Block->setParams(BlockParams);
1866
31
1867
31
  Block->setIsConversionFromLambda(true);
1868
31
1869
31
  // Add capture. The capture uses a fake variable, which doesn't correspond
1870
31
  // to any actual memory location. However, the initializer copy-initializes
1871
31
  // the lambda object.
1872
31
  TypeSourceInfo *CapVarTSI =
1873
31
      Context.getTrivialTypeSourceInfo(Src->getType());
1874
31
  VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1875
31
                                    ConvLocation, nullptr,
1876
31
                                    Src->getType(), CapVarTSI,
1877
31
                                    SC_None);
1878
31
  BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
1879
31
                             /*nested=*/false, /*copy=*/Init.get());
1880
31
  Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
1881
31
1882
31
  // Add a fake function body to the block. IR generation is responsible
1883
31
  // for filling in the actual body, which cannot be expressed as an AST.
1884
31
  Block->setBody(new (Context) CompoundStmt(ConvLocation));
1885
31
1886
31
  // Create the block literal expression.
1887
31
  Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1888
31
  ExprCleanupObjects.push_back(Block);
1889
31
  Cleanup.setExprNeedsCleanups(true);
1890
31
1891
31
  return BuildBlock;
1892
31
}