2012-02-09 05:18:48 +08:00
|
|
|
//===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
|
|
|
|
//
|
|
|
|
// The LLVM Compiler Infrastructure
|
|
|
|
//
|
|
|
|
// This file is distributed under the University of Illinois Open Source
|
|
|
|
// License. See LICENSE.TXT for details.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//
|
|
|
|
// This file implements semantic analysis for C++ lambda expressions.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
#include "clang/Sema/DeclSpec.h"
|
2014-01-07 19:51:46 +08:00
|
|
|
#include "TypeLocBuilder.h"
|
Implement a rudimentary form of generic lambdas.
Specifically, the following features are not included in this commit:
- any sort of capturing within generic lambdas
- generic lambdas within template functions and nested
within other generic lambdas
- conversion operator for captureless lambdas
- ensuring all visitors are generic lambda aware
(Although I have gotten some useful feedback on my patches of the above and will be incorporating that as I submit those patches for commit)
As an example of what compiles through this commit:
template <class F1, class F2>
struct overload : F1, F2 {
using F1::operator();
using F2::operator();
overload(F1 f1, F2 f2) : F1(f1), F2(f2) { }
};
auto Recursive = [](auto Self, auto h, auto ... rest) {
return 1 + Self(Self, rest...);
};
auto Base = [](auto Self, auto h) {
return 1;
};
overload<decltype(Base), decltype(Recursive)> O(Base, Recursive);
int num_params = O(O, 5, 3, "abc", 3.14, 'a');
Please see attached tests for more examples.
This patch has been reviewed by Doug and Richard. Minor changes (non-functionality affecting) have been made since both of them formally looked at it, but the changes involve removal of supernumerary return type deduction changes (since they are now redundant, with richard having committed a recent patch to address return type deduction for C++11 lambdas using C++14 semantics).
Some implementation notes:
- Add a new Declarator context => LambdaExprParameterContext to
clang::Declarator to allow the use of 'auto' in declaring generic
lambda parameters
- Add various helpers to CXXRecordDecl to facilitate identifying
and querying a closure class
- LambdaScopeInfo (which maintains the current lambda's Sema state)
was augmented to house the current depth of the template being
parsed (id est the Parser calls Sema::RecordParsingTemplateParameterDepth)
so that SemaType.cpp::ConvertDeclSpecToType may use it to immediately
generate a template-parameter-type when 'auto' is parsed in a generic
lambda parameter context. (i.e we do NOT use AutoType deduced to
a template parameter type - Richard seemed ok with this approach).
We encode that this template type was generated from an auto by simply
adding $auto to the name which can be used for better diagnostics if needed.
- SemaLambda.h was added to hold some common lambda utility
functions (this file is likely to grow ...)
- Teach Sema::ActOnStartOfFunctionDef to check whether it
is being called to instantiate a generic lambda's call
operator, and if so, push an appropriately prepared
LambdaScopeInfo object on the stack.
- various tests were added - but much more will be needed.
There is obviously more work to be done, and both Richard (weakly) and Doug (strongly)
have requested that LambdaExpr be removed form the CXXRecordDecl LambdaDefinitionaData
in a future patch which is forthcoming.
A greatful thanks to all reviewers including Eli Friedman, James Dennett,
and especially the two gracious wizards (Richard Smith and Doug Gregor)
who spent hours providing feedback (in person in Chicago and on the mailing lists).
And yet I am certain that I have allowed unidentified bugs to creep in; bugs, that I will do my best to slay, once identified!
Thanks!
llvm-svn: 191453
2013-09-27 03:54:12 +08:00
|
|
|
#include "clang/AST/ASTLambda.h"
|
2012-12-04 17:13:33 +08:00
|
|
|
#include "clang/AST/ExprCXX.h"
|
2013-09-11 04:14:30 +08:00
|
|
|
#include "clang/Basic/TargetInfo.h"
|
2012-02-09 05:18:48 +08:00
|
|
|
#include "clang/Sema/Initialization.h"
|
|
|
|
#include "clang/Sema/Lookup.h"
|
2012-02-21 12:17:39 +08:00
|
|
|
#include "clang/Sema/Scope.h"
|
2012-02-09 05:18:48 +08:00
|
|
|
#include "clang/Sema/ScopeInfo.h"
|
|
|
|
#include "clang/Sema/SemaInternal.h"
|
This patch implements capturing of variables within generic lambdas.
Both Richard and I felt that the current wording in the working paper needed some tweaking - Please see http://llvm-reviews.chandlerc.com/D2035 for additional context and references to core-reflector messages that discuss wording tweaks.
What is implemented is what we had intended to specify in Bristol; but, recently felt that the specification might benefit from some tweaking and fleshing.
As a rough attempt to explain the semantics: If a nested lambda with a default-capture names a variable within its body, and if the enclosing full expression that contains the name of that variable is instantiation-dependent - then an enclosing lambda that is capture-ready (i.e. within a non-dependent context) must capture that variable, if all intervening nested lambdas can potentially capture that variable if they need to, and all intervening parent lambdas of the capture-ready lambda can and do capture the variable.
Of note, 'this' capturing is also currently underspecified in the working paper for generic lambdas. What is implemented here is if the set of candidate functions in a nested generic lambda includes both static and non-static member functions (regardless of viability checking - i.e. num and type of parameters/arguments) - and if all intervening nested-inner lambdas between the capture-ready lambda and the function-call containing nested lambda can capture 'this' and if all enclosing lambdas of the capture-ready lambda can capture 'this', then 'this' is speculatively captured by that capture-ready lambda.
Hopefully a paper for the C++ committee (that Richard and I had started some preliminary work on) is forthcoming.
This essentially makes generic lambdas feature complete, except for known bugs. The more prominent ones (and the ones I am currently aware of) being:
- generic lambdas and init-captures are broken - but a patch that fixes this is already in the works ...
- nested variadic expansions such as:
auto K = [](auto ... OuterArgs) {
vp([=](auto ... Is) {
decltype(OuterArgs) OA = OuterArgs;
return 0;
}(5)...);
return 0;
};
auto M = K('a', ' ', 1, " -- ", 3.14);
currently cause crashes. I think I know how to fix this (since I had done so in my initial implementation) - but it will probably take some work and back & forth with Doug and Richard.
A warm thanks to all who provided feedback - and especially to Doug Gregor and Richard Smith for their pivotal guidance: their insight and prestidigitation in such matters is boundless!
Now let's hope this commit doesn't upset the buildbot gods ;)
Thanks!
llvm-svn: 194188
2013-11-07 13:17:06 +08:00
|
|
|
#include "clang/Sema/SemaLambda.h"
|
2012-02-09 05:18:48 +08:00
|
|
|
using namespace clang;
|
|
|
|
using namespace sema;
|
|
|
|
|
2018-05-09 09:00:01 +08:00
|
|
|
/// Examines the FunctionScopeInfo stack to determine the nearest
|
2018-07-31 03:24:48 +08:00
|
|
|
/// enclosing lambda (to the current lambda) that is 'capture-ready' for
|
2013-12-08 04:22:44 +08:00
|
|
|
/// the variable referenced in the current lambda (i.e. \p VarToCapture).
|
|
|
|
/// If successful, returns the index into Sema's FunctionScopeInfo stack
|
|
|
|
/// of the capture-ready lambda's LambdaScopeInfo.
|
2018-07-31 03:24:48 +08:00
|
|
|
///
|
|
|
|
/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
|
2013-12-08 04:22:44 +08:00
|
|
|
/// lambda - is on top) to determine the index of the nearest enclosing/outer
|
2018-07-31 03:24:48 +08:00
|
|
|
/// lambda that is ready to capture the \p VarToCapture being referenced in
|
|
|
|
/// the current lambda.
|
2013-12-08 04:22:44 +08:00
|
|
|
/// As we climb down the stack, we want the index of the first such lambda -
|
2018-07-31 03:24:48 +08:00
|
|
|
/// that is the lambda with the highest index that is 'capture-ready'.
|
|
|
|
///
|
2013-12-08 04:22:44 +08:00
|
|
|
/// A lambda 'L' is capture-ready for 'V' (var or this) if:
|
|
|
|
/// - its enclosing context is non-dependent
|
|
|
|
/// - and if the chain of lambdas between L and the lambda in which
|
2018-07-31 03:24:48 +08:00
|
|
|
/// V is potentially used (i.e. the lambda at the top of the scope info
|
2013-12-08 04:22:44 +08:00
|
|
|
/// stack), can all capture or have already captured V.
|
|
|
|
/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
|
2018-07-31 03:24:48 +08:00
|
|
|
///
|
2013-12-08 04:22:44 +08:00
|
|
|
/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
|
|
|
|
/// for whether it is 'capture-capable' (see
|
2018-07-31 03:24:48 +08:00
|
|
|
/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
|
2013-12-08 04:22:44 +08:00
|
|
|
/// capture.
|
|
|
|
///
|
|
|
|
/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
|
|
|
|
/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
|
|
|
|
/// is at the top of the stack and has the highest index.
|
|
|
|
/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
|
|
|
|
///
|
|
|
|
/// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
|
|
|
|
/// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
|
|
|
|
/// which is capture-ready. If the return value evaluates to 'false' then
|
|
|
|
/// no lambda is capture-ready for \p VarToCapture.
|
|
|
|
|
|
|
|
static inline Optional<unsigned>
|
|
|
|
getStackIndexOfNearestEnclosingCaptureReadyLambda(
|
|
|
|
ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
|
|
|
|
VarDecl *VarToCapture) {
|
|
|
|
// Label failure to capture.
|
|
|
|
const Optional<unsigned> NoLambdaIsCaptureReady;
|
|
|
|
|
2016-11-11 20:36:20 +08:00
|
|
|
// Ignore all inner captured regions.
|
|
|
|
unsigned CurScopeIndex = FunctionScopes.size() - 1;
|
|
|
|
while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
|
|
|
|
FunctionScopes[CurScopeIndex]))
|
|
|
|
--CurScopeIndex;
|
2013-12-08 04:22:44 +08:00
|
|
|
assert(
|
2016-11-11 20:36:20 +08:00
|
|
|
isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
|
2013-12-08 04:22:44 +08:00
|
|
|
"The function on the top of sema's function-info stack must be a lambda");
|
2016-11-11 20:36:20 +08:00
|
|
|
|
2013-12-08 04:22:44 +08:00
|
|
|
// If VarToCapture is null, we are attempting to capture 'this'.
|
|
|
|
const bool IsCapturingThis = !VarToCapture;
|
This patch implements capturing of variables within generic lambdas.
Both Richard and I felt that the current wording in the working paper needed some tweaking - Please see http://llvm-reviews.chandlerc.com/D2035 for additional context and references to core-reflector messages that discuss wording tweaks.
What is implemented is what we had intended to specify in Bristol; but, recently felt that the specification might benefit from some tweaking and fleshing.
As a rough attempt to explain the semantics: If a nested lambda with a default-capture names a variable within its body, and if the enclosing full expression that contains the name of that variable is instantiation-dependent - then an enclosing lambda that is capture-ready (i.e. within a non-dependent context) must capture that variable, if all intervening nested lambdas can potentially capture that variable if they need to, and all intervening parent lambdas of the capture-ready lambda can and do capture the variable.
Of note, 'this' capturing is also currently underspecified in the working paper for generic lambdas. What is implemented here is if the set of candidate functions in a nested generic lambda includes both static and non-static member functions (regardless of viability checking - i.e. num and type of parameters/arguments) - and if all intervening nested-inner lambdas between the capture-ready lambda and the function-call containing nested lambda can capture 'this' and if all enclosing lambdas of the capture-ready lambda can capture 'this', then 'this' is speculatively captured by that capture-ready lambda.
Hopefully a paper for the C++ committee (that Richard and I had started some preliminary work on) is forthcoming.
This essentially makes generic lambdas feature complete, except for known bugs. The more prominent ones (and the ones I am currently aware of) being:
- generic lambdas and init-captures are broken - but a patch that fixes this is already in the works ...
- nested variadic expansions such as:
auto K = [](auto ... OuterArgs) {
vp([=](auto ... Is) {
decltype(OuterArgs) OA = OuterArgs;
return 0;
}(5)...);
return 0;
};
auto M = K('a', ' ', 1, " -- ", 3.14);
currently cause crashes. I think I know how to fix this (since I had done so in my initial implementation) - but it will probably take some work and back & forth with Doug and Richard.
A warm thanks to all who provided feedback - and especially to Doug Gregor and Richard Smith for their pivotal guidance: their insight and prestidigitation in such matters is boundless!
Now let's hope this commit doesn't upset the buildbot gods ;)
Thanks!
llvm-svn: 194188
2013-11-07 13:17:06 +08:00
|
|
|
const bool IsCapturingVariable = !IsCapturingThis;
|
2013-12-08 04:22:44 +08:00
|
|
|
|
|
|
|
// Start with the current lambda at the top of the stack (highest index).
|
|
|
|
DeclContext *EnclosingDC =
|
|
|
|
cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
|
|
|
|
|
|
|
|
do {
|
|
|
|
const clang::sema::LambdaScopeInfo *LSI =
|
|
|
|
cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
|
|
|
|
// IF we have climbed down to an intervening enclosing lambda that contains
|
|
|
|
// the variable declaration - it obviously can/must not capture the
|
|
|
|
// variable.
|
|
|
|
// Since its enclosing DC is dependent, all the lambdas between it and the
|
|
|
|
// innermost nested lambda are dependent (otherwise we wouldn't have
|
|
|
|
// arrived here) - so we don't yet have a lambda that can capture the
|
This patch implements capturing of variables within generic lambdas.
Both Richard and I felt that the current wording in the working paper needed some tweaking - Please see http://llvm-reviews.chandlerc.com/D2035 for additional context and references to core-reflector messages that discuss wording tweaks.
What is implemented is what we had intended to specify in Bristol; but, recently felt that the specification might benefit from some tweaking and fleshing.
As a rough attempt to explain the semantics: If a nested lambda with a default-capture names a variable within its body, and if the enclosing full expression that contains the name of that variable is instantiation-dependent - then an enclosing lambda that is capture-ready (i.e. within a non-dependent context) must capture that variable, if all intervening nested lambdas can potentially capture that variable if they need to, and all intervening parent lambdas of the capture-ready lambda can and do capture the variable.
Of note, 'this' capturing is also currently underspecified in the working paper for generic lambdas. What is implemented here is if the set of candidate functions in a nested generic lambda includes both static and non-static member functions (regardless of viability checking - i.e. num and type of parameters/arguments) - and if all intervening nested-inner lambdas between the capture-ready lambda and the function-call containing nested lambda can capture 'this' and if all enclosing lambdas of the capture-ready lambda can capture 'this', then 'this' is speculatively captured by that capture-ready lambda.
Hopefully a paper for the C++ committee (that Richard and I had started some preliminary work on) is forthcoming.
This essentially makes generic lambdas feature complete, except for known bugs. The more prominent ones (and the ones I am currently aware of) being:
- generic lambdas and init-captures are broken - but a patch that fixes this is already in the works ...
- nested variadic expansions such as:
auto K = [](auto ... OuterArgs) {
vp([=](auto ... Is) {
decltype(OuterArgs) OA = OuterArgs;
return 0;
}(5)...);
return 0;
};
auto M = K('a', ' ', 1, " -- ", 3.14);
currently cause crashes. I think I know how to fix this (since I had done so in my initial implementation) - but it will probably take some work and back & forth with Doug and Richard.
A warm thanks to all who provided feedback - and especially to Doug Gregor and Richard Smith for their pivotal guidance: their insight and prestidigitation in such matters is boundless!
Now let's hope this commit doesn't upset the buildbot gods ;)
Thanks!
llvm-svn: 194188
2013-11-07 13:17:06 +08:00
|
|
|
// variable.
|
2013-12-08 04:22:44 +08:00
|
|
|
if (IsCapturingVariable &&
|
|
|
|
VarToCapture->getDeclContext()->Equals(EnclosingDC))
|
|
|
|
return NoLambdaIsCaptureReady;
|
|
|
|
|
|
|
|
// For an enclosing lambda to be capture ready for an entity, all
|
|
|
|
// intervening lambda's have to be able to capture that entity. If even
|
|
|
|
// one of the intervening lambda's is not capable of capturing the entity
|
|
|
|
// then no enclosing lambda can ever capture that entity.
|
|
|
|
// For e.g.
|
|
|
|
// const int x = 10;
|
|
|
|
// [=](auto a) { #1
|
|
|
|
// [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
|
|
|
|
// [=](auto c) { #3
|
|
|
|
// f(x, c); <-- can not lead to x's speculative capture by #1 or #2
|
|
|
|
// }; }; };
|
This patch implements capturing of variables within generic lambdas.
Both Richard and I felt that the current wording in the working paper needed some tweaking - Please see http://llvm-reviews.chandlerc.com/D2035 for additional context and references to core-reflector messages that discuss wording tweaks.
What is implemented is what we had intended to specify in Bristol; but, recently felt that the specification might benefit from some tweaking and fleshing.
As a rough attempt to explain the semantics: If a nested lambda with a default-capture names a variable within its body, and if the enclosing full expression that contains the name of that variable is instantiation-dependent - then an enclosing lambda that is capture-ready (i.e. within a non-dependent context) must capture that variable, if all intervening nested lambdas can potentially capture that variable if they need to, and all intervening parent lambdas of the capture-ready lambda can and do capture the variable.
Of note, 'this' capturing is also currently underspecified in the working paper for generic lambdas. What is implemented here is if the set of candidate functions in a nested generic lambda includes both static and non-static member functions (regardless of viability checking - i.e. num and type of parameters/arguments) - and if all intervening nested-inner lambdas between the capture-ready lambda and the function-call containing nested lambda can capture 'this' and if all enclosing lambdas of the capture-ready lambda can capture 'this', then 'this' is speculatively captured by that capture-ready lambda.
Hopefully a paper for the C++ committee (that Richard and I had started some preliminary work on) is forthcoming.
This essentially makes generic lambdas feature complete, except for known bugs. The more prominent ones (and the ones I am currently aware of) being:
- generic lambdas and init-captures are broken - but a patch that fixes this is already in the works ...
- nested variadic expansions such as:
auto K = [](auto ... OuterArgs) {
vp([=](auto ... Is) {
decltype(OuterArgs) OA = OuterArgs;
return 0;
}(5)...);
return 0;
};
auto M = K('a', ' ', 1, " -- ", 3.14);
currently cause crashes. I think I know how to fix this (since I had done so in my initial implementation) - but it will probably take some work and back & forth with Doug and Richard.
A warm thanks to all who provided feedback - and especially to Doug Gregor and Richard Smith for their pivotal guidance: their insight and prestidigitation in such matters is boundless!
Now let's hope this commit doesn't upset the buildbot gods ;)
Thanks!
llvm-svn: 194188
2013-11-07 13:17:06 +08:00
|
|
|
// If they do not have a default implicit capture, check to see
|
|
|
|
// if the entity has already been explicitly captured.
|
2013-12-08 04:22:44 +08:00
|
|
|
// If even a single dependent enclosing lambda lacks the capability
|
|
|
|
// to ever capture this variable, there is no further enclosing
|
This patch implements capturing of variables within generic lambdas.
Both Richard and I felt that the current wording in the working paper needed some tweaking - Please see http://llvm-reviews.chandlerc.com/D2035 for additional context and references to core-reflector messages that discuss wording tweaks.
What is implemented is what we had intended to specify in Bristol; but, recently felt that the specification might benefit from some tweaking and fleshing.
As a rough attempt to explain the semantics: If a nested lambda with a default-capture names a variable within its body, and if the enclosing full expression that contains the name of that variable is instantiation-dependent - then an enclosing lambda that is capture-ready (i.e. within a non-dependent context) must capture that variable, if all intervening nested lambdas can potentially capture that variable if they need to, and all intervening parent lambdas of the capture-ready lambda can and do capture the variable.
Of note, 'this' capturing is also currently underspecified in the working paper for generic lambdas. What is implemented here is if the set of candidate functions in a nested generic lambda includes both static and non-static member functions (regardless of viability checking - i.e. num and type of parameters/arguments) - and if all intervening nested-inner lambdas between the capture-ready lambda and the function-call containing nested lambda can capture 'this' and if all enclosing lambdas of the capture-ready lambda can capture 'this', then 'this' is speculatively captured by that capture-ready lambda.
Hopefully a paper for the C++ committee (that Richard and I had started some preliminary work on) is forthcoming.
This essentially makes generic lambdas feature complete, except for known bugs. The more prominent ones (and the ones I am currently aware of) being:
- generic lambdas and init-captures are broken - but a patch that fixes this is already in the works ...
- nested variadic expansions such as:
auto K = [](auto ... OuterArgs) {
vp([=](auto ... Is) {
decltype(OuterArgs) OA = OuterArgs;
return 0;
}(5)...);
return 0;
};
auto M = K('a', ' ', 1, " -- ", 3.14);
currently cause crashes. I think I know how to fix this (since I had done so in my initial implementation) - but it will probably take some work and back & forth with Doug and Richard.
A warm thanks to all who provided feedback - and especially to Doug Gregor and Richard Smith for their pivotal guidance: their insight and prestidigitation in such matters is boundless!
Now let's hope this commit doesn't upset the buildbot gods ;)
Thanks!
llvm-svn: 194188
2013-11-07 13:17:06 +08:00
|
|
|
// non-dependent lambda that can capture this variable.
|
|
|
|
if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
|
2013-12-08 04:22:44 +08:00
|
|
|
if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
|
|
|
|
return NoLambdaIsCaptureReady;
|
This patch implements capturing of variables within generic lambdas.
Both Richard and I felt that the current wording in the working paper needed some tweaking - Please see http://llvm-reviews.chandlerc.com/D2035 for additional context and references to core-reflector messages that discuss wording tweaks.
What is implemented is what we had intended to specify in Bristol; but, recently felt that the specification might benefit from some tweaking and fleshing.
As a rough attempt to explain the semantics: If a nested lambda with a default-capture names a variable within its body, and if the enclosing full expression that contains the name of that variable is instantiation-dependent - then an enclosing lambda that is capture-ready (i.e. within a non-dependent context) must capture that variable, if all intervening nested lambdas can potentially capture that variable if they need to, and all intervening parent lambdas of the capture-ready lambda can and do capture the variable.
Of note, 'this' capturing is also currently underspecified in the working paper for generic lambdas. What is implemented here is if the set of candidate functions in a nested generic lambda includes both static and non-static member functions (regardless of viability checking - i.e. num and type of parameters/arguments) - and if all intervening nested-inner lambdas between the capture-ready lambda and the function-call containing nested lambda can capture 'this' and if all enclosing lambdas of the capture-ready lambda can capture 'this', then 'this' is speculatively captured by that capture-ready lambda.
Hopefully a paper for the C++ committee (that Richard and I had started some preliminary work on) is forthcoming.
This essentially makes generic lambdas feature complete, except for known bugs. The more prominent ones (and the ones I am currently aware of) being:
- generic lambdas and init-captures are broken - but a patch that fixes this is already in the works ...
- nested variadic expansions such as:
auto K = [](auto ... OuterArgs) {
vp([=](auto ... Is) {
decltype(OuterArgs) OA = OuterArgs;
return 0;
}(5)...);
return 0;
};
auto M = K('a', ' ', 1, " -- ", 3.14);
currently cause crashes. I think I know how to fix this (since I had done so in my initial implementation) - but it will probably take some work and back & forth with Doug and Richard.
A warm thanks to all who provided feedback - and especially to Doug Gregor and Richard Smith for their pivotal guidance: their insight and prestidigitation in such matters is boundless!
Now let's hope this commit doesn't upset the buildbot gods ;)
Thanks!
llvm-svn: 194188
2013-11-07 13:17:06 +08:00
|
|
|
if (IsCapturingThis && !LSI->isCXXThisCaptured())
|
2013-12-08 04:22:44 +08:00
|
|
|
return NoLambdaIsCaptureReady;
|
This patch implements capturing of variables within generic lambdas.
Both Richard and I felt that the current wording in the working paper needed some tweaking - Please see http://llvm-reviews.chandlerc.com/D2035 for additional context and references to core-reflector messages that discuss wording tweaks.
What is implemented is what we had intended to specify in Bristol; but, recently felt that the specification might benefit from some tweaking and fleshing.
As a rough attempt to explain the semantics: If a nested lambda with a default-capture names a variable within its body, and if the enclosing full expression that contains the name of that variable is instantiation-dependent - then an enclosing lambda that is capture-ready (i.e. within a non-dependent context) must capture that variable, if all intervening nested lambdas can potentially capture that variable if they need to, and all intervening parent lambdas of the capture-ready lambda can and do capture the variable.
Of note, 'this' capturing is also currently underspecified in the working paper for generic lambdas. What is implemented here is if the set of candidate functions in a nested generic lambda includes both static and non-static member functions (regardless of viability checking - i.e. num and type of parameters/arguments) - and if all intervening nested-inner lambdas between the capture-ready lambda and the function-call containing nested lambda can capture 'this' and if all enclosing lambdas of the capture-ready lambda can capture 'this', then 'this' is speculatively captured by that capture-ready lambda.
Hopefully a paper for the C++ committee (that Richard and I had started some preliminary work on) is forthcoming.
This essentially makes generic lambdas feature complete, except for known bugs. The more prominent ones (and the ones I am currently aware of) being:
- generic lambdas and init-captures are broken - but a patch that fixes this is already in the works ...
- nested variadic expansions such as:
auto K = [](auto ... OuterArgs) {
vp([=](auto ... Is) {
decltype(OuterArgs) OA = OuterArgs;
return 0;
}(5)...);
return 0;
};
auto M = K('a', ' ', 1, " -- ", 3.14);
currently cause crashes. I think I know how to fix this (since I had done so in my initial implementation) - but it will probably take some work and back & forth with Doug and Richard.
A warm thanks to all who provided feedback - and especially to Doug Gregor and Richard Smith for their pivotal guidance: their insight and prestidigitation in such matters is boundless!
Now let's hope this commit doesn't upset the buildbot gods ;)
Thanks!
llvm-svn: 194188
2013-11-07 13:17:06 +08:00
|
|
|
}
|
|
|
|
EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
|
2018-07-31 03:24:48 +08:00
|
|
|
|
2013-12-08 04:22:44 +08:00
|
|
|
assert(CurScopeIndex);
|
This patch implements capturing of variables within generic lambdas.
Both Richard and I felt that the current wording in the working paper needed some tweaking - Please see http://llvm-reviews.chandlerc.com/D2035 for additional context and references to core-reflector messages that discuss wording tweaks.
What is implemented is what we had intended to specify in Bristol; but, recently felt that the specification might benefit from some tweaking and fleshing.
As a rough attempt to explain the semantics: If a nested lambda with a default-capture names a variable within its body, and if the enclosing full expression that contains the name of that variable is instantiation-dependent - then an enclosing lambda that is capture-ready (i.e. within a non-dependent context) must capture that variable, if all intervening nested lambdas can potentially capture that variable if they need to, and all intervening parent lambdas of the capture-ready lambda can and do capture the variable.
Of note, 'this' capturing is also currently underspecified in the working paper for generic lambdas. What is implemented here is if the set of candidate functions in a nested generic lambda includes both static and non-static member functions (regardless of viability checking - i.e. num and type of parameters/arguments) - and if all intervening nested-inner lambdas between the capture-ready lambda and the function-call containing nested lambda can capture 'this' and if all enclosing lambdas of the capture-ready lambda can capture 'this', then 'this' is speculatively captured by that capture-ready lambda.
Hopefully a paper for the C++ committee (that Richard and I had started some preliminary work on) is forthcoming.
This essentially makes generic lambdas feature complete, except for known bugs. The more prominent ones (and the ones I am currently aware of) being:
- generic lambdas and init-captures are broken - but a patch that fixes this is already in the works ...
- nested variadic expansions such as:
auto K = [](auto ... OuterArgs) {
vp([=](auto ... Is) {
decltype(OuterArgs) OA = OuterArgs;
return 0;
}(5)...);
return 0;
};
auto M = K('a', ' ', 1, " -- ", 3.14);
currently cause crashes. I think I know how to fix this (since I had done so in my initial implementation) - but it will probably take some work and back & forth with Doug and Richard.
A warm thanks to all who provided feedback - and especially to Doug Gregor and Richard Smith for their pivotal guidance: their insight and prestidigitation in such matters is boundless!
Now let's hope this commit doesn't upset the buildbot gods ;)
Thanks!
llvm-svn: 194188
2013-11-07 13:17:06 +08:00
|
|
|
--CurScopeIndex;
|
2013-12-08 04:22:44 +08:00
|
|
|
} while (!EnclosingDC->isTranslationUnit() &&
|
|
|
|
EnclosingDC->isDependentContext() &&
|
|
|
|
isLambdaCallOperator(EnclosingDC));
|
|
|
|
|
|
|
|
assert(CurScopeIndex < (FunctionScopes.size() - 1));
|
This patch implements capturing of variables within generic lambdas.
Both Richard and I felt that the current wording in the working paper needed some tweaking - Please see http://llvm-reviews.chandlerc.com/D2035 for additional context and references to core-reflector messages that discuss wording tweaks.
What is implemented is what we had intended to specify in Bristol; but, recently felt that the specification might benefit from some tweaking and fleshing.
As a rough attempt to explain the semantics: If a nested lambda with a default-capture names a variable within its body, and if the enclosing full expression that contains the name of that variable is instantiation-dependent - then an enclosing lambda that is capture-ready (i.e. within a non-dependent context) must capture that variable, if all intervening nested lambdas can potentially capture that variable if they need to, and all intervening parent lambdas of the capture-ready lambda can and do capture the variable.
Of note, 'this' capturing is also currently underspecified in the working paper for generic lambdas. What is implemented here is if the set of candidate functions in a nested generic lambda includes both static and non-static member functions (regardless of viability checking - i.e. num and type of parameters/arguments) - and if all intervening nested-inner lambdas between the capture-ready lambda and the function-call containing nested lambda can capture 'this' and if all enclosing lambdas of the capture-ready lambda can capture 'this', then 'this' is speculatively captured by that capture-ready lambda.
Hopefully a paper for the C++ committee (that Richard and I had started some preliminary work on) is forthcoming.
This essentially makes generic lambdas feature complete, except for known bugs. The more prominent ones (and the ones I am currently aware of) being:
- generic lambdas and init-captures are broken - but a patch that fixes this is already in the works ...
- nested variadic expansions such as:
auto K = [](auto ... OuterArgs) {
vp([=](auto ... Is) {
decltype(OuterArgs) OA = OuterArgs;
return 0;
}(5)...);
return 0;
};
auto M = K('a', ' ', 1, " -- ", 3.14);
currently cause crashes. I think I know how to fix this (since I had done so in my initial implementation) - but it will probably take some work and back & forth with Doug and Richard.
A warm thanks to all who provided feedback - and especially to Doug Gregor and Richard Smith for their pivotal guidance: their insight and prestidigitation in such matters is boundless!
Now let's hope this commit doesn't upset the buildbot gods ;)
Thanks!
llvm-svn: 194188
2013-11-07 13:17:06 +08:00
|
|
|
// If the enclosingDC is not dependent, then the immediately nested lambda
|
2013-12-08 04:22:44 +08:00
|
|
|
// (one index above) is capture-ready.
|
This patch implements capturing of variables within generic lambdas.
Both Richard and I felt that the current wording in the working paper needed some tweaking - Please see http://llvm-reviews.chandlerc.com/D2035 for additional context and references to core-reflector messages that discuss wording tweaks.
What is implemented is what we had intended to specify in Bristol; but, recently felt that the specification might benefit from some tweaking and fleshing.
As a rough attempt to explain the semantics: If a nested lambda with a default-capture names a variable within its body, and if the enclosing full expression that contains the name of that variable is instantiation-dependent - then an enclosing lambda that is capture-ready (i.e. within a non-dependent context) must capture that variable, if all intervening nested lambdas can potentially capture that variable if they need to, and all intervening parent lambdas of the capture-ready lambda can and do capture the variable.
Of note, 'this' capturing is also currently underspecified in the working paper for generic lambdas. What is implemented here is if the set of candidate functions in a nested generic lambda includes both static and non-static member functions (regardless of viability checking - i.e. num and type of parameters/arguments) - and if all intervening nested-inner lambdas between the capture-ready lambda and the function-call containing nested lambda can capture 'this' and if all enclosing lambdas of the capture-ready lambda can capture 'this', then 'this' is speculatively captured by that capture-ready lambda.
Hopefully a paper for the C++ committee (that Richard and I had started some preliminary work on) is forthcoming.
This essentially makes generic lambdas feature complete, except for known bugs. The more prominent ones (and the ones I am currently aware of) being:
- generic lambdas and init-captures are broken - but a patch that fixes this is already in the works ...
- nested variadic expansions such as:
auto K = [](auto ... OuterArgs) {
vp([=](auto ... Is) {
decltype(OuterArgs) OA = OuterArgs;
return 0;
}(5)...);
return 0;
};
auto M = K('a', ' ', 1, " -- ", 3.14);
currently cause crashes. I think I know how to fix this (since I had done so in my initial implementation) - but it will probably take some work and back & forth with Doug and Richard.
A warm thanks to all who provided feedback - and especially to Doug Gregor and Richard Smith for their pivotal guidance: their insight and prestidigitation in such matters is boundless!
Now let's hope this commit doesn't upset the buildbot gods ;)
Thanks!
llvm-svn: 194188
2013-11-07 13:17:06 +08:00
|
|
|
if (!EnclosingDC->isDependentContext())
|
2013-12-08 04:22:44 +08:00
|
|
|
return CurScopeIndex + 1;
|
|
|
|
return NoLambdaIsCaptureReady;
|
This patch implements capturing of variables within generic lambdas.
Both Richard and I felt that the current wording in the working paper needed some tweaking - Please see http://llvm-reviews.chandlerc.com/D2035 for additional context and references to core-reflector messages that discuss wording tweaks.
What is implemented is what we had intended to specify in Bristol; but, recently felt that the specification might benefit from some tweaking and fleshing.
As a rough attempt to explain the semantics: If a nested lambda with a default-capture names a variable within its body, and if the enclosing full expression that contains the name of that variable is instantiation-dependent - then an enclosing lambda that is capture-ready (i.e. within a non-dependent context) must capture that variable, if all intervening nested lambdas can potentially capture that variable if they need to, and all intervening parent lambdas of the capture-ready lambda can and do capture the variable.
Of note, 'this' capturing is also currently underspecified in the working paper for generic lambdas. What is implemented here is if the set of candidate functions in a nested generic lambda includes both static and non-static member functions (regardless of viability checking - i.e. num and type of parameters/arguments) - and if all intervening nested-inner lambdas between the capture-ready lambda and the function-call containing nested lambda can capture 'this' and if all enclosing lambdas of the capture-ready lambda can capture 'this', then 'this' is speculatively captured by that capture-ready lambda.
Hopefully a paper for the C++ committee (that Richard and I had started some preliminary work on) is forthcoming.
This essentially makes generic lambdas feature complete, except for known bugs. The more prominent ones (and the ones I am currently aware of) being:
- generic lambdas and init-captures are broken - but a patch that fixes this is already in the works ...
- nested variadic expansions such as:
auto K = [](auto ... OuterArgs) {
vp([=](auto ... Is) {
decltype(OuterArgs) OA = OuterArgs;
return 0;
}(5)...);
return 0;
};
auto M = K('a', ' ', 1, " -- ", 3.14);
currently cause crashes. I think I know how to fix this (since I had done so in my initial implementation) - but it will probably take some work and back & forth with Doug and Richard.
A warm thanks to all who provided feedback - and especially to Doug Gregor and Richard Smith for their pivotal guidance: their insight and prestidigitation in such matters is boundless!
Now let's hope this commit doesn't upset the buildbot gods ;)
Thanks!
llvm-svn: 194188
2013-11-07 13:17:06 +08:00
|
|
|
}
|
2013-12-08 04:22:44 +08:00
|
|
|
|
2018-05-09 09:00:01 +08:00
|
|
|
/// Examines the FunctionScopeInfo stack to determine the nearest
|
2018-07-31 03:24:48 +08:00
|
|
|
/// enclosing lambda (to the current lambda) that is 'capture-capable' for
|
2013-12-08 04:22:44 +08:00
|
|
|
/// the variable referenced in the current lambda (i.e. \p VarToCapture).
|
|
|
|
/// If successful, returns the index into Sema's FunctionScopeInfo stack
|
|
|
|
/// of the capture-capable lambda's LambdaScopeInfo.
|
|
|
|
///
|
|
|
|
/// Given the current stack of lambdas being processed by Sema and
|
2018-07-31 03:24:48 +08:00
|
|
|
/// the variable of interest, to identify the nearest enclosing lambda (to the
|
2013-12-08 04:22:44 +08:00
|
|
|
/// current lambda at the top of the stack) that can truly capture
|
|
|
|
/// a variable, it has to have the following two properties:
|
|
|
|
/// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
|
|
|
|
/// - climb down the stack (i.e. starting from the innermost and examining
|
|
|
|
/// each outer lambda step by step) checking if each enclosing
|
|
|
|
/// lambda can either implicitly or explicitly capture the variable.
|
|
|
|
/// Record the first such lambda that is enclosed in a non-dependent
|
|
|
|
/// context. If no such lambda currently exists return failure.
|
|
|
|
/// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
|
|
|
|
/// capture the variable by checking all its enclosing lambdas:
|
|
|
|
/// - check if all outer lambdas enclosing the 'capture-ready' lambda
|
|
|
|
/// identified above in 'a' can also capture the variable (this is done
|
|
|
|
/// via tryCaptureVariable for variables and CheckCXXThisCapture for
|
|
|
|
/// 'this' by passing in the index of the Lambda identified in step 'a')
|
|
|
|
///
|
|
|
|
/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
|
|
|
|
/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
|
|
|
|
/// is at the top of the stack.
|
|
|
|
///
|
|
|
|
/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
|
|
|
|
///
|
|
|
|
///
|
|
|
|
/// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
|
|
|
|
/// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
|
|
|
|
/// which is capture-capable. If the return value evaluates to 'false' then
|
|
|
|
/// no lambda is capture-capable for \p VarToCapture.
|
|
|
|
|
|
|
|
Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
|
|
|
|
ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
|
|
|
|
VarDecl *VarToCapture, Sema &S) {
|
|
|
|
|
2013-12-09 08:15:23 +08:00
|
|
|
const Optional<unsigned> NoLambdaIsCaptureCapable;
|
2018-07-31 03:24:48 +08:00
|
|
|
|
2013-12-08 04:22:44 +08:00
|
|
|
const Optional<unsigned> OptionalStackIndex =
|
|
|
|
getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
|
|
|
|
VarToCapture);
|
|
|
|
if (!OptionalStackIndex)
|
2013-12-09 08:15:23 +08:00
|
|
|
return NoLambdaIsCaptureCapable;
|
2013-12-08 04:22:44 +08:00
|
|
|
|
|
|
|
const unsigned IndexOfCaptureReadyLambda = OptionalStackIndex.getValue();
|
2013-12-08 23:00:29 +08:00
|
|
|
assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
|
|
|
|
S.getCurGenericLambda()) &&
|
|
|
|
"The capture ready lambda for a potential capture can only be the "
|
2013-12-08 23:04:03 +08:00
|
|
|
"current lambda if it is a generic lambda");
|
2013-12-08 04:22:44 +08:00
|
|
|
|
|
|
|
const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
|
|
|
|
cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
|
2018-07-31 03:24:48 +08:00
|
|
|
|
2013-12-08 04:22:44 +08:00
|
|
|
// If VarToCapture is null, we are attempting to capture 'this'
|
|
|
|
const bool IsCapturingThis = !VarToCapture;
|
This patch implements capturing of variables within generic lambdas.
Both Richard and I felt that the current wording in the working paper needed some tweaking - Please see http://llvm-reviews.chandlerc.com/D2035 for additional context and references to core-reflector messages that discuss wording tweaks.
What is implemented is what we had intended to specify in Bristol; but, recently felt that the specification might benefit from some tweaking and fleshing.
As a rough attempt to explain the semantics: If a nested lambda with a default-capture names a variable within its body, and if the enclosing full expression that contains the name of that variable is instantiation-dependent - then an enclosing lambda that is capture-ready (i.e. within a non-dependent context) must capture that variable, if all intervening nested lambdas can potentially capture that variable if they need to, and all intervening parent lambdas of the capture-ready lambda can and do capture the variable.
Of note, 'this' capturing is also currently underspecified in the working paper for generic lambdas. What is implemented here is if the set of candidate functions in a nested generic lambda includes both static and non-static member functions (regardless of viability checking - i.e. num and type of parameters/arguments) - and if all intervening nested-inner lambdas between the capture-ready lambda and the function-call containing nested lambda can capture 'this' and if all enclosing lambdas of the capture-ready lambda can capture 'this', then 'this' is speculatively captured by that capture-ready lambda.
Hopefully a paper for the C++ committee (that Richard and I had started some preliminary work on) is forthcoming.
This essentially makes generic lambdas feature complete, except for known bugs. The more prominent ones (and the ones I am currently aware of) being:
- generic lambdas and init-captures are broken - but a patch that fixes this is already in the works ...
- nested variadic expansions such as:
auto K = [](auto ... OuterArgs) {
vp([=](auto ... Is) {
decltype(OuterArgs) OA = OuterArgs;
return 0;
}(5)...);
return 0;
};
auto M = K('a', ' ', 1, " -- ", 3.14);
currently cause crashes. I think I know how to fix this (since I had done so in my initial implementation) - but it will probably take some work and back & forth with Doug and Richard.
A warm thanks to all who provided feedback - and especially to Doug Gregor and Richard Smith for their pivotal guidance: their insight and prestidigitation in such matters is boundless!
Now let's hope this commit doesn't upset the buildbot gods ;)
Thanks!
llvm-svn: 194188
2013-11-07 13:17:06 +08:00
|
|
|
const bool IsCapturingVariable = !IsCapturingThis;
|
|
|
|
|
|
|
|
if (IsCapturingVariable) {
|
2013-12-08 04:22:44 +08:00
|
|
|
// Check if the capture-ready lambda can truly capture the variable, by
|
|
|
|
// checking whether all enclosing lambdas of the capture-ready lambda allow
|
|
|
|
// the capture - i.e. make sure it is capture-capable.
|
This patch implements capturing of variables within generic lambdas.
Both Richard and I felt that the current wording in the working paper needed some tweaking - Please see http://llvm-reviews.chandlerc.com/D2035 for additional context and references to core-reflector messages that discuss wording tweaks.
What is implemented is what we had intended to specify in Bristol; but, recently felt that the specification might benefit from some tweaking and fleshing.
As a rough attempt to explain the semantics: If a nested lambda with a default-capture names a variable within its body, and if the enclosing full expression that contains the name of that variable is instantiation-dependent - then an enclosing lambda that is capture-ready (i.e. within a non-dependent context) must capture that variable, if all intervening nested lambdas can potentially capture that variable if they need to, and all intervening parent lambdas of the capture-ready lambda can and do capture the variable.
Of note, 'this' capturing is also currently underspecified in the working paper for generic lambdas. What is implemented here is if the set of candidate functions in a nested generic lambda includes both static and non-static member functions (regardless of viability checking - i.e. num and type of parameters/arguments) - and if all intervening nested-inner lambdas between the capture-ready lambda and the function-call containing nested lambda can capture 'this' and if all enclosing lambdas of the capture-ready lambda can capture 'this', then 'this' is speculatively captured by that capture-ready lambda.
Hopefully a paper for the C++ committee (that Richard and I had started some preliminary work on) is forthcoming.
This essentially makes generic lambdas feature complete, except for known bugs. The more prominent ones (and the ones I am currently aware of) being:
- generic lambdas and init-captures are broken - but a patch that fixes this is already in the works ...
- nested variadic expansions such as:
auto K = [](auto ... OuterArgs) {
vp([=](auto ... Is) {
decltype(OuterArgs) OA = OuterArgs;
return 0;
}(5)...);
return 0;
};
auto M = K('a', ' ', 1, " -- ", 3.14);
currently cause crashes. I think I know how to fix this (since I had done so in my initial implementation) - but it will probably take some work and back & forth with Doug and Richard.
A warm thanks to all who provided feedback - and especially to Doug Gregor and Richard Smith for their pivotal guidance: their insight and prestidigitation in such matters is boundless!
Now let's hope this commit doesn't upset the buildbot gods ;)
Thanks!
llvm-svn: 194188
2013-11-07 13:17:06 +08:00
|
|
|
QualType CaptureType, DeclRefType;
|
2013-12-08 04:22:44 +08:00
|
|
|
const bool CanCaptureVariable =
|
|
|
|
!S.tryCaptureVariable(VarToCapture,
|
|
|
|
/*ExprVarIsUsedInLoc*/ SourceLocation(),
|
|
|
|
clang::Sema::TryCapture_Implicit,
|
|
|
|
/*EllipsisLoc*/ SourceLocation(),
|
|
|
|
/*BuildAndDiagnose*/ false, CaptureType,
|
|
|
|
DeclRefType, &IndexOfCaptureReadyLambda);
|
|
|
|
if (!CanCaptureVariable)
|
2013-12-09 08:15:23 +08:00
|
|
|
return NoLambdaIsCaptureCapable;
|
2013-12-08 04:22:44 +08:00
|
|
|
} else {
|
|
|
|
// Check if the capture-ready lambda can truly capture 'this' by checking
|
|
|
|
// whether all enclosing lambdas of the capture-ready lambda can capture
|
|
|
|
// 'this'.
|
|
|
|
const bool CanCaptureThis =
|
|
|
|
!S.CheckCXXThisCapture(
|
|
|
|
CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
|
|
|
|
/*Explicit*/ false, /*BuildAndDiagnose*/ false,
|
|
|
|
&IndexOfCaptureReadyLambda);
|
|
|
|
if (!CanCaptureThis)
|
2013-12-09 08:15:23 +08:00
|
|
|
return NoLambdaIsCaptureCapable;
|
2018-07-31 03:24:48 +08:00
|
|
|
}
|
2013-12-08 04:22:44 +08:00
|
|
|
return IndexOfCaptureReadyLambda;
|
This patch implements capturing of variables within generic lambdas.
Both Richard and I felt that the current wording in the working paper needed some tweaking - Please see http://llvm-reviews.chandlerc.com/D2035 for additional context and references to core-reflector messages that discuss wording tweaks.
What is implemented is what we had intended to specify in Bristol; but, recently felt that the specification might benefit from some tweaking and fleshing.
As a rough attempt to explain the semantics: If a nested lambda with a default-capture names a variable within its body, and if the enclosing full expression that contains the name of that variable is instantiation-dependent - then an enclosing lambda that is capture-ready (i.e. within a non-dependent context) must capture that variable, if all intervening nested lambdas can potentially capture that variable if they need to, and all intervening parent lambdas of the capture-ready lambda can and do capture the variable.
Of note, 'this' capturing is also currently underspecified in the working paper for generic lambdas. What is implemented here is if the set of candidate functions in a nested generic lambda includes both static and non-static member functions (regardless of viability checking - i.e. num and type of parameters/arguments) - and if all intervening nested-inner lambdas between the capture-ready lambda and the function-call containing nested lambda can capture 'this' and if all enclosing lambdas of the capture-ready lambda can capture 'this', then 'this' is speculatively captured by that capture-ready lambda.
Hopefully a paper for the C++ committee (that Richard and I had started some preliminary work on) is forthcoming.
This essentially makes generic lambdas feature complete, except for known bugs. The more prominent ones (and the ones I am currently aware of) being:
- generic lambdas and init-captures are broken - but a patch that fixes this is already in the works ...
- nested variadic expansions such as:
auto K = [](auto ... OuterArgs) {
vp([=](auto ... Is) {
decltype(OuterArgs) OA = OuterArgs;
return 0;
}(5)...);
return 0;
};
auto M = K('a', ' ', 1, " -- ", 3.14);
currently cause crashes. I think I know how to fix this (since I had done so in my initial implementation) - but it will probably take some work and back & forth with Doug and Richard.
A warm thanks to all who provided feedback - and especially to Doug Gregor and Richard Smith for their pivotal guidance: their insight and prestidigitation in such matters is boundless!
Now let's hope this commit doesn't upset the buildbot gods ;)
Thanks!
llvm-svn: 194188
2013-11-07 13:17:06 +08:00
|
|
|
}
|
2013-10-24 00:10:50 +08:00
|
|
|
|
|
|
|
static inline TemplateParameterList *
|
|
|
|
getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
|
|
|
|
if (LSI->GLTemplateParameterList)
|
|
|
|
return LSI->GLTemplateParameterList;
|
|
|
|
|
2015-12-27 15:16:27 +08:00
|
|
|
if (!LSI->AutoTemplateParams.empty()) {
|
2013-10-24 00:10:50 +08:00
|
|
|
SourceRange IntroRange = LSI->IntroducerRange;
|
|
|
|
SourceLocation LAngleLoc = IntroRange.getBegin();
|
|
|
|
SourceLocation RAngleLoc = IntroRange.getEnd();
|
|
|
|
LSI->GLTemplateParameterList = TemplateParameterList::Create(
|
2013-12-08 04:22:44 +08:00
|
|
|
SemaRef.Context,
|
|
|
|
/*Template kw loc*/ SourceLocation(), LAngleLoc,
|
2015-12-27 15:16:27 +08:00
|
|
|
llvm::makeArrayRef((NamedDecl *const *)LSI->AutoTemplateParams.data(),
|
|
|
|
LSI->AutoTemplateParams.size()),
|
2016-07-31 06:33:34 +08:00
|
|
|
RAngleLoc, nullptr);
|
2013-10-24 00:10:50 +08:00
|
|
|
}
|
|
|
|
return LSI->GLTemplateParameterList;
|
|
|
|
}
|
|
|
|
|
2012-02-22 03:11:17 +08:00
|
|
|
CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
|
2012-09-19 09:18:11 +08:00
|
|
|
TypeSourceInfo *Info,
|
2018-07-31 03:24:48 +08:00
|
|
|
bool KnownDependent,
|
2013-10-24 00:10:50 +08:00
|
|
|
LambdaCaptureDefault CaptureDefault) {
|
2012-02-09 05:18:48 +08:00
|
|
|
DeclContext *DC = CurContext;
|
|
|
|
while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
|
|
|
|
DC = DC->getParent();
|
2013-10-24 00:10:50 +08:00
|
|
|
bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
|
2018-07-31 03:24:48 +08:00
|
|
|
*this);
|
2012-02-09 05:18:48 +08:00
|
|
|
// Start constructing the lambda class.
|
2012-09-19 09:18:11 +08:00
|
|
|
CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
|
2012-02-22 03:11:17 +08:00
|
|
|
IntroducerRange.getBegin(),
|
2018-07-31 03:24:48 +08:00
|
|
|
KnownDependent,
|
|
|
|
IsGenericLambda,
|
2013-10-24 00:10:50 +08:00
|
|
|
CaptureDefault);
|
2012-02-21 04:47:06 +08:00
|
|
|
DC->addDecl(Class);
|
2014-02-07 05:49:08 +08:00
|
|
|
|
2012-02-14 06:00:16 +08:00
|
|
|
return Class;
|
|
|
|
}
|
2012-02-09 05:18:48 +08:00
|
|
|
|
2018-05-09 09:00:01 +08:00
|
|
|
/// Determine whether the given context is or is enclosed in an inline
|
2012-04-05 01:40:10 +08:00
|
|
|
/// function.
|
|
|
|
static bool isInInlineFunction(const DeclContext *DC) {
|
|
|
|
while (!DC->isFileContext()) {
|
|
|
|
if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
|
|
|
|
if (FD->isInlined())
|
|
|
|
return true;
|
2018-07-31 03:24:48 +08:00
|
|
|
|
2012-04-05 01:40:10 +08:00
|
|
|
DC = DC->getLexicalParent();
|
|
|
|
}
|
2018-07-31 03:24:48 +08:00
|
|
|
|
2012-04-05 01:40:10 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2013-07-02 04:22:57 +08:00
|
|
|
MangleNumberingContext *
|
2013-07-10 08:30:46 +08:00
|
|
|
Sema::getCurrentMangleNumberContext(const DeclContext *DC,
|
2013-07-02 04:22:57 +08:00
|
|
|
Decl *&ManglingContextDecl) {
|
|
|
|
// Compute the context for allocating mangling numbers in the current
|
|
|
|
// expression, if the ABI requires them.
|
|
|
|
ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
|
|
|
|
|
|
|
|
enum ContextKind {
|
|
|
|
Normal,
|
|
|
|
DefaultArgument,
|
|
|
|
DataMember,
|
2017-09-22 12:25:05 +08:00
|
|
|
StaticDataMember,
|
|
|
|
InlineVariable,
|
|
|
|
VariableTemplate
|
2013-07-02 04:22:57 +08:00
|
|
|
} Kind = Normal;
|
|
|
|
|
|
|
|
// Default arguments of member function parameters that appear in a class
|
|
|
|
// definition, as well as the initializers of data members, receive special
|
|
|
|
// treatment. Identify them.
|
|
|
|
if (ManglingContextDecl) {
|
|
|
|
if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
|
|
|
|
if (const DeclContext *LexicalDC
|
|
|
|
= Param->getDeclContext()->getLexicalParent())
|
|
|
|
if (LexicalDC->isRecord())
|
|
|
|
Kind = DefaultArgument;
|
|
|
|
} else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
|
|
|
|
if (Var->getDeclContext()->isRecord())
|
|
|
|
Kind = StaticDataMember;
|
2017-09-22 12:25:05 +08:00
|
|
|
else if (Var->getMostRecentDecl()->isInline())
|
|
|
|
Kind = InlineVariable;
|
|
|
|
else if (Var->getDescribedVarTemplate())
|
|
|
|
Kind = VariableTemplate;
|
|
|
|
else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
|
|
|
|
if (!VTS->isExplicitSpecialization())
|
|
|
|
Kind = VariableTemplate;
|
|
|
|
}
|
2013-07-02 04:22:57 +08:00
|
|
|
} else if (isa<FieldDecl>(ManglingContextDecl)) {
|
|
|
|
Kind = DataMember;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Itanium ABI [5.1.7]:
|
|
|
|
// In the following contexts [...] the one-definition rule requires closure
|
|
|
|
// types in different translation units to "correspond":
|
|
|
|
bool IsInNonspecializedTemplate =
|
2017-02-21 09:17:38 +08:00
|
|
|
inTemplateInstantiation() || CurContext->isDependentContext();
|
2013-07-02 04:22:57 +08:00
|
|
|
switch (Kind) {
|
2016-10-14 20:43:59 +08:00
|
|
|
case Normal: {
|
2013-07-02 04:22:57 +08:00
|
|
|
// -- the bodies of non-exported nonspecialized template functions
|
|
|
|
// -- the bodies of inline functions
|
|
|
|
if ((IsInNonspecializedTemplate &&
|
|
|
|
!(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
|
2016-11-15 21:15:20 +08:00
|
|
|
isInInlineFunction(CurContext)) {
|
2014-05-26 14:22:03 +08:00
|
|
|
ManglingContextDecl = nullptr;
|
2016-11-15 21:15:20 +08:00
|
|
|
while (auto *CD = dyn_cast<CapturedDecl>(DC))
|
|
|
|
DC = CD->getParent();
|
|
|
|
return &Context.getManglingNumberContext(DC);
|
2013-07-02 04:22:57 +08:00
|
|
|
}
|
|
|
|
|
2014-05-26 14:22:03 +08:00
|
|
|
ManglingContextDecl = nullptr;
|
|
|
|
return nullptr;
|
2016-10-14 20:43:59 +08:00
|
|
|
}
|
2013-07-02 04:22:57 +08:00
|
|
|
|
|
|
|
case StaticDataMember:
|
|
|
|
// -- the initializers of nonspecialized static members of template classes
|
|
|
|
if (!IsInNonspecializedTemplate) {
|
2014-05-26 14:22:03 +08:00
|
|
|
ManglingContextDecl = nullptr;
|
|
|
|
return nullptr;
|
2013-07-02 04:22:57 +08:00
|
|
|
}
|
|
|
|
// Fall through to get the current context.
|
2017-06-03 14:35:06 +08:00
|
|
|
LLVM_FALLTHROUGH;
|
2013-07-02 04:22:57 +08:00
|
|
|
|
|
|
|
case DataMember:
|
|
|
|
// -- the in-class initializers of class members
|
|
|
|
case DefaultArgument:
|
|
|
|
// -- default arguments appearing in class definitions
|
2017-09-22 12:25:05 +08:00
|
|
|
case InlineVariable:
|
|
|
|
// -- the initializers of inline variables
|
|
|
|
case VariableTemplate:
|
|
|
|
// -- the initializers of templated variables
|
2013-09-11 04:14:30 +08:00
|
|
|
return &ExprEvalContexts.back().getMangleNumberingContext(Context);
|
2013-07-02 04:22:57 +08:00
|
|
|
}
|
2013-07-03 00:01:56 +08:00
|
|
|
|
|
|
|
llvm_unreachable("unexpected context");
|
2013-07-02 04:22:57 +08:00
|
|
|
}
|
|
|
|
|
2013-09-11 04:14:30 +08:00
|
|
|
MangleNumberingContext &
|
|
|
|
Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext(
|
|
|
|
ASTContext &Ctx) {
|
|
|
|
assert(ManglingContextDecl && "Need to have a context declaration");
|
|
|
|
if (!MangleNumbering)
|
|
|
|
MangleNumbering = Ctx.createMangleNumberingContext();
|
|
|
|
return *MangleNumbering;
|
|
|
|
}
|
|
|
|
|
2012-02-14 06:00:16 +08:00
|
|
|
CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
|
2013-09-25 13:02:54 +08:00
|
|
|
SourceRange IntroducerRange,
|
|
|
|
TypeSourceInfo *MethodTypeInfo,
|
|
|
|
SourceLocation EndLoc,
|
2016-03-27 00:11:37 +08:00
|
|
|
ArrayRef<ParmVarDecl *> Params,
|
|
|
|
const bool IsConstexprSpecified) {
|
2013-09-25 13:02:54 +08:00
|
|
|
QualType MethodType = MethodTypeInfo->getType();
|
2018-07-31 03:24:48 +08:00
|
|
|
TemplateParameterList *TemplateParams =
|
Implement a rudimentary form of generic lambdas.
Specifically, the following features are not included in this commit:
- any sort of capturing within generic lambdas
- generic lambdas within template functions and nested
within other generic lambdas
- conversion operator for captureless lambdas
- ensuring all visitors are generic lambda aware
(Although I have gotten some useful feedback on my patches of the above and will be incorporating that as I submit those patches for commit)
As an example of what compiles through this commit:
template <class F1, class F2>
struct overload : F1, F2 {
using F1::operator();
using F2::operator();
overload(F1 f1, F2 f2) : F1(f1), F2(f2) { }
};
auto Recursive = [](auto Self, auto h, auto ... rest) {
return 1 + Self(Self, rest...);
};
auto Base = [](auto Self, auto h) {
return 1;
};
overload<decltype(Base), decltype(Recursive)> O(Base, Recursive);
int num_params = O(O, 5, 3, "abc", 3.14, 'a');
Please see attached tests for more examples.
This patch has been reviewed by Doug and Richard. Minor changes (non-functionality affecting) have been made since both of them formally looked at it, but the changes involve removal of supernumerary return type deduction changes (since they are now redundant, with richard having committed a recent patch to address return type deduction for C++11 lambdas using C++14 semantics).
Some implementation notes:
- Add a new Declarator context => LambdaExprParameterContext to
clang::Declarator to allow the use of 'auto' in declaring generic
lambda parameters
- Add various helpers to CXXRecordDecl to facilitate identifying
and querying a closure class
- LambdaScopeInfo (which maintains the current lambda's Sema state)
was augmented to house the current depth of the template being
parsed (id est the Parser calls Sema::RecordParsingTemplateParameterDepth)
so that SemaType.cpp::ConvertDeclSpecToType may use it to immediately
generate a template-parameter-type when 'auto' is parsed in a generic
lambda parameter context. (i.e we do NOT use AutoType deduced to
a template parameter type - Richard seemed ok with this approach).
We encode that this template type was generated from an auto by simply
adding $auto to the name which can be used for better diagnostics if needed.
- SemaLambda.h was added to hold some common lambda utility
functions (this file is likely to grow ...)
- Teach Sema::ActOnStartOfFunctionDef to check whether it
is being called to instantiate a generic lambda's call
operator, and if so, push an appropriately prepared
LambdaScopeInfo object on the stack.
- various tests were added - but much more will be needed.
There is obviously more work to be done, and both Richard (weakly) and Doug (strongly)
have requested that LambdaExpr be removed form the CXXRecordDecl LambdaDefinitionaData
in a future patch which is forthcoming.
A greatful thanks to all reviewers including Eli Friedman, James Dennett,
and especially the two gracious wizards (Richard Smith and Doug Gregor)
who spent hours providing feedback (in person in Chicago and on the mailing lists).
And yet I am certain that I have allowed unidentified bugs to creep in; bugs, that I will do my best to slay, once identified!
Thanks!
llvm-svn: 191453
2013-09-27 03:54:12 +08:00
|
|
|
getGenericLambdaTemplateParameterList(getCurLambda(), *this);
|
|
|
|
// If a lambda appears in a dependent context or is a generic lambda (has
|
2018-07-31 03:24:48 +08:00
|
|
|
// template parameters) and has an 'auto' return type, deduce it to a
|
Implement a rudimentary form of generic lambdas.
Specifically, the following features are not included in this commit:
- any sort of capturing within generic lambdas
- generic lambdas within template functions and nested
within other generic lambdas
- conversion operator for captureless lambdas
- ensuring all visitors are generic lambda aware
(Although I have gotten some useful feedback on my patches of the above and will be incorporating that as I submit those patches for commit)
As an example of what compiles through this commit:
template <class F1, class F2>
struct overload : F1, F2 {
using F1::operator();
using F2::operator();
overload(F1 f1, F2 f2) : F1(f1), F2(f2) { }
};
auto Recursive = [](auto Self, auto h, auto ... rest) {
return 1 + Self(Self, rest...);
};
auto Base = [](auto Self, auto h) {
return 1;
};
overload<decltype(Base), decltype(Recursive)> O(Base, Recursive);
int num_params = O(O, 5, 3, "abc", 3.14, 'a');
Please see attached tests for more examples.
This patch has been reviewed by Doug and Richard. Minor changes (non-functionality affecting) have been made since both of them formally looked at it, but the changes involve removal of supernumerary return type deduction changes (since they are now redundant, with richard having committed a recent patch to address return type deduction for C++11 lambdas using C++14 semantics).
Some implementation notes:
- Add a new Declarator context => LambdaExprParameterContext to
clang::Declarator to allow the use of 'auto' in declaring generic
lambda parameters
- Add various helpers to CXXRecordDecl to facilitate identifying
and querying a closure class
- LambdaScopeInfo (which maintains the current lambda's Sema state)
was augmented to house the current depth of the template being
parsed (id est the Parser calls Sema::RecordParsingTemplateParameterDepth)
so that SemaType.cpp::ConvertDeclSpecToType may use it to immediately
generate a template-parameter-type when 'auto' is parsed in a generic
lambda parameter context. (i.e we do NOT use AutoType deduced to
a template parameter type - Richard seemed ok with this approach).
We encode that this template type was generated from an auto by simply
adding $auto to the name which can be used for better diagnostics if needed.
- SemaLambda.h was added to hold some common lambda utility
functions (this file is likely to grow ...)
- Teach Sema::ActOnStartOfFunctionDef to check whether it
is being called to instantiate a generic lambda's call
operator, and if so, push an appropriately prepared
LambdaScopeInfo object on the stack.
- various tests were added - but much more will be needed.
There is obviously more work to be done, and both Richard (weakly) and Doug (strongly)
have requested that LambdaExpr be removed form the CXXRecordDecl LambdaDefinitionaData
in a future patch which is forthcoming.
A greatful thanks to all reviewers including Eli Friedman, James Dennett,
and especially the two gracious wizards (Richard Smith and Doug Gregor)
who spent hours providing feedback (in person in Chicago and on the mailing lists).
And yet I am certain that I have allowed unidentified bugs to creep in; bugs, that I will do my best to slay, once identified!
Thanks!
llvm-svn: 191453
2013-09-27 03:54:12 +08:00
|
|
|
// dependent type.
|
|
|
|
if (Class->isDependentContext() || TemplateParams) {
|
2013-09-25 13:02:54 +08:00
|
|
|
const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
|
2014-01-26 00:55:45 +08:00
|
|
|
QualType Result = FPT->getReturnType();
|
2013-09-25 13:02:54 +08:00
|
|
|
if (Result->isUndeducedType()) {
|
|
|
|
Result = SubstAutoType(Result, Context.DependentTy);
|
2014-01-21 04:26:09 +08:00
|
|
|
MethodType = Context.getFunctionType(Result, FPT->getParamTypes(),
|
2013-09-25 13:02:54 +08:00
|
|
|
FPT->getExtProtoInfo());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2012-02-14 06:00:16 +08:00
|
|
|
// C++11 [expr.prim.lambda]p5:
|
2018-07-31 03:24:48 +08:00
|
|
|
// The closure type for a lambda-expression has a public inline function
|
2012-02-14 06:00:16 +08:00
|
|
|
// call operator (13.5.4) whose parameters and return type are described by
|
2018-07-31 03:24:48 +08:00
|
|
|
// the lambda-expression's parameter-declaration-clause and
|
2012-02-14 06:00:16 +08:00
|
|
|
// trailing-return-type respectively.
|
|
|
|
DeclarationName MethodName
|
|
|
|
= Context.DeclarationNames.getCXXOperatorName(OO_Call);
|
|
|
|
DeclarationNameLoc MethodNameLoc;
|
|
|
|
MethodNameLoc.CXXOperatorName.BeginOpNameLoc
|
|
|
|
= IntroducerRange.getBegin().getRawEncoding();
|
|
|
|
MethodNameLoc.CXXOperatorName.EndOpNameLoc
|
|
|
|
= IntroducerRange.getEnd().getRawEncoding();
|
|
|
|
CXXMethodDecl *Method
|
|
|
|
= CXXMethodDecl::Create(Context, Class, EndLoc,
|
2018-07-31 03:24:48 +08:00
|
|
|
DeclarationNameInfo(MethodName,
|
2012-02-14 06:00:16 +08:00
|
|
|
IntroducerRange.getBegin(),
|
|
|
|
MethodNameLoc),
|
2013-09-25 13:02:54 +08:00
|
|
|
MethodType, MethodTypeInfo,
|
2012-02-14 06:00:16 +08:00
|
|
|
SC_None,
|
|
|
|
/*isInline=*/true,
|
2016-03-27 00:11:37 +08:00
|
|
|
IsConstexprSpecified,
|
2012-02-14 06:00:16 +08:00
|
|
|
EndLoc);
|
|
|
|
Method->setAccess(AS_public);
|
2018-07-31 03:24:48 +08:00
|
|
|
|
2012-02-14 06:00:16 +08:00
|
|
|
// Temporarily set the lexical declaration context to the current
|
|
|
|
// context, so that the Scope stack matches the lexical nesting.
|
2018-07-31 03:24:48 +08:00
|
|
|
Method->setLexicalDeclContext(CurContext);
|
Implement a rudimentary form of generic lambdas.
Specifically, the following features are not included in this commit:
- any sort of capturing within generic lambdas
- generic lambdas within template functions and nested
within other generic lambdas
- conversion operator for captureless lambdas
- ensuring all visitors are generic lambda aware
(Although I have gotten some useful feedback on my patches of the above and will be incorporating that as I submit those patches for commit)
As an example of what compiles through this commit:
template <class F1, class F2>
struct overload : F1, F2 {
using F1::operator();
using F2::operator();
overload(F1 f1, F2 f2) : F1(f1), F2(f2) { }
};
auto Recursive = [](auto Self, auto h, auto ... rest) {
return 1 + Self(Self, rest...);
};
auto Base = [](auto Self, auto h) {
return 1;
};
overload<decltype(Base), decltype(Recursive)> O(Base, Recursive);
int num_params = O(O, 5, 3, "abc", 3.14, 'a');
Please see attached tests for more examples.
This patch has been reviewed by Doug and Richard. Minor changes (non-functionality affecting) have been made since both of them formally looked at it, but the changes involve removal of supernumerary return type deduction changes (since they are now redundant, with richard having committed a recent patch to address return type deduction for C++11 lambdas using C++14 semantics).
Some implementation notes:
- Add a new Declarator context => LambdaExprParameterContext to
clang::Declarator to allow the use of 'auto' in declaring generic
lambda parameters
- Add various helpers to CXXRecordDecl to facilitate identifying
and querying a closure class
- LambdaScopeInfo (which maintains the current lambda's Sema state)
was augmented to house the current depth of the template being
parsed (id est the Parser calls Sema::RecordParsingTemplateParameterDepth)
so that SemaType.cpp::ConvertDeclSpecToType may use it to immediately
generate a template-parameter-type when 'auto' is parsed in a generic
lambda parameter context. (i.e we do NOT use AutoType deduced to
a template parameter type - Richard seemed ok with this approach).
We encode that this template type was generated from an auto by simply
adding $auto to the name which can be used for better diagnostics if needed.
- SemaLambda.h was added to hold some common lambda utility
functions (this file is likely to grow ...)
- Teach Sema::ActOnStartOfFunctionDef to check whether it
is being called to instantiate a generic lambda's call
operator, and if so, push an appropriately prepared
LambdaScopeInfo object on the stack.
- various tests were added - but much more will be needed.
There is obviously more work to be done, and both Richard (weakly) and Doug (strongly)
have requested that LambdaExpr be removed form the CXXRecordDecl LambdaDefinitionaData
in a future patch which is forthcoming.
A greatful thanks to all reviewers including Eli Friedman, James Dennett,
and especially the two gracious wizards (Richard Smith and Doug Gregor)
who spent hours providing feedback (in person in Chicago and on the mailing lists).
And yet I am certain that I have allowed unidentified bugs to creep in; bugs, that I will do my best to slay, once identified!
Thanks!
llvm-svn: 191453
2013-09-27 03:54:12 +08:00
|
|
|
// Create a function template if we have a template parameter list
|
|
|
|
FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
|
|
|
|
FunctionTemplateDecl::Create(Context, Class,
|
2018-07-31 03:24:48 +08:00
|
|
|
Method->getLocation(), MethodName,
|
Implement a rudimentary form of generic lambdas.
Specifically, the following features are not included in this commit:
- any sort of capturing within generic lambdas
- generic lambdas within template functions and nested
within other generic lambdas
- conversion operator for captureless lambdas
- ensuring all visitors are generic lambda aware
(Although I have gotten some useful feedback on my patches of the above and will be incorporating that as I submit those patches for commit)
As an example of what compiles through this commit:
template <class F1, class F2>
struct overload : F1, F2 {
using F1::operator();
using F2::operator();
overload(F1 f1, F2 f2) : F1(f1), F2(f2) { }
};
auto Recursive = [](auto Self, auto h, auto ... rest) {
return 1 + Self(Self, rest...);
};
auto Base = [](auto Self, auto h) {
return 1;
};
overload<decltype(Base), decltype(Recursive)> O(Base, Recursive);
int num_params = O(O, 5, 3, "abc", 3.14, 'a');
Please see attached tests for more examples.
This patch has been reviewed by Doug and Richard. Minor changes (non-functionality affecting) have been made since both of them formally looked at it, but the changes involve removal of supernumerary return type deduction changes (since they are now redundant, with richard having committed a recent patch to address return type deduction for C++11 lambdas using C++14 semantics).
Some implementation notes:
- Add a new Declarator context => LambdaExprParameterContext to
clang::Declarator to allow the use of 'auto' in declaring generic
lambda parameters
- Add various helpers to CXXRecordDecl to facilitate identifying
and querying a closure class
- LambdaScopeInfo (which maintains the current lambda's Sema state)
was augmented to house the current depth of the template being
parsed (id est the Parser calls Sema::RecordParsingTemplateParameterDepth)
so that SemaType.cpp::ConvertDeclSpecToType may use it to immediately
generate a template-parameter-type when 'auto' is parsed in a generic
lambda parameter context. (i.e we do NOT use AutoType deduced to
a template parameter type - Richard seemed ok with this approach).
We encode that this template type was generated from an auto by simply
adding $auto to the name which can be used for better diagnostics if needed.
- SemaLambda.h was added to hold some common lambda utility
functions (this file is likely to grow ...)
- Teach Sema::ActOnStartOfFunctionDef to check whether it
is being called to instantiate a generic lambda's call
operator, and if so, push an appropriately prepared
LambdaScopeInfo object on the stack.
- various tests were added - but much more will be needed.
There is obviously more work to be done, and both Richard (weakly) and Doug (strongly)
have requested that LambdaExpr be removed form the CXXRecordDecl LambdaDefinitionaData
in a future patch which is forthcoming.
A greatful thanks to all reviewers including Eli Friedman, James Dennett,
and especially the two gracious wizards (Richard Smith and Doug Gregor)
who spent hours providing feedback (in person in Chicago and on the mailing lists).
And yet I am certain that I have allowed unidentified bugs to creep in; bugs, that I will do my best to slay, once identified!
Thanks!
llvm-svn: 191453
2013-09-27 03:54:12 +08:00
|
|
|
TemplateParams,
|
2014-05-26 14:22:03 +08:00
|
|
|
Method) : nullptr;
|
Implement a rudimentary form of generic lambdas.
Specifically, the following features are not included in this commit:
- any sort of capturing within generic lambdas
- generic lambdas within template functions and nested
within other generic lambdas
- conversion operator for captureless lambdas
- ensuring all visitors are generic lambda aware
(Although I have gotten some useful feedback on my patches of the above and will be incorporating that as I submit those patches for commit)
As an example of what compiles through this commit:
template <class F1, class F2>
struct overload : F1, F2 {
using F1::operator();
using F2::operator();
overload(F1 f1, F2 f2) : F1(f1), F2(f2) { }
};
auto Recursive = [](auto Self, auto h, auto ... rest) {
return 1 + Self(Self, rest...);
};
auto Base = [](auto Self, auto h) {
return 1;
};
overload<decltype(Base), decltype(Recursive)> O(Base, Recursive);
int num_params = O(O, 5, 3, "abc", 3.14, 'a');
Please see attached tests for more examples.
This patch has been reviewed by Doug and Richard. Minor changes (non-functionality affecting) have been made since both of them formally looked at it, but the changes involve removal of supernumerary return type deduction changes (since they are now redundant, with richard having committed a recent patch to address return type deduction for C++11 lambdas using C++14 semantics).
Some implementation notes:
- Add a new Declarator context => LambdaExprParameterContext to
clang::Declarator to allow the use of 'auto' in declaring generic
lambda parameters
- Add various helpers to CXXRecordDecl to facilitate identifying
and querying a closure class
- LambdaScopeInfo (which maintains the current lambda's Sema state)
was augmented to house the current depth of the template being
parsed (id est the Parser calls Sema::RecordParsingTemplateParameterDepth)
so that SemaType.cpp::ConvertDeclSpecToType may use it to immediately
generate a template-parameter-type when 'auto' is parsed in a generic
lambda parameter context. (i.e we do NOT use AutoType deduced to
a template parameter type - Richard seemed ok with this approach).
We encode that this template type was generated from an auto by simply
adding $auto to the name which can be used for better diagnostics if needed.
- SemaLambda.h was added to hold some common lambda utility
functions (this file is likely to grow ...)
- Teach Sema::ActOnStartOfFunctionDef to check whether it
is being called to instantiate a generic lambda's call
operator, and if so, push an appropriately prepared
LambdaScopeInfo object on the stack.
- various tests were added - but much more will be needed.
There is obviously more work to be done, and both Richard (weakly) and Doug (strongly)
have requested that LambdaExpr be removed form the CXXRecordDecl LambdaDefinitionaData
in a future patch which is forthcoming.
A greatful thanks to all reviewers including Eli Friedman, James Dennett,
and especially the two gracious wizards (Richard Smith and Doug Gregor)
who spent hours providing feedback (in person in Chicago and on the mailing lists).
And yet I am certain that I have allowed unidentified bugs to creep in; bugs, that I will do my best to slay, once identified!
Thanks!
llvm-svn: 191453
2013-09-27 03:54:12 +08:00
|
|
|
if (TemplateMethod) {
|
|
|
|
TemplateMethod->setLexicalDeclContext(CurContext);
|
|
|
|
TemplateMethod->setAccess(AS_public);
|
|
|
|
Method->setDescribedFunctionTemplate(TemplateMethod);
|
|
|
|
}
|
2018-07-31 03:24:48 +08:00
|
|
|
|
2012-02-15 06:28:59 +08:00
|
|
|
// Add parameters.
|
|
|
|
if (!Params.empty()) {
|
|
|
|
Method->setParams(Params);
|
2016-06-24 12:05:48 +08:00
|
|
|
CheckParmsForFunctionDef(Params,
|
2012-02-15 06:28:59 +08:00
|
|
|
/*CheckParameterNames=*/false);
|
2016-06-24 12:05:48 +08:00
|
|
|
|
|
|
|
for (auto P : Method->parameters())
|
2014-03-08 01:50:17 +08:00
|
|
|
P->setOwningFunction(Method);
|
2012-02-15 06:28:59 +08:00
|
|
|
}
|
2012-07-23 07:45:10 +08:00
|
|
|
|
2013-07-02 04:22:57 +08:00
|
|
|
Decl *ManglingContextDecl;
|
|
|
|
if (MangleNumberingContext *MCtx =
|
|
|
|
getCurrentMangleNumberContext(Class->getDeclContext(),
|
|
|
|
ManglingContextDecl)) {
|
|
|
|
unsigned ManglingNumber = MCtx->getManglingNumber(Method);
|
|
|
|
Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
|
2012-07-23 07:45:10 +08:00
|
|
|
}
|
|
|
|
|
2012-02-14 06:00:16 +08:00
|
|
|
return Method;
|
|
|
|
}
|
|
|
|
|
Implement a rudimentary form of generic lambdas.
Specifically, the following features are not included in this commit:
- any sort of capturing within generic lambdas
- generic lambdas within template functions and nested
within other generic lambdas
- conversion operator for captureless lambdas
- ensuring all visitors are generic lambda aware
(Although I have gotten some useful feedback on my patches of the above and will be incorporating that as I submit those patches for commit)
As an example of what compiles through this commit:
template <class F1, class F2>
struct overload : F1, F2 {
using F1::operator();
using F2::operator();
overload(F1 f1, F2 f2) : F1(f1), F2(f2) { }
};
auto Recursive = [](auto Self, auto h, auto ... rest) {
return 1 + Self(Self, rest...);
};
auto Base = [](auto Self, auto h) {
return 1;
};
overload<decltype(Base), decltype(Recursive)> O(Base, Recursive);
int num_params = O(O, 5, 3, "abc", 3.14, 'a');
Please see attached tests for more examples.
This patch has been reviewed by Doug and Richard. Minor changes (non-functionality affecting) have been made since both of them formally looked at it, but the changes involve removal of supernumerary return type deduction changes (since they are now redundant, with richard having committed a recent patch to address return type deduction for C++11 lambdas using C++14 semantics).
Some implementation notes:
- Add a new Declarator context => LambdaExprParameterContext to
clang::Declarator to allow the use of 'auto' in declaring generic
lambda parameters
- Add various helpers to CXXRecordDecl to facilitate identifying
and querying a closure class
- LambdaScopeInfo (which maintains the current lambda's Sema state)
was augmented to house the current depth of the template being
parsed (id est the Parser calls Sema::RecordParsingTemplateParameterDepth)
so that SemaType.cpp::ConvertDeclSpecToType may use it to immediately
generate a template-parameter-type when 'auto' is parsed in a generic
lambda parameter context. (i.e we do NOT use AutoType deduced to
a template parameter type - Richard seemed ok with this approach).
We encode that this template type was generated from an auto by simply
adding $auto to the name which can be used for better diagnostics if needed.
- SemaLambda.h was added to hold some common lambda utility
functions (this file is likely to grow ...)
- Teach Sema::ActOnStartOfFunctionDef to check whether it
is being called to instantiate a generic lambda's call
operator, and if so, push an appropriately prepared
LambdaScopeInfo object on the stack.
- various tests were added - but much more will be needed.
There is obviously more work to be done, and both Richard (weakly) and Doug (strongly)
have requested that LambdaExpr be removed form the CXXRecordDecl LambdaDefinitionaData
in a future patch which is forthcoming.
A greatful thanks to all reviewers including Eli Friedman, James Dennett,
and especially the two gracious wizards (Richard Smith and Doug Gregor)
who spent hours providing feedback (in person in Chicago and on the mailing lists).
And yet I am certain that I have allowed unidentified bugs to creep in; bugs, that I will do my best to slay, once identified!
Thanks!
llvm-svn: 191453
2013-09-27 03:54:12 +08:00
|
|
|
void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
|
|
|
|
CXXMethodDecl *CallOperator,
|
2012-02-14 06:00:16 +08:00
|
|
|
SourceRange IntroducerRange,
|
|
|
|
LambdaCaptureDefault CaptureDefault,
|
2013-08-10 07:08:25 +08:00
|
|
|
SourceLocation CaptureDefaultLoc,
|
2012-02-14 06:00:16 +08:00
|
|
|
bool ExplicitParams,
|
|
|
|
bool ExplicitResultType,
|
|
|
|
bool Mutable) {
|
Implement a rudimentary form of generic lambdas.
Specifically, the following features are not included in this commit:
- any sort of capturing within generic lambdas
- generic lambdas within template functions and nested
within other generic lambdas
- conversion operator for captureless lambdas
- ensuring all visitors are generic lambda aware
(Although I have gotten some useful feedback on my patches of the above and will be incorporating that as I submit those patches for commit)
As an example of what compiles through this commit:
template <class F1, class F2>
struct overload : F1, F2 {
using F1::operator();
using F2::operator();
overload(F1 f1, F2 f2) : F1(f1), F2(f2) { }
};
auto Recursive = [](auto Self, auto h, auto ... rest) {
return 1 + Self(Self, rest...);
};
auto Base = [](auto Self, auto h) {
return 1;
};
overload<decltype(Base), decltype(Recursive)> O(Base, Recursive);
int num_params = O(O, 5, 3, "abc", 3.14, 'a');
Please see attached tests for more examples.
This patch has been reviewed by Doug and Richard. Minor changes (non-functionality affecting) have been made since both of them formally looked at it, but the changes involve removal of supernumerary return type deduction changes (since they are now redundant, with richard having committed a recent patch to address return type deduction for C++11 lambdas using C++14 semantics).
Some implementation notes:
- Add a new Declarator context => LambdaExprParameterContext to
clang::Declarator to allow the use of 'auto' in declaring generic
lambda parameters
- Add various helpers to CXXRecordDecl to facilitate identifying
and querying a closure class
- LambdaScopeInfo (which maintains the current lambda's Sema state)
was augmented to house the current depth of the template being
parsed (id est the Parser calls Sema::RecordParsingTemplateParameterDepth)
so that SemaType.cpp::ConvertDeclSpecToType may use it to immediately
generate a template-parameter-type when 'auto' is parsed in a generic
lambda parameter context. (i.e we do NOT use AutoType deduced to
a template parameter type - Richard seemed ok with this approach).
We encode that this template type was generated from an auto by simply
adding $auto to the name which can be used for better diagnostics if needed.
- SemaLambda.h was added to hold some common lambda utility
functions (this file is likely to grow ...)
- Teach Sema::ActOnStartOfFunctionDef to check whether it
is being called to instantiate a generic lambda's call
operator, and if so, push an appropriately prepared
LambdaScopeInfo object on the stack.
- various tests were added - but much more will be needed.
There is obviously more work to be done, and both Richard (weakly) and Doug (strongly)
have requested that LambdaExpr be removed form the CXXRecordDecl LambdaDefinitionaData
in a future patch which is forthcoming.
A greatful thanks to all reviewers including Eli Friedman, James Dennett,
and especially the two gracious wizards (Richard Smith and Doug Gregor)
who spent hours providing feedback (in person in Chicago and on the mailing lists).
And yet I am certain that I have allowed unidentified bugs to creep in; bugs, that I will do my best to slay, once identified!
Thanks!
llvm-svn: 191453
2013-09-27 03:54:12 +08:00
|
|
|
LSI->CallOperator = CallOperator;
|
2013-10-24 00:10:50 +08:00
|
|
|
CXXRecordDecl *LambdaClass = CallOperator->getParent();
|
|
|
|
LSI->Lambda = LambdaClass;
|
2012-02-14 06:00:16 +08:00
|
|
|
if (CaptureDefault == LCD_ByCopy)
|
|
|
|
LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
|
|
|
|
else if (CaptureDefault == LCD_ByRef)
|
|
|
|
LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
|
2013-08-10 07:08:25 +08:00
|
|
|
LSI->CaptureDefaultLoc = CaptureDefaultLoc;
|
2012-02-14 06:00:16 +08:00
|
|
|
LSI->IntroducerRange = IntroducerRange;
|
|
|
|
LSI->ExplicitParams = ExplicitParams;
|
|
|
|
LSI->Mutable = Mutable;
|
|
|
|
|
|
|
|
if (ExplicitResultType) {
|
2014-01-26 00:55:45 +08:00
|
|
|
LSI->ReturnType = CallOperator->getReturnType();
|
|
|
|
|
2012-02-15 05:20:44 +08:00
|
|
|
if (!LSI->ReturnType->isDependentType() &&
|
|
|
|
!LSI->ReturnType->isVoidType()) {
|
2018-08-10 05:08:08 +08:00
|
|
|
if (RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
|
2012-02-15 05:20:44 +08:00
|
|
|
diag::err_lambda_incomplete_result)) {
|
|
|
|
// Do nothing.
|
|
|
|
}
|
|
|
|
}
|
2012-02-14 06:00:16 +08:00
|
|
|
} else {
|
|
|
|
LSI->HasImplicitReturnType = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
|
|
|
|
LSI->finishedExplicitCaptures();
|
|
|
|
}
|
|
|
|
|
2018-10-26 04:15:03 +08:00
|
|
|
void Sema::addLambdaParameters(
|
|
|
|
ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
|
|
|
|
CXXMethodDecl *CallOperator, Scope *CurScope) {
|
2012-02-14 06:00:16 +08:00
|
|
|
// Introduce our parameters into the function scope
|
2018-07-31 03:24:48 +08:00
|
|
|
for (unsigned p = 0, NumParams = CallOperator->getNumParams();
|
2012-02-14 06:00:16 +08:00
|
|
|
p < NumParams; ++p) {
|
|
|
|
ParmVarDecl *Param = CallOperator->getParamDecl(p);
|
2018-07-31 03:24:48 +08:00
|
|
|
|
2012-02-14 06:00:16 +08:00
|
|
|
// If this has an identifier, add it to the scope stack.
|
|
|
|
if (CurScope && Param->getIdentifier()) {
|
2018-10-26 04:15:03 +08:00
|
|
|
bool Error = false;
|
|
|
|
// Resolution of CWG 2211 in C++17 renders shadowing ill-formed, but we
|
|
|
|
// retroactively apply it.
|
|
|
|
for (const auto &Capture : Captures) {
|
|
|
|
if (Capture.Id == Param->getIdentifier()) {
|
|
|
|
Error = true;
|
|
|
|
Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
|
|
|
|
Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
|
|
|
|
<< Capture.Id << true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!Error)
|
|
|
|
CheckShadow(CurScope, Param);
|
2018-07-31 03:24:48 +08:00
|
|
|
|
2012-02-14 06:00:16 +08:00
|
|
|
PushOnScopeChains(Param, CurScope);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-03-09 08:54:31 +08:00
|
|
|
/// If this expression is an enumerator-like expression of some type
|
|
|
|
/// T, return the type T; otherwise, return null.
|
|
|
|
///
|
|
|
|
/// Pointer comparisons on the result here should always work because
|
|
|
|
/// it's derived from either the parent of an EnumConstantDecl
|
|
|
|
/// (i.e. the definition) or the declaration returned by
|
|
|
|
/// EnumType::getDecl() (i.e. the definition).
|
|
|
|
static EnumDecl *findEnumForBlockReturn(Expr *E) {
|
|
|
|
// An expression is an enumerator-like expression of type T if,
|
|
|
|
// ignoring parens and parens-like expressions:
|
|
|
|
E = E->IgnoreParens();
|
|
|
|
|
|
|
|
// - it is an enumerator whose enum type is T or
|
|
|
|
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
|
|
|
|
if (EnumConstantDecl *D
|
|
|
|
= dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
|
|
|
|
return cast<EnumDecl>(D->getDeclContext());
|
|
|
|
}
|
2014-05-26 14:22:03 +08:00
|
|
|
return nullptr;
|
2012-07-03 05:19:23 +08:00
|
|
|
}
|
|
|
|
|
2013-03-09 08:54:31 +08:00
|
|
|
// - it is a comma expression whose RHS is an enumerator-like
|
|
|
|
// expression of type T or
|
|
|
|
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
|
|
|
|
if (BO->getOpcode() == BO_Comma)
|
|
|
|
return findEnumForBlockReturn(BO->getRHS());
|
2014-05-26 14:22:03 +08:00
|
|
|
return nullptr;
|
2012-07-03 05:19:23 +08:00
|
|
|
}
|
|
|
|
|
2013-03-09 08:54:31 +08:00
|
|
|
// - it is a statement-expression whose value expression is an
|
|
|
|
// enumerator-like expression of type T or
|
|
|
|
if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
|
|
|
|
if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
|
|
|
|
return findEnumForBlockReturn(last);
|
2014-05-26 14:22:03 +08:00
|
|
|
return nullptr;
|
2012-07-03 05:19:23 +08:00
|
|
|
}
|
|
|
|
|
2013-03-09 08:54:31 +08:00
|
|
|
// - it is a ternary conditional operator (not the GNU ?:
|
|
|
|
// extension) whose second and third operands are
|
|
|
|
// enumerator-like expressions of type T or
|
|
|
|
if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
|
|
|
|
if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
|
|
|
|
if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
|
|
|
|
return ED;
|
2014-05-26 14:22:03 +08:00
|
|
|
return nullptr;
|
2012-07-03 05:19:23 +08:00
|
|
|
}
|
|
|
|
|
2013-03-09 08:54:31 +08:00
|
|
|
// (implicitly:)
|
|
|
|
// - it is an implicit integral conversion applied to an
|
|
|
|
// enumerator-like expression of type T or
|
|
|
|
if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
|
2013-05-08 11:34:22 +08:00
|
|
|
// We can sometimes see integral conversions in valid
|
|
|
|
// enumerator-like expressions.
|
2013-03-09 08:54:31 +08:00
|
|
|
if (ICE->getCastKind() == CK_IntegralCast)
|
|
|
|
return findEnumForBlockReturn(ICE->getSubExpr());
|
2013-05-08 11:34:22 +08:00
|
|
|
|
|
|
|
// Otherwise, just rely on the type.
|
2012-07-03 05:19:23 +08:00
|
|
|
}
|
|
|
|
|
2013-03-09 08:54:31 +08:00
|
|
|
// - it is an expression of that formal enum type.
|
|
|
|
if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
|
|
|
|
return ET->getDecl();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, nope.
|
2014-05-26 14:22:03 +08:00
|
|
|
return nullptr;
|
2013-03-09 08:54:31 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Attempt to find a type T for which the returned expression of the
|
|
|
|
/// given statement is an enumerator-like expression of that type.
|
|
|
|
static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
|
|
|
|
if (Expr *retValue = ret->getRetValue())
|
|
|
|
return findEnumForBlockReturn(retValue);
|
2014-05-26 14:22:03 +08:00
|
|
|
return nullptr;
|
2013-03-09 08:54:31 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Attempt to find a common type T for which all of the returned
|
|
|
|
/// expressions in a block are enumerator-like expressions of that
|
|
|
|
/// type.
|
|
|
|
static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
|
|
|
|
ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
|
|
|
|
|
|
|
|
// Try to find one for the first return.
|
|
|
|
EnumDecl *ED = findEnumForBlockReturn(*i);
|
2014-05-26 14:22:03 +08:00
|
|
|
if (!ED) return nullptr;
|
2013-03-09 08:54:31 +08:00
|
|
|
|
|
|
|
// Check that the rest of the returns have the same enum.
|
|
|
|
for (++i; i != e; ++i) {
|
|
|
|
if (findEnumForBlockReturn(*i) != ED)
|
2014-05-26 14:22:03 +08:00
|
|
|
return nullptr;
|
2013-03-09 08:54:31 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Never infer an anonymous enum type.
|
2014-05-26 14:22:03 +08:00
|
|
|
if (!ED->hasNameForLinkage()) return nullptr;
|
2013-03-09 08:54:31 +08:00
|
|
|
|
|
|
|
return ED;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Adjust the given return statements so that they formally return
|
|
|
|
/// the given type. It should require, at most, an IntegralCast.
|
|
|
|
static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
|
|
|
|
QualType returnType) {
|
|
|
|
for (ArrayRef<ReturnStmt*>::iterator
|
|
|
|
i = returns.begin(), e = returns.end(); i != e; ++i) {
|
|
|
|
ReturnStmt *ret = *i;
|
|
|
|
Expr *retValue = ret->getRetValue();
|
|
|
|
if (S.Context.hasSameType(retValue->getType(), returnType))
|
|
|
|
continue;
|
|
|
|
|
|
|
|
// Right now we only support integral fixup casts.
|
|
|
|
assert(returnType->isIntegralOrUnscopedEnumerationType());
|
|
|
|
assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
|
|
|
|
|
|
|
|
ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
|
|
|
|
|
|
|
|
Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
|
|
|
|
E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
|
2014-05-26 14:22:03 +08:00
|
|
|
E, /*base path*/ nullptr, VK_RValue);
|
2013-03-09 08:54:31 +08:00
|
|
|
if (cleanups) {
|
|
|
|
cleanups->setSubExpr(E);
|
|
|
|
} else {
|
|
|
|
ret->setRetValue(E);
|
|
|
|
}
|
|
|
|
}
|
2012-07-03 05:19:23 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
|
2013-08-22 20:12:24 +08:00
|
|
|
assert(CSI.HasImplicitReturnType);
|
Implement a rudimentary form of generic lambdas.
Specifically, the following features are not included in this commit:
- any sort of capturing within generic lambdas
- generic lambdas within template functions and nested
within other generic lambdas
- conversion operator for captureless lambdas
- ensuring all visitors are generic lambda aware
(Although I have gotten some useful feedback on my patches of the above and will be incorporating that as I submit those patches for commit)
As an example of what compiles through this commit:
template <class F1, class F2>
struct overload : F1, F2 {
using F1::operator();
using F2::operator();
overload(F1 f1, F2 f2) : F1(f1), F2(f2) { }
};
auto Recursive = [](auto Self, auto h, auto ... rest) {
return 1 + Self(Self, rest...);
};
auto Base = [](auto Self, auto h) {
return 1;
};
overload<decltype(Base), decltype(Recursive)> O(Base, Recursive);
int num_params = O(O, 5, 3, "abc", 3.14, 'a');
Please see attached tests for more examples.
This patch has been reviewed by Doug and Richard. Minor changes (non-functionality affecting) have been made since both of them formally looked at it, but the changes involve removal of supernumerary return type deduction changes (since they are now redundant, with richard having committed a recent patch to address return type deduction for C++11 lambdas using C++14 semantics).
Some implementation notes:
- Add a new Declarator context => LambdaExprParameterContext to
clang::Declarator to allow the use of 'auto' in declaring generic
lambda parameters
- Add various helpers to CXXRecordDecl to facilitate identifying
and querying a closure class
- LambdaScopeInfo (which maintains the current lambda's Sema state)
was augmented to house the current depth of the template being
parsed (id est the Parser calls Sema::RecordParsingTemplateParameterDepth)
so that SemaType.cpp::ConvertDeclSpecToType may use it to immediately
generate a template-parameter-type when 'auto' is parsed in a generic
lambda parameter context. (i.e we do NOT use AutoType deduced to
a template parameter type - Richard seemed ok with this approach).
We encode that this template type was generated from an auto by simply
adding $auto to the name which can be used for better diagnostics if needed.
- SemaLambda.h was added to hold some common lambda utility
functions (this file is likely to grow ...)
- Teach Sema::ActOnStartOfFunctionDef to check whether it
is being called to instantiate a generic lambda's call
operator, and if so, push an appropriately prepared
LambdaScopeInfo object on the stack.
- various tests were added - but much more will be needed.
There is obviously more work to be done, and both Richard (weakly) and Doug (strongly)
have requested that LambdaExpr be removed form the CXXRecordDecl LambdaDefinitionaData
in a future patch which is forthcoming.
A greatful thanks to all reviewers including Eli Friedman, James Dennett,
and especially the two gracious wizards (Richard Smith and Doug Gregor)
who spent hours providing feedback (in person in Chicago and on the mailing lists).
And yet I am certain that I have allowed unidentified bugs to creep in; bugs, that I will do my best to slay, once identified!
Thanks!
llvm-svn: 191453
2013-09-27 03:54:12 +08:00
|
|
|
// If it was ever a placeholder, it had to been deduced to DependentTy.
|
2018-07-31 03:24:48 +08:00
|
|
|
assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
|
2016-02-03 07:58:56 +08:00
|
|
|
assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
|
|
|
|
"lambda expressions use auto deduction in C++14 onwards");
|
2012-07-03 05:19:23 +08:00
|
|
|
|
2014-12-20 06:10:51 +08:00
|
|
|
// C++ core issue 975:
|
2013-03-09 08:54:31 +08:00
|
|
|
// If a lambda-expression does not include a trailing-return-type,
|
|
|
|
// it is as if the trailing-return-type denotes the following type:
|
|
|
|
// - if there are no return statements in the compound-statement,
|
|
|
|
// or all return statements return either an expression of type
|
|
|
|
// void or no expression or braced-init-list, the type void;
|
|
|
|
// - otherwise, if all return statements return an expression
|
|
|
|
// and the types of the returned expressions after
|
|
|
|
// lvalue-to-rvalue conversion (4.1 [conv.lval]),
|
|
|
|
// array-to-pointer conversion (4.2 [conv.array]), and
|
|
|
|
// function-to-pointer conversion (4.3 [conv.func]) are the
|
|
|
|
// same, that common type;
|
|
|
|
// - otherwise, the program is ill-formed.
|
|
|
|
//
|
2014-12-20 06:10:51 +08:00
|
|
|
// C++ core issue 1048 additionally removes top-level cv-qualifiers
|
|
|
|
// from the types of returned expressions to match the C++14 auto
|
|
|
|
// deduction rules.
|
|
|
|
//
|
2013-03-09 08:54:31 +08:00
|
|
|
// In addition, in blocks in non-C++ modes, if all of the return
|
|
|
|
// statements are enumerator-like expressions of some type T, where
|
|
|
|
// T has a name for linkage, then we infer the return type of the
|
|
|
|
// block to be that type.
|
|
|
|
|
2012-07-03 05:19:23 +08:00
|
|
|
// First case: no return statements, implicit void return type.
|
|
|
|
ASTContext &Ctx = getASTContext();
|
|
|
|
if (CSI.Returns.empty()) {
|
|
|
|
// It's possible there were simply no /valid/ return statements.
|
|
|
|
// In this case, the first one we found may have at least given us a type.
|
|
|
|
if (CSI.ReturnType.isNull())
|
|
|
|
CSI.ReturnType = Ctx.VoidTy;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Second case: at least one return statement has dependent type.
|
|
|
|
// Delay type checking until instantiation.
|
|
|
|
assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
|
2013-08-22 20:12:24 +08:00
|
|
|
if (CSI.ReturnType->isDependentType())
|
2012-07-03 05:19:23 +08:00
|
|
|
return;
|
|
|
|
|
2013-03-09 08:54:31 +08:00
|
|
|
// Try to apply the enum-fuzz rule.
|
|
|
|
if (!getLangOpts().CPlusPlus) {
|
|
|
|
assert(isa<BlockScopeInfo>(CSI));
|
|
|
|
const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
|
|
|
|
if (ED) {
|
|
|
|
CSI.ReturnType = Context.getTypeDeclType(ED);
|
|
|
|
adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2012-07-03 05:19:23 +08:00
|
|
|
// Third case: only one return statement. Don't bother doing extra work!
|
2018-06-26 10:50:01 +08:00
|
|
|
if (CSI.Returns.size() == 1)
|
2012-07-03 05:19:23 +08:00
|
|
|
return;
|
|
|
|
|
|
|
|
// General case: many return statements.
|
|
|
|
// Check that they all have compatible return types.
|
|
|
|
|
|
|
|
// We require the return types to strictly match here.
|
2013-03-09 08:54:31 +08:00
|
|
|
// Note that we've already done the required promotions as part of
|
|
|
|
// processing the return statement.
|
2018-06-26 10:50:01 +08:00
|
|
|
for (const ReturnStmt *RS : CSI.Returns) {
|
2012-07-03 05:19:23 +08:00
|
|
|
const Expr *RetE = RS->getRetValue();
|
|
|
|
|
2014-12-20 06:10:51 +08:00
|
|
|
QualType ReturnType =
|
|
|
|
(RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
|
2015-10-02 04:20:47 +08:00
|
|
|
if (Context.getCanonicalFunctionResultType(ReturnType) ==
|
2018-06-26 10:50:04 +08:00
|
|
|
Context.getCanonicalFunctionResultType(CSI.ReturnType)) {
|
|
|
|
// Use the return type with the strictest possible nullability annotation.
|
|
|
|
auto RetTyNullability = ReturnType->getNullability(Ctx);
|
|
|
|
auto BlockNullability = CSI.ReturnType->getNullability(Ctx);
|
|
|
|
if (BlockNullability &&
|
2018-06-26 11:53:06 +08:00
|
|
|
(!RetTyNullability ||
|
|
|
|
hasWeakerNullability(*RetTyNullability, *BlockNullability)))
|
2018-06-26 10:50:04 +08:00
|
|
|
CSI.ReturnType = ReturnType;
|
2013-03-09 08:54:31 +08:00
|
|
|
continue;
|
2018-06-26 10:50:04 +08:00
|
|
|
}
|
2013-03-09 08:54:31 +08:00
|
|
|
|
|
|
|
// FIXME: This is a poor diagnostic for ReturnStmts without expressions.
|
|
|
|
// TODO: It's possible that the *first* return is the divergent one.
|
2018-08-10 05:08:08 +08:00
|
|
|
Diag(RS->getBeginLoc(),
|
2013-03-09 08:54:31 +08:00
|
|
|
diag::err_typecheck_missing_return_type_incompatible)
|
2018-08-10 05:08:08 +08:00
|
|
|
<< ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
|
2013-03-09 08:54:31 +08:00
|
|
|
// Continue iterating so that we keep emitting diagnostics.
|
2012-07-03 05:19:23 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-11 09:36:17 +08:00
|
|
|
QualType Sema::buildLambdaInitCaptureInitialization(SourceLocation Loc,
|
|
|
|
bool ByRef,
|
|
|
|
IdentifierInfo *Id,
|
|
|
|
bool IsDirectInit,
|
|
|
|
Expr *&Init) {
|
2013-12-05 09:40:41 +08:00
|
|
|
// Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
|
|
|
|
// deduce against.
|
2013-05-16 14:20:58 +08:00
|
|
|
QualType DeductType = Context.getAutoDeductType();
|
|
|
|
TypeLocBuilder TLB;
|
|
|
|
TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
|
|
|
|
if (ByRef) {
|
|
|
|
DeductType = BuildReferenceType(DeductType, true, Loc, Id);
|
|
|
|
assert(!DeductType.isNull() && "can't build reference to auto");
|
|
|
|
TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
|
|
|
|
}
|
2013-06-08 04:31:48 +08:00
|
|
|
TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
|
2013-05-16 14:20:58 +08:00
|
|
|
|
2015-11-11 09:36:17 +08:00
|
|
|
// Deduce the type of the init capture.
|
|
|
|
QualType DeducedType = deduceVarTypeFromInitializer(
|
|
|
|
/*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
|
|
|
|
SourceRange(Loc, Loc), IsDirectInit, Init);
|
2013-12-05 09:40:41 +08:00
|
|
|
if (DeducedType.isNull())
|
|
|
|
return QualType();
|
|
|
|
|
2015-11-11 09:36:17 +08:00
|
|
|
// Are we a non-list direct initialization?
|
|
|
|
ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
|
|
|
|
|
2013-12-05 09:40:41 +08:00
|
|
|
// Perform initialization analysis and ensure any implicit conversions
|
|
|
|
// (such as lvalue-to-rvalue) are enforced.
|
|
|
|
InitializedEntity Entity =
|
|
|
|
InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
|
|
|
|
InitializationKind Kind =
|
|
|
|
IsDirectInit
|
|
|
|
? (CXXDirectInit ? InitializationKind::CreateDirect(
|
2018-08-10 05:09:38 +08:00
|
|
|
Loc, Init->getBeginLoc(), Init->getEndLoc())
|
2013-12-05 09:40:41 +08:00
|
|
|
: InitializationKind::CreateDirectList(Loc))
|
2018-08-10 05:08:08 +08:00
|
|
|
: InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
|
2013-12-05 09:40:41 +08:00
|
|
|
|
|
|
|
MultiExprArg Args = Init;
|
|
|
|
if (CXXDirectInit)
|
|
|
|
Args =
|
|
|
|
MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
|
|
|
|
QualType DclT;
|
|
|
|
InitializationSequence InitSeq(*this, Entity, Kind, Args);
|
|
|
|
ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
|
|
|
|
|
|
|
|
if (Result.isInvalid())
|
|
|
|
return QualType();
|
|
|
|
|
2014-05-29 18:55:11 +08:00
|
|
|
Init = Result.getAs<Expr>();
|
2013-12-05 09:40:41 +08:00
|
|
|
return DeducedType;
|
|
|
|
}
|
|
|
|
|
2015-11-11 09:36:17 +08:00
|
|
|
VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
|
|
|
|
QualType InitCaptureType,
|
|
|
|
IdentifierInfo *Id,
|
|
|
|
unsigned InitStyle, Expr *Init) {
|
2013-12-05 09:40:41 +08:00
|
|
|
TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType,
|
|
|
|
Loc);
|
2013-09-28 12:02:39 +08:00
|
|
|
// Create a dummy variable representing the init-capture. This is not actually
|
|
|
|
// used as a variable, and only exists as a way to name and refer to the
|
|
|
|
// init-capture.
|
|
|
|
// FIXME: Pass in separate source locations for '&' and identifier.
|
2013-09-28 12:31:26 +08:00
|
|
|
VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
|
2013-12-05 09:40:41 +08:00
|
|
|
Loc, Id, InitCaptureType, TSI, SC_Auto);
|
2013-09-28 12:02:39 +08:00
|
|
|
NewVD->setInitCapture(true);
|
|
|
|
NewVD->setReferenced(true);
|
2015-11-11 09:36:17 +08:00
|
|
|
// FIXME: Pass in a VarDecl::InitializationStyle.
|
|
|
|
NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
|
2013-09-28 12:02:39 +08:00
|
|
|
NewVD->markUsed(Context);
|
2013-12-05 09:40:41 +08:00
|
|
|
NewVD->setInit(Init);
|
2013-09-28 12:02:39 +08:00
|
|
|
return NewVD;
|
|
|
|
}
|
2013-05-16 14:20:58 +08:00
|
|
|
|
2013-09-28 12:02:39 +08:00
|
|
|
FieldDecl *Sema::buildInitCaptureField(LambdaScopeInfo *LSI, VarDecl *Var) {
|
|
|
|
FieldDecl *Field = FieldDecl::Create(
|
|
|
|
Context, LSI->Lambda, Var->getLocation(), Var->getLocation(),
|
2014-05-26 14:22:03 +08:00
|
|
|
nullptr, Var->getType(), Var->getTypeSourceInfo(), nullptr, false,
|
|
|
|
ICIS_NoInit);
|
2013-09-28 12:02:39 +08:00
|
|
|
Field->setImplicit(true);
|
|
|
|
Field->setAccess(AS_private);
|
|
|
|
LSI->Lambda->addDecl(Field);
|
|
|
|
|
|
|
|
LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
|
|
|
|
/*isNested*/false, Var->getLocation(), SourceLocation(),
|
|
|
|
Var->getType(), Var->getInit());
|
|
|
|
return Field;
|
2013-05-16 14:20:58 +08:00
|
|
|
}
|
|
|
|
|
2012-02-14 06:00:16 +08:00
|
|
|
void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
|
2015-04-28 05:27:54 +08:00
|
|
|
Declarator &ParamInfo,
|
|
|
|
Scope *CurScope) {
|
2012-02-22 03:11:17 +08:00
|
|
|
// Determine if we're within a context where we know that the lambda will
|
|
|
|
// be dependent, because there are template parameters in scope.
|
|
|
|
bool KnownDependent = false;
|
Implement a rudimentary form of generic lambdas.
Specifically, the following features are not included in this commit:
- any sort of capturing within generic lambdas
- generic lambdas within template functions and nested
within other generic lambdas
- conversion operator for captureless lambdas
- ensuring all visitors are generic lambda aware
(Although I have gotten some useful feedback on my patches of the above and will be incorporating that as I submit those patches for commit)
As an example of what compiles through this commit:
template <class F1, class F2>
struct overload : F1, F2 {
using F1::operator();
using F2::operator();
overload(F1 f1, F2 f2) : F1(f1), F2(f2) { }
};
auto Recursive = [](auto Self, auto h, auto ... rest) {
return 1 + Self(Self, rest...);
};
auto Base = [](auto Self, auto h) {
return 1;
};
overload<decltype(Base), decltype(Recursive)> O(Base, Recursive);
int num_params = O(O, 5, 3, "abc", 3.14, 'a');
Please see attached tests for more examples.
This patch has been reviewed by Doug and Richard. Minor changes (non-functionality affecting) have been made since both of them formally looked at it, but the changes involve removal of supernumerary return type deduction changes (since they are now redundant, with richard having committed a recent patch to address return type deduction for C++11 lambdas using C++14 semantics).
Some implementation notes:
- Add a new Declarator context => LambdaExprParameterContext to
clang::Declarator to allow the use of 'auto' in declaring generic
lambda parameters
- Add various helpers to CXXRecordDecl to facilitate identifying
and querying a closure class
- LambdaScopeInfo (which maintains the current lambda's Sema state)
was augmented to house the current depth of the template being
parsed (id est the Parser calls Sema::RecordParsingTemplateParameterDepth)
so that SemaType.cpp::ConvertDeclSpecToType may use it to immediately
generate a template-parameter-type when 'auto' is parsed in a generic
lambda parameter context. (i.e we do NOT use AutoType deduced to
a template parameter type - Richard seemed ok with this approach).
We encode that this template type was generated from an auto by simply
adding $auto to the name which can be used for better diagnostics if needed.
- SemaLambda.h was added to hold some common lambda utility
functions (this file is likely to grow ...)
- Teach Sema::ActOnStartOfFunctionDef to check whether it
is being called to instantiate a generic lambda's call
operator, and if so, push an appropriately prepared
LambdaScopeInfo object on the stack.
- various tests were added - but much more will be needed.
There is obviously more work to be done, and both Richard (weakly) and Doug (strongly)
have requested that LambdaExpr be removed form the CXXRecordDecl LambdaDefinitionaData
in a future patch which is forthcoming.
A greatful thanks to all reviewers including Eli Friedman, James Dennett,
and especially the two gracious wizards (Richard Smith and Doug Gregor)
who spent hours providing feedback (in person in Chicago and on the mailing lists).
And yet I am certain that I have allowed unidentified bugs to creep in; bugs, that I will do my best to slay, once identified!
Thanks!
llvm-svn: 191453
2013-09-27 03:54:12 +08:00
|
|
|
LambdaScopeInfo *const LSI = getCurLambda();
|
|
|
|
assert(LSI && "LambdaScopeInfo should be on stack!");
|
2016-03-24 04:07:07 +08:00
|
|
|
|
|
|
|
// The lambda-expression's closure type might be dependent even if its
|
|
|
|
// semantic context isn't, if it appears within a default argument of a
|
|
|
|
// function template.
|
2016-04-29 10:24:14 +08:00
|
|
|
if (CurScope->getTemplateParamParent())
|
|
|
|
KnownDependent = true;
|
2016-03-24 04:07:07 +08:00
|
|
|
|
2012-02-14 06:00:16 +08:00
|
|
|
// Determine the signature of the call operator.
|
2012-02-09 05:18:48 +08:00
|
|
|
TypeSourceInfo *MethodTyInfo;
|
|
|
|
bool ExplicitParams = true;
|
2012-02-14 06:00:16 +08:00
|
|
|
bool ExplicitResultType = true;
|
2012-07-25 11:56:55 +08:00
|
|
|
bool ContainsUnexpandedParameterPack = false;
|
2012-02-09 05:18:48 +08:00
|
|
|
SourceLocation EndLoc;
|
2013-01-13 03:30:44 +08:00
|
|
|
SmallVector<ParmVarDecl *, 8> Params;
|
2012-02-09 05:18:48 +08:00
|
|
|
if (ParamInfo.getNumTypeObjects() == 0) {
|
|
|
|
// C++11 [expr.prim.lambda]p4:
|
2018-07-31 03:24:48 +08:00
|
|
|
// If a lambda-expression does not include a lambda-declarator, it is as
|
2012-02-09 05:18:48 +08:00
|
|
|
// if the lambda-declarator were ().
|
2013-08-28 07:08:25 +08:00
|
|
|
FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
|
|
|
|
/*IsVariadic=*/false, /*IsCXXMethod=*/true));
|
2012-02-10 17:58:53 +08:00
|
|
|
EPI.HasTrailingReturn = true;
|
2018-12-12 23:06:16 +08:00
|
|
|
EPI.TypeQuals |= DeclSpec::TQ_const;
|
2013-09-25 13:02:54 +08:00
|
|
|
// C++1y [expr.prim.lambda]:
|
|
|
|
// The lambda return type is 'auto', which is replaced by the
|
|
|
|
// trailing-return type if provided and/or deduced from 'return'
|
|
|
|
// statements
|
|
|
|
// We don't do this before C++1y, because we don't support deduced return
|
|
|
|
// types there.
|
|
|
|
QualType DefaultTypeForNoTrailingReturn =
|
2014-08-19 23:55:55 +08:00
|
|
|
getLangOpts().CPlusPlus14 ? Context.getAutoDeductType()
|
2013-09-25 13:02:54 +08:00
|
|
|
: Context.DependentTy;
|
|
|
|
QualType MethodTy =
|
|
|
|
Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
|
2012-02-09 05:18:48 +08:00
|
|
|
MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
|
|
|
|
ExplicitParams = false;
|
2012-02-14 06:00:16 +08:00
|
|
|
ExplicitResultType = false;
|
2012-02-09 05:18:48 +08:00
|
|
|
EndLoc = Intro.Range.getEnd();
|
|
|
|
} else {
|
|
|
|
assert(ParamInfo.isFunctionDeclarator() &&
|
|
|
|
"lambda-declarator is a function");
|
|
|
|
DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
|
2013-09-25 13:02:54 +08:00
|
|
|
|
2012-02-09 05:18:48 +08:00
|
|
|
// C++11 [expr.prim.lambda]p5:
|
2018-07-31 03:24:48 +08:00
|
|
|
// This function call operator is declared const (9.3.1) if and only if
|
|
|
|
// the lambda-expression's parameter-declaration-clause is not followed
|
2012-02-09 05:18:48 +08:00
|
|
|
// by mutable. It is neither virtual nor declared volatile. [...]
|
|
|
|
if (!FTI.hasMutableQualifier())
|
|
|
|
FTI.TypeQuals |= DeclSpec::TQ_const;
|
2013-09-25 13:02:54 +08:00
|
|
|
|
2012-02-09 05:18:48 +08:00
|
|
|
MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
|
|
|
|
assert(MethodTyInfo && "no type from lambda-declarator");
|
|
|
|
EndLoc = ParamInfo.getSourceRange().getEnd();
|
2013-09-25 13:02:54 +08:00
|
|
|
|
|
|
|
ExplicitResultType = FTI.hasTrailingReturnType();
|
2013-08-22 20:12:24 +08:00
|
|
|
|
2014-05-12 00:05:55 +08:00
|
|
|
if (FTIHasNonVoidParameters(FTI)) {
|
2014-02-27 06:27:52 +08:00
|
|
|
Params.reserve(FTI.NumParams);
|
|
|
|
for (unsigned i = 0, e = FTI.NumParams; i != e; ++i)
|
|
|
|
Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param));
|
2012-09-20 09:40:23 +08:00
|
|
|
}
|
2012-06-16 00:59:29 +08:00
|
|
|
|
|
|
|
// Check for unexpanded parameter packs in the method type.
|
2012-07-25 11:56:55 +08:00
|
|
|
if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
|
|
|
|
ContainsUnexpandedParameterPack = true;
|
2012-02-09 05:18:48 +08:00
|
|
|
}
|
2012-09-19 09:18:11 +08:00
|
|
|
|
|
|
|
CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
|
2013-10-24 00:10:50 +08:00
|
|
|
KnownDependent, Intro.Default);
|
2012-09-19 09:18:11 +08:00
|
|
|
|
2016-03-27 00:11:37 +08:00
|
|
|
CXXMethodDecl *Method =
|
|
|
|
startLambdaDefinition(Class, Intro.Range, MethodTyInfo, EndLoc, Params,
|
|
|
|
ParamInfo.getDeclSpec().isConstexprSpecified());
|
2012-02-15 06:28:59 +08:00
|
|
|
if (ExplicitParams)
|
|
|
|
CheckCXXDefaultArguments(Method);
|
2018-03-26 21:48:03 +08:00
|
|
|
|
|
|
|
// This represents the function body for the lambda function, check if we
|
|
|
|
// have to apply optnone due to a pragma.
|
|
|
|
AddRangeBasedOptnone(Method);
|
2018-07-19 04:04:48 +08:00
|
|
|
|
|
|
|
// code_seg attribute on lambda apply to the method.
|
|
|
|
if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
|
|
|
|
Method->addAttr(A);
|
2018-07-31 03:24:48 +08:00
|
|
|
|
|
|
|
// Attributes on the lambda apply to the method.
|
2012-02-09 05:18:48 +08:00
|
|
|
ProcessDeclAttributes(CurScope, Method, ParamInfo);
|
2016-10-01 01:14:53 +08:00
|
|
|
|
|
|
|
// CUDA lambdas get implicit attributes based on the scope in which they're
|
|
|
|
// declared.
|
|
|
|
if (getLangOpts().CUDA)
|
|
|
|
CUDASetLambdaAttrs(Method);
|
|
|
|
|
2012-02-09 08:47:04 +08:00
|
|
|
// Introduce the function call operator as the current declaration context.
|
2012-02-09 05:18:48 +08:00
|
|
|
PushDeclContext(CurScope, Method);
|
2018-07-31 03:24:48 +08:00
|
|
|
|
Implement a rudimentary form of generic lambdas.
Specifically, the following features are not included in this commit:
- any sort of capturing within generic lambdas
- generic lambdas within template functions and nested
within other generic lambdas
- conversion operator for captureless lambdas
- ensuring all visitors are generic lambda aware
(Although I have gotten some useful feedback on my patches of the above and will be incorporating that as I submit those patches for commit)
As an example of what compiles through this commit:
template <class F1, class F2>
struct overload : F1, F2 {
using F1::operator();
using F2::operator();
overload(F1 f1, F2 f2) : F1(f1), F2(f2) { }
};
auto Recursive = [](auto Self, auto h, auto ... rest) {
return 1 + Self(Self, rest...);
};
auto Base = [](auto Self, auto h) {
return 1;
};
overload<decltype(Base), decltype(Recursive)> O(Base, Recursive);
int num_params = O(O, 5, 3, "abc", 3.14, 'a');
Please see attached tests for more examples.
This patch has been reviewed by Doug and Richard. Minor changes (non-functionality affecting) have been made since both of them formally looked at it, but the changes involve removal of supernumerary return type deduction changes (since they are now redundant, with richard having committed a recent patch to address return type deduction for C++11 lambdas using C++14 semantics).
Some implementation notes:
- Add a new Declarator context => LambdaExprParameterContext to
clang::Declarator to allow the use of 'auto' in declaring generic
lambda parameters
- Add various helpers to CXXRecordDecl to facilitate identifying
and querying a closure class
- LambdaScopeInfo (which maintains the current lambda's Sema state)
was augmented to house the current depth of the template being
parsed (id est the Parser calls Sema::RecordParsingTemplateParameterDepth)
so that SemaType.cpp::ConvertDeclSpecToType may use it to immediately
generate a template-parameter-type when 'auto' is parsed in a generic
lambda parameter context. (i.e we do NOT use AutoType deduced to
a template parameter type - Richard seemed ok with this approach).
We encode that this template type was generated from an auto by simply
adding $auto to the name which can be used for better diagnostics if needed.
- SemaLambda.h was added to hold some common lambda utility
functions (this file is likely to grow ...)
- Teach Sema::ActOnStartOfFunctionDef to check whether it
is being called to instantiate a generic lambda's call
operator, and if so, push an appropriately prepared
LambdaScopeInfo object on the stack.
- various tests were added - but much more will be needed.
There is obviously more work to be done, and both Richard (weakly) and Doug (strongly)
have requested that LambdaExpr be removed form the CXXRecordDecl LambdaDefinitionaData
in a future patch which is forthcoming.
A greatful thanks to all reviewers including Eli Friedman, James Dennett,
and especially the two gracious wizards (Richard Smith and Doug Gregor)
who spent hours providing feedback (in person in Chicago and on the mailing lists).
And yet I am certain that I have allowed unidentified bugs to creep in; bugs, that I will do my best to slay, once identified!
Thanks!
llvm-svn: 191453
2013-09-27 03:54:12 +08:00
|
|
|
// Build the lambda scope.
|
2015-04-28 05:27:54 +08:00
|
|
|
buildLambdaScope(LSI, Method, Intro.Range, Intro.Default, Intro.DefaultLoc,
|
|
|
|
ExplicitParams, ExplicitResultType, !Method->isConst());
|
2013-05-16 14:20:58 +08:00
|
|
|
|
2014-02-07 05:49:08 +08:00
|
|
|
// C++11 [expr.prim.lambda]p9:
|
|
|
|
// A lambda-expression whose smallest enclosing scope is a block scope is a
|
|
|
|
// local lambda expression; any other lambda expression shall not have a
|
|
|
|
// capture-default or simple-capture in its lambda-introducer.
|
|
|
|
//
|
|
|
|
// For simple-captures, this is covered by the check below that any named
|
|
|
|
// entity is a variable that can be captured.
|
|
|
|
//
|
|
|
|
// For DR1632, we also allow a capture-default in any context where we can
|
|
|
|
// odr-use 'this' (in particular, in a default initializer for a non-static
|
|
|
|
// data member).
|
|
|
|
if (Intro.Default != LCD_None && !Class->getParent()->isFunctionOrMethod() &&
|
|
|
|
(getCurrentThisType().isNull() ||
|
|
|
|
CheckCXXThisCapture(SourceLocation(), /*Explicit*/true,
|
|
|
|
/*BuildAndDiagnose*/false)))
|
|
|
|
Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
|
|
|
|
|
2013-05-16 14:20:58 +08:00
|
|
|
// Distinct capture names, for diagnostics.
|
|
|
|
llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
|
|
|
|
|
2012-02-09 05:18:48 +08:00
|
|
|
// Handle explicit captures.
|
2012-02-11 01:46:20 +08:00
|
|
|
SourceLocation PrevCaptureLoc
|
|
|
|
= Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
|
2014-05-11 00:31:55 +08:00
|
|
|
for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
|
2012-02-11 01:46:20 +08:00
|
|
|
PrevCaptureLoc = C->Loc, ++C) {
|
[Cxx1z] Implement Lambda Capture of *this by Value as [=,*this] (P0018R3)
Implement lambda capture of *this by copy.
For e.g.:
struct A {
int d = 10;
auto foo() { return [*this] (auto a) mutable { d+=a; return d; }; }
};
auto L = A{}.foo(); // A{}'s lifetime is gone.
// Below is still ok, because *this was captured by value.
assert(L(10) == 20);
assert(L(100) == 120);
If the capture was implicit, or [this] (i.e. *this was captured by reference), this code would be otherwise undefined.
Implementation Strategy:
- amend the parser to accept *this in the lambda introducer
- add a new king of capture LCK_StarThis
- teach Sema::CheckCXXThisCapture to handle by copy captures of the
enclosing object (i.e. *this)
- when CheckCXXThisCapture does capture by copy, the corresponding
initializer expression for the closure's data member
direct-initializes it thus making a copy of '*this'.
- in codegen, when assigning to CXXThisValue, if *this was captured by
copy, make sure it points to the corresponding field member, and
not, unlike when captured by reference, what the field member points
to.
- mark feature as implemented in svn
Much gratitude to Richard Smith for his carefully illuminating reviews!
llvm-svn: 263921
2016-03-21 17:25:37 +08:00
|
|
|
if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
|
2018-07-31 03:24:48 +08:00
|
|
|
if (C->Kind == LCK_StarThis)
|
2017-12-05 04:27:34 +08:00
|
|
|
Diag(C->Loc, !getLangOpts().CPlusPlus17
|
2017-08-14 07:37:29 +08:00
|
|
|
? diag::ext_star_this_lambda_capture_cxx17
|
[Cxx1z] Implement Lambda Capture of *this by Value as [=,*this] (P0018R3)
Implement lambda capture of *this by copy.
For e.g.:
struct A {
int d = 10;
auto foo() { return [*this] (auto a) mutable { d+=a; return d; }; }
};
auto L = A{}.foo(); // A{}'s lifetime is gone.
// Below is still ok, because *this was captured by value.
assert(L(10) == 20);
assert(L(100) == 120);
If the capture was implicit, or [this] (i.e. *this was captured by reference), this code would be otherwise undefined.
Implementation Strategy:
- amend the parser to accept *this in the lambda introducer
- add a new king of capture LCK_StarThis
- teach Sema::CheckCXXThisCapture to handle by copy captures of the
enclosing object (i.e. *this)
- when CheckCXXThisCapture does capture by copy, the corresponding
initializer expression for the closure's data member
direct-initializes it thus making a copy of '*this'.
- in codegen, when assigning to CXXThisValue, if *this was captured by
copy, make sure it points to the corresponding field member, and
not, unlike when captured by reference, what the field member points
to.
- mark feature as implemented in svn
Much gratitude to Richard Smith for his carefully illuminating reviews!
llvm-svn: 263921
2016-03-21 17:25:37 +08:00
|
|
|
: diag::warn_cxx14_compat_star_this_lambda_capture);
|
|
|
|
|
2012-02-09 05:18:48 +08:00
|
|
|
// C++11 [expr.prim.lambda]p8:
|
2018-07-31 03:24:48 +08:00
|
|
|
// An identifier or this shall not appear more than once in a
|
2012-02-09 05:18:48 +08:00
|
|
|
// lambda-capture.
|
|
|
|
if (LSI->isCXXThisCaptured()) {
|
2014-05-03 11:45:55 +08:00
|
|
|
Diag(C->Loc, diag::err_capture_more_than_once)
|
|
|
|
<< "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
|
|
|
|
<< FixItHint::CreateRemoval(
|
|
|
|
SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
|
2012-02-09 05:18:48 +08:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2017-08-19 11:43:07 +08:00
|
|
|
// C++2a [expr.prim.lambda]p8:
|
|
|
|
// If a lambda-capture includes a capture-default that is =,
|
|
|
|
// each simple-capture of that lambda-capture shall be of the form
|
|
|
|
// "&identifier", "this", or "* this". [ Note: The form [&,this] is
|
|
|
|
// redundant but accepted for compatibility with ISO C++14. --end note ]
|
|
|
|
if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
|
|
|
|
Diag(C->Loc, !getLangOpts().CPlusPlus2a
|
|
|
|
? diag::ext_equals_this_lambda_capture_cxx2a
|
|
|
|
: diag::warn_cxx17_compat_equals_this_lambda_capture);
|
2012-02-09 05:18:48 +08:00
|
|
|
|
|
|
|
// C++11 [expr.prim.lambda]p12:
|
|
|
|
// If this is captured by a local lambda expression, its nearest
|
|
|
|
// enclosing function shall be a non-static member function.
|
|
|
|
QualType ThisCaptureType = getCurrentThisType();
|
|
|
|
if (ThisCaptureType.isNull()) {
|
|
|
|
Diag(C->Loc, diag::err_this_capture) << true;
|
|
|
|
continue;
|
|
|
|
}
|
2018-07-31 03:24:48 +08:00
|
|
|
|
[Cxx1z] Implement Lambda Capture of *this by Value as [=,*this] (P0018R3)
Implement lambda capture of *this by copy.
For e.g.:
struct A {
int d = 10;
auto foo() { return [*this] (auto a) mutable { d+=a; return d; }; }
};
auto L = A{}.foo(); // A{}'s lifetime is gone.
// Below is still ok, because *this was captured by value.
assert(L(10) == 20);
assert(L(100) == 120);
If the capture was implicit, or [this] (i.e. *this was captured by reference), this code would be otherwise undefined.
Implementation Strategy:
- amend the parser to accept *this in the lambda introducer
- add a new king of capture LCK_StarThis
- teach Sema::CheckCXXThisCapture to handle by copy captures of the
enclosing object (i.e. *this)
- when CheckCXXThisCapture does capture by copy, the corresponding
initializer expression for the closure's data member
direct-initializes it thus making a copy of '*this'.
- in codegen, when assigning to CXXThisValue, if *this was captured by
copy, make sure it points to the corresponding field member, and
not, unlike when captured by reference, what the field member points
to.
- mark feature as implemented in svn
Much gratitude to Richard Smith for his carefully illuminating reviews!
llvm-svn: 263921
2016-03-21 17:25:37 +08:00
|
|
|
CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
|
|
|
|
/*FunctionScopeIndexToStopAtPtr*/ nullptr,
|
|
|
|
C->Kind == LCK_StarThis);
|
2018-07-16 15:23:47 +08:00
|
|
|
if (!LSI->Captures.empty())
|
|
|
|
LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
|
2012-02-09 05:18:48 +08:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2013-05-16 14:20:58 +08:00
|
|
|
assert(C->Id && "missing identifier for capture");
|
|
|
|
|
2013-05-10 05:36:41 +08:00
|
|
|
if (C->Init.isInvalid())
|
|
|
|
continue;
|
2013-05-16 14:20:58 +08:00
|
|
|
|
2014-05-26 14:22:03 +08:00
|
|
|
VarDecl *Var = nullptr;
|
2013-09-28 12:02:39 +08:00
|
|
|
if (C->Init.isUsable()) {
|
2014-08-19 23:55:55 +08:00
|
|
|
Diag(C->Loc, getLangOpts().CPlusPlus14
|
2013-09-28 13:38:27 +08:00
|
|
|
? diag::warn_cxx11_compat_init_capture
|
|
|
|
: diag::ext_init_capture);
|
|
|
|
|
2013-05-16 14:20:58 +08:00
|
|
|
if (C->Init.get()->containsUnexpandedParameterPack())
|
|
|
|
ContainsUnexpandedParameterPack = true;
|
2013-12-05 09:40:41 +08:00
|
|
|
// If the initializer expression is usable, but the InitCaptureType
|
|
|
|
// is not, then an error has occurred - so ignore the capture for now.
|
|
|
|
// for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
|
2018-07-31 03:24:48 +08:00
|
|
|
// FIXME: we should create the init capture variable and mark it invalid
|
2013-12-05 09:40:41 +08:00
|
|
|
// in this case.
|
2018-07-31 03:24:48 +08:00
|
|
|
if (C->InitCaptureType.get().isNull())
|
2013-12-05 09:40:41 +08:00
|
|
|
continue;
|
2015-11-11 09:36:17 +08:00
|
|
|
|
|
|
|
unsigned InitStyle;
|
|
|
|
switch (C->InitKind) {
|
|
|
|
case LambdaCaptureInitKind::NoInit:
|
|
|
|
llvm_unreachable("not an init-capture?");
|
|
|
|
case LambdaCaptureInitKind::CopyInit:
|
|
|
|
InitStyle = VarDecl::CInit;
|
|
|
|
break;
|
|
|
|
case LambdaCaptureInitKind::DirectInit:
|
|
|
|
InitStyle = VarDecl::CallInit;
|
|
|
|
break;
|
|
|
|
case LambdaCaptureInitKind::ListInit:
|
|
|
|
InitStyle = VarDecl::ListInit;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
|
|
|
|
C->Id, InitStyle, C->Init.get());
|
2013-05-16 14:20:58 +08:00
|
|
|
// C++1y [expr.prim.lambda]p11:
|
2013-09-28 12:02:39 +08:00
|
|
|
// An init-capture behaves as if it declares and explicitly
|
|
|
|
// captures a variable [...] whose declarative region is the
|
|
|
|
// lambda-expression's compound-statement
|
|
|
|
if (Var)
|
|
|
|
PushOnScopeChains(Var, CurScope, false);
|
|
|
|
} else {
|
2015-11-11 09:36:17 +08:00
|
|
|
assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
|
|
|
|
"init capture has valid but null init?");
|
|
|
|
|
2013-09-28 12:02:39 +08:00
|
|
|
// C++11 [expr.prim.lambda]p8:
|
2018-07-31 03:24:48 +08:00
|
|
|
// If a lambda-capture includes a capture-default that is &, the
|
2013-09-28 12:02:39 +08:00
|
|
|
// identifiers in the lambda-capture shall not be preceded by &.
|
|
|
|
// If a lambda-capture includes a capture-default that is =, [...]
|
|
|
|
// each identifier it contains shall be preceded by &.
|
|
|
|
if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
|
|
|
|
Diag(C->Loc, diag::err_reference_capture_with_reference_default)
|
2014-05-03 11:45:55 +08:00
|
|
|
<< FixItHint::CreateRemoval(
|
|
|
|
SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
|
2013-09-28 12:02:39 +08:00
|
|
|
continue;
|
|
|
|
} else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
|
|
|
|
Diag(C->Loc, diag::err_copy_capture_with_copy_default)
|
2014-05-03 11:45:55 +08:00
|
|
|
<< FixItHint::CreateRemoval(
|
|
|
|
SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
|
2013-09-28 12:02:39 +08:00
|
|
|
continue;
|
|
|
|
}
|
2012-02-09 05:18:48 +08:00
|
|
|
|
2013-09-28 12:02:39 +08:00
|
|
|
// C++11 [expr.prim.lambda]p10:
|
|
|
|
// The identifiers in a capture-list are looked up using the usual
|
|
|
|
// rules for unqualified name lookup (3.4.1)
|
|
|
|
DeclarationNameInfo Name(C->Id, C->Loc);
|
|
|
|
LookupResult R(*this, Name, LookupOrdinaryName);
|
|
|
|
LookupName(R, CurScope);
|
|
|
|
if (R.isAmbiguous())
|
2012-02-09 05:18:48 +08:00
|
|
|
continue;
|
2013-09-28 12:02:39 +08:00
|
|
|
if (R.empty()) {
|
|
|
|
// FIXME: Disable corrections that would add qualification?
|
|
|
|
CXXScopeSpec ScopeSpec;
|
2014-10-28 02:07:29 +08:00
|
|
|
if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R,
|
|
|
|
llvm::make_unique<DeclFilterCCC<VarDecl>>()))
|
2013-09-28 12:02:39 +08:00
|
|
|
continue;
|
|
|
|
}
|
2012-02-09 05:18:48 +08:00
|
|
|
|
2013-09-28 12:02:39 +08:00
|
|
|
Var = R.getAsSingle<VarDecl>();
|
2014-03-26 05:11:32 +08:00
|
|
|
if (Var && DiagnoseUseOfDecl(Var, C->Loc))
|
|
|
|
continue;
|
2013-09-28 12:02:39 +08:00
|
|
|
}
|
2013-05-16 14:20:58 +08:00
|
|
|
|
|
|
|
// C++11 [expr.prim.lambda]p8:
|
|
|
|
// An identifier or this shall not appear more than once in a
|
|
|
|
// lambda-capture.
|
2014-11-19 15:49:47 +08:00
|
|
|
if (!CaptureNames.insert(C->Id).second) {
|
2013-05-16 14:20:58 +08:00
|
|
|
if (Var && LSI->isCaptured(Var)) {
|
|
|
|
Diag(C->Loc, diag::err_capture_more_than_once)
|
2014-05-03 11:45:55 +08:00
|
|
|
<< C->Id << SourceRange(LSI->getCapture(Var).getLocation())
|
|
|
|
<< FixItHint::CreateRemoval(
|
|
|
|
SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
|
2013-05-16 14:20:58 +08:00
|
|
|
} else
|
2013-09-28 12:02:39 +08:00
|
|
|
// Previous capture captured something different (one or both was
|
|
|
|
// an init-cpature): no fixit.
|
2013-05-16 14:20:58 +08:00
|
|
|
Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2012-02-09 05:18:48 +08:00
|
|
|
// C++11 [expr.prim.lambda]p10:
|
2013-05-16 14:20:58 +08:00
|
|
|
// [...] each such lookup shall find a variable with automatic storage
|
|
|
|
// duration declared in the reaching scope of the local lambda expression.
|
2012-02-18 17:37:24 +08:00
|
|
|
// Note that the 'reaching scope' check happens in tryCaptureVariable().
|
2012-02-09 05:18:48 +08:00
|
|
|
if (!Var) {
|
|
|
|
Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2012-09-19 05:11:30 +08:00
|
|
|
// Ignore invalid decls; they'll just confuse the code later.
|
|
|
|
if (Var->isInvalidDecl())
|
|
|
|
continue;
|
|
|
|
|
2012-02-09 05:18:48 +08:00
|
|
|
if (!Var->hasLocalStorage()) {
|
|
|
|
Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
|
|
|
|
Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2012-02-15 03:27:52 +08:00
|
|
|
// C++11 [expr.prim.lambda]p23:
|
|
|
|
// A capture followed by an ellipsis is a pack expansion (14.5.3).
|
|
|
|
SourceLocation EllipsisLoc;
|
|
|
|
if (C->EllipsisLoc.isValid()) {
|
|
|
|
if (Var->isParameterPack()) {
|
|
|
|
EllipsisLoc = C->EllipsisLoc;
|
|
|
|
} else {
|
|
|
|
Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
|
|
|
|
<< SourceRange(C->Loc);
|
2018-07-31 03:24:48 +08:00
|
|
|
|
2012-02-15 03:27:52 +08:00
|
|
|
// Just ignore the ellipsis.
|
|
|
|
}
|
|
|
|
} else if (Var->isParameterPack()) {
|
2012-07-25 11:56:55 +08:00
|
|
|
ContainsUnexpandedParameterPack = true;
|
2012-02-15 03:27:52 +08:00
|
|
|
}
|
2013-09-28 12:02:39 +08:00
|
|
|
|
|
|
|
if (C->Init.isUsable()) {
|
|
|
|
buildInitCaptureField(LSI, Var);
|
|
|
|
} else {
|
|
|
|
TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
|
|
|
|
TryCapture_ExplicitByVal;
|
|
|
|
tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
|
|
|
|
}
|
2018-07-16 15:23:47 +08:00
|
|
|
if (!LSI->Captures.empty())
|
|
|
|
LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
|
2012-02-09 05:18:48 +08:00
|
|
|
}
|
2012-02-14 06:00:16 +08:00
|
|
|
finishLambdaExplicitCaptures(LSI);
|
2012-02-09 05:18:48 +08:00
|
|
|
|
2012-07-25 11:56:55 +08:00
|
|
|
LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
|
|
|
|
|
2012-02-15 06:28:59 +08:00
|
|
|
// Add lambda parameters into scope.
|
2018-10-26 04:15:03 +08:00
|
|
|
addLambdaParameters(Intro.Captures, Method, CurScope);
|
2012-02-09 05:18:48 +08:00
|
|
|
|
2012-02-14 06:00:16 +08:00
|
|
|
// Enter a new evaluation context to insulate the lambda from any
|
2012-02-09 08:47:04 +08:00
|
|
|
// cleanups from the enclosing full-expression.
|
2017-04-02 05:30:49 +08:00
|
|
|
PushExpressionEvaluationContext(
|
|
|
|
ExpressionEvaluationContext::PotentiallyEvaluated);
|
2012-02-09 05:18:48 +08:00
|
|
|
}
|
|
|
|
|
2012-02-14 06:00:16 +08:00
|
|
|
void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
|
|
|
|
bool IsInstantiation) {
|
2015-04-28 05:27:54 +08:00
|
|
|
LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
|
2014-04-27 02:29:13 +08:00
|
|
|
|
2012-02-09 05:18:48 +08:00
|
|
|
// Leave the expression-evaluation context.
|
|
|
|
DiscardCleanupsInEvaluationContext();
|
|
|
|
PopExpressionEvaluationContext();
|
|
|
|
|
|
|
|
// Leave the context of the lambda.
|
2012-02-14 06:00:16 +08:00
|
|
|
if (!IsInstantiation)
|
|
|
|
PopDeclContext();
|
2012-02-09 09:28:42 +08:00
|
|
|
|
|
|
|
// Finalize the lambda.
|
|
|
|
CXXRecordDecl *Class = LSI->Lambda;
|
|
|
|
Class->setInvalidDecl();
|
2014-03-10 21:43:55 +08:00
|
|
|
SmallVector<Decl*, 4> Fields(Class->fields());
|
2014-05-26 14:22:03 +08:00
|
|
|
ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
|
2018-07-13 05:09:05 +08:00
|
|
|
SourceLocation(), ParsedAttributesView());
|
2012-02-09 09:28:42 +08:00
|
|
|
CheckCompletedCXXClass(Class);
|
|
|
|
|
2012-02-09 05:18:48 +08:00
|
|
|
PopFunctionScopeInfo();
|
|
|
|
}
|
|
|
|
|
2018-01-03 07:52:42 +08:00
|
|
|
QualType Sema::getLambdaConversionFunctionResultType(
|
|
|
|
const FunctionProtoType *CallOpProto) {
|
|
|
|
// The function type inside the pointer type is the same as the call
|
|
|
|
// operator with some tweaks. The calling convention is the default free
|
|
|
|
// function convention, and the type qualifications are lost.
|
2018-07-31 03:24:48 +08:00
|
|
|
const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
|
|
|
|
CallOpProto->getExtProtoInfo();
|
2018-01-03 07:52:42 +08:00
|
|
|
FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
|
|
|
|
CallingConv CC = Context.getDefaultCallingConvention(
|
|
|
|
CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
|
|
|
|
InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
|
2018-12-12 23:06:16 +08:00
|
|
|
InvokerExtInfo.TypeQuals = 0;
|
2018-07-31 03:24:48 +08:00
|
|
|
assert(InvokerExtInfo.RefQualifier == RQ_None &&
|
2018-01-03 07:52:42 +08:00
|
|
|
"Lambda's call operator should not have a reference qualifier");
|
|
|
|
return Context.getFunctionType(CallOpProto->getReturnType(),
|
|
|
|
CallOpProto->getParamTypes(), InvokerExtInfo);
|
|
|
|
}
|
|
|
|
|
2018-05-09 09:00:01 +08:00
|
|
|
/// Add a lambda's conversion to function pointer, as described in
|
2012-02-16 06:00:51 +08:00
|
|
|
/// C++11 [expr.prim.lambda]p6.
|
2016-07-25 07:12:40 +08:00
|
|
|
static void addFunctionPointerConversion(Sema &S,
|
2012-02-16 06:00:51 +08:00
|
|
|
SourceRange IntroducerRange,
|
|
|
|
CXXRecordDecl *Class,
|
|
|
|
CXXMethodDecl *CallOperator) {
|
2015-12-03 05:58:08 +08:00
|
|
|
// This conversion is explicitly disabled if the lambda's function has
|
|
|
|
// pass_object_size attributes on any of its parameters.
|
2016-07-25 07:12:40 +08:00
|
|
|
auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
|
|
|
|
return P->hasAttr<PassObjectSizeAttr>();
|
|
|
|
};
|
|
|
|
if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
|
2015-12-03 05:58:08 +08:00
|
|
|
return;
|
|
|
|
|
2012-02-17 11:02:34 +08:00
|
|
|
// Add the conversion to function pointer.
|
2018-01-03 07:52:42 +08:00
|
|
|
QualType InvokerFunctionTy = S.getLambdaConversionFunctionResultType(
|
|
|
|
CallOperator->getType()->castAs<FunctionProtoType>());
|
|
|
|
QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
|
2013-08-28 07:08:25 +08:00
|
|
|
|
2013-10-24 09:05:22 +08:00
|
|
|
// Create the type of the conversion function.
|
|
|
|
FunctionProtoType::ExtProtoInfo ConvExtInfo(
|
|
|
|
S.Context.getDefaultCallingConvention(
|
2013-08-28 07:08:25 +08:00
|
|
|
/*IsVariadic=*/false, /*IsCXXMethod=*/true));
|
2013-10-24 09:05:22 +08:00
|
|
|
// The conversion function is always const.
|
2018-12-12 23:06:16 +08:00
|
|
|
ConvExtInfo.TypeQuals = Qualifiers::Const;
|
2018-07-31 03:24:48 +08:00
|
|
|
QualType ConvTy =
|
2013-10-24 09:05:22 +08:00
|
|
|
S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
|
2013-08-28 07:08:25 +08:00
|
|
|
|
2012-02-16 06:00:51 +08:00
|
|
|
SourceLocation Loc = IntroducerRange.getBegin();
|
2013-10-24 09:05:22 +08:00
|
|
|
DeclarationName ConversionName
|
2012-02-16 06:00:51 +08:00
|
|
|
= S.Context.DeclarationNames.getCXXConversionFunctionName(
|
2013-10-24 09:05:22 +08:00
|
|
|
S.Context.getCanonicalType(PtrToFunctionTy));
|
|
|
|
DeclarationNameLoc ConvNameLoc;
|
|
|
|
// Construct a TypeSourceInfo for the conversion function, and wire
|
2018-07-31 03:24:48 +08:00
|
|
|
// all the parameters appropriately for the FunctionProtoTypeLoc
|
|
|
|
// so that everything works during transformation/instantiation of
|
2013-10-24 09:05:22 +08:00
|
|
|
// generic lambdas.
|
|
|
|
// The main reason for wiring up the parameters of the conversion
|
|
|
|
// function with that of the call operator is so that constructs
|
|
|
|
// like the following work:
|
|
|
|
// auto L = [](auto b) { <-- 1
|
|
|
|
// return [](auto a) -> decltype(a) { <-- 2
|
|
|
|
// return a;
|
|
|
|
// };
|
|
|
|
// };
|
2018-07-31 03:24:48 +08:00
|
|
|
// int (*fp)(int) = L(5);
|
2013-10-24 09:05:22 +08:00
|
|
|
// Because the trailing return type can contain DeclRefExprs that refer
|
2018-07-31 03:24:48 +08:00
|
|
|
// to the original call operator's variables, we hijack the call
|
2013-10-24 09:05:22 +08:00
|
|
|
// operators ParmVarDecls below.
|
2018-07-31 03:24:48 +08:00
|
|
|
TypeSourceInfo *ConvNamePtrToFunctionTSI =
|
2013-10-24 09:05:22 +08:00
|
|
|
S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
|
|
|
|
ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI;
|
|
|
|
|
|
|
|
// The conversion function is a conversion to a pointer-to-function.
|
|
|
|
TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
|
2018-07-31 03:24:48 +08:00
|
|
|
FunctionProtoTypeLoc ConvTL =
|
2013-10-24 09:05:22 +08:00
|
|
|
ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
|
|
|
|
// Get the result of the conversion function which is a pointer-to-function.
|
2018-07-31 03:24:48 +08:00
|
|
|
PointerTypeLoc PtrToFunctionTL =
|
2014-01-26 07:51:36 +08:00
|
|
|
ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
|
2013-10-24 09:05:22 +08:00
|
|
|
// Do the same for the TypeSourceInfo that is used to name the conversion
|
|
|
|
// operator.
|
2018-07-31 03:24:48 +08:00
|
|
|
PointerTypeLoc ConvNamePtrToFunctionTL =
|
2013-10-24 09:05:22 +08:00
|
|
|
ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
|
2018-07-31 03:24:48 +08:00
|
|
|
|
2013-10-24 09:05:22 +08:00
|
|
|
// Get the underlying function types that the conversion function will
|
|
|
|
// be converting to (should match the type of the call operator).
|
2018-07-31 03:24:48 +08:00
|
|
|
FunctionProtoTypeLoc CallOpConvTL =
|
2013-10-24 09:05:22 +08:00
|
|
|
PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
|
2018-07-31 03:24:48 +08:00
|
|
|
FunctionProtoTypeLoc CallOpConvNameTL =
|
2013-10-24 09:05:22 +08:00
|
|
|
ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
|
2018-07-31 03:24:48 +08:00
|
|
|
|
2013-10-24 09:05:22 +08:00
|
|
|
// Wire up the FunctionProtoTypeLocs with the call operator's parameters.
|
|
|
|
// These parameter's are essentially used to transform the name and
|
|
|
|
// the type of the conversion operator. By using the same parameters
|
|
|
|
// as the call operator's we don't have to fix any back references that
|
2018-07-31 03:24:48 +08:00
|
|
|
// the trailing return type of the call operator's uses (such as
|
2013-10-24 09:05:22 +08:00
|
|
|
// decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
|
2018-07-31 03:24:48 +08:00
|
|
|
// - we can simply use the return type of the call operator, and
|
|
|
|
// everything should work.
|
2013-10-24 09:05:22 +08:00
|
|
|
SmallVector<ParmVarDecl *, 4> InvokerParams;
|
|
|
|
for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
|
|
|
|
ParmVarDecl *From = CallOperator->getParamDecl(I);
|
|
|
|
|
2018-08-10 05:08:08 +08:00
|
|
|
InvokerParams.push_back(ParmVarDecl::Create(
|
|
|
|
S.Context,
|
|
|
|
// Temporarily add to the TU. This is set to the invoker below.
|
|
|
|
S.Context.getTranslationUnitDecl(), From->getBeginLoc(),
|
|
|
|
From->getLocation(), From->getIdentifier(), From->getType(),
|
|
|
|
From->getTypeSourceInfo(), From->getStorageClass(),
|
|
|
|
/*DefaultArg=*/nullptr));
|
2014-01-21 08:32:38 +08:00
|
|
|
CallOpConvTL.setParam(I, From);
|
|
|
|
CallOpConvNameTL.setParam(I, From);
|
2013-10-24 09:05:22 +08:00
|
|
|
}
|
|
|
|
|
2018-08-10 05:09:38 +08:00
|
|
|
CXXConversionDecl *Conversion = CXXConversionDecl::Create(
|
|
|
|
S.Context, Class, Loc,
|
|
|
|
DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
|
|
|
|
/*isInline=*/true, /*isExplicit=*/false,
|
|
|
|
/*isConstexpr=*/S.getLangOpts().CPlusPlus17,
|
|
|
|
CallOperator->getBody()->getEndLoc());
|
2012-02-16 06:00:51 +08:00
|
|
|
Conversion->setAccess(AS_public);
|
|
|
|
Conversion->setImplicit(true);
|
2013-09-29 16:45:24 +08:00
|
|
|
|
|
|
|
if (Class->isGenericLambda()) {
|
|
|
|
// Create a template version of the conversion operator, using the template
|
|
|
|
// parameter list of the function call operator.
|
2018-07-31 03:24:48 +08:00
|
|
|
FunctionTemplateDecl *TemplateCallOperator =
|
2013-09-29 16:45:24 +08:00
|
|
|
CallOperator->getDescribedFunctionTemplate();
|
|
|
|
FunctionTemplateDecl *ConversionTemplate =
|
|
|
|
FunctionTemplateDecl::Create(S.Context, Class,
|
2013-10-24 09:05:22 +08:00
|
|
|
Loc, ConversionName,
|
2013-09-29 16:45:24 +08:00
|
|
|
TemplateCallOperator->getTemplateParameters(),
|
|
|
|
Conversion);
|
|
|
|
ConversionTemplate->setAccess(AS_public);
|
|
|
|
ConversionTemplate->setImplicit(true);
|
|
|
|
Conversion->setDescribedFunctionTemplate(ConversionTemplate);
|
|
|
|
Class->addDecl(ConversionTemplate);
|
|
|
|
} else
|
|
|
|
Class->addDecl(Conversion);
|
Implement a rudimentary form of generic lambdas.
Specifically, the following features are not included in this commit:
- any sort of capturing within generic lambdas
- generic lambdas within template functions and nested
within other generic lambdas
- conversion operator for captureless lambdas
- ensuring all visitors are generic lambda aware
(Although I have gotten some useful feedback on my patches of the above and will be incorporating that as I submit those patches for commit)
As an example of what compiles through this commit:
template <class F1, class F2>
struct overload : F1, F2 {
using F1::operator();
using F2::operator();
overload(F1 f1, F2 f2) : F1(f1), F2(f2) { }
};
auto Recursive = [](auto Self, auto h, auto ... rest) {
return 1 + Self(Self, rest...);
};
auto Base = [](auto Self, auto h) {
return 1;
};
overload<decltype(Base), decltype(Recursive)> O(Base, Recursive);
int num_params = O(O, 5, 3, "abc", 3.14, 'a');
Please see attached tests for more examples.
This patch has been reviewed by Doug and Richard. Minor changes (non-functionality affecting) have been made since both of them formally looked at it, but the changes involve removal of supernumerary return type deduction changes (since they are now redundant, with richard having committed a recent patch to address return type deduction for C++11 lambdas using C++14 semantics).
Some implementation notes:
- Add a new Declarator context => LambdaExprParameterContext to
clang::Declarator to allow the use of 'auto' in declaring generic
lambda parameters
- Add various helpers to CXXRecordDecl to facilitate identifying
and querying a closure class
- LambdaScopeInfo (which maintains the current lambda's Sema state)
was augmented to house the current depth of the template being
parsed (id est the Parser calls Sema::RecordParsingTemplateParameterDepth)
so that SemaType.cpp::ConvertDeclSpecToType may use it to immediately
generate a template-parameter-type when 'auto' is parsed in a generic
lambda parameter context. (i.e we do NOT use AutoType deduced to
a template parameter type - Richard seemed ok with this approach).
We encode that this template type was generated from an auto by simply
adding $auto to the name which can be used for better diagnostics if needed.
- SemaLambda.h was added to hold some common lambda utility
functions (this file is likely to grow ...)
- Teach Sema::ActOnStartOfFunctionDef to check whether it
is being called to instantiate a generic lambda's call
operator, and if so, push an appropriately prepared
LambdaScopeInfo object on the stack.
- various tests were added - but much more will be needed.
There is obviously more work to be done, and both Richard (weakly) and Doug (strongly)
have requested that LambdaExpr be removed form the CXXRecordDecl LambdaDefinitionaData
in a future patch which is forthcoming.
A greatful thanks to all reviewers including Eli Friedman, James Dennett,
and especially the two gracious wizards (Richard Smith and Doug Gregor)
who spent hours providing feedback (in person in Chicago and on the mailing lists).
And yet I am certain that I have allowed unidentified bugs to creep in; bugs, that I will do my best to slay, once identified!
Thanks!
llvm-svn: 191453
2013-09-27 03:54:12 +08:00
|
|
|
// Add a non-static member function that will be the result of
|
|
|
|
// the conversion with a certain unique ID.
|
2013-10-24 09:05:22 +08:00
|
|
|
DeclarationName InvokerName = &S.Context.Idents.get(
|
|
|
|
getLambdaStaticInvokerName());
|
2013-09-29 16:45:24 +08:00
|
|
|
// FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
|
|
|
|
// we should get a prebuilt TrivialTypeSourceInfo from Context
|
|
|
|
// using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
|
|
|
|
// then rewire the parameters accordingly, by hoisting up the InvokeParams
|
|
|
|
// loop below and then use its Params to set Invoke->setParams(...) below.
|
2018-07-31 03:24:48 +08:00
|
|
|
// This would avoid the 'const' qualifier of the calloperator from
|
|
|
|
// contaminating the type of the invoker, which is currently adjusted
|
2013-10-24 09:05:22 +08:00
|
|
|
// in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
|
|
|
|
// trailing return type of the invoker would require a visitor to rebuild
|
|
|
|
// the trailing return type and adjusting all back DeclRefExpr's to refer
|
|
|
|
// to the new static invoker parameters - not the call operator's.
|
2018-08-10 05:09:38 +08:00
|
|
|
CXXMethodDecl *Invoke = CXXMethodDecl::Create(
|
|
|
|
S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
|
|
|
|
InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
|
|
|
|
/*IsInline=*/true,
|
|
|
|
/*IsConstexpr=*/false, CallOperator->getBody()->getEndLoc());
|
2013-10-24 09:05:22 +08:00
|
|
|
for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
|
|
|
|
InvokerParams[I]->setOwningFunction(Invoke);
|
|
|
|
Invoke->setParams(InvokerParams);
|
2012-02-17 11:02:34 +08:00
|
|
|
Invoke->setAccess(AS_private);
|
|
|
|
Invoke->setImplicit(true);
|
2013-09-29 16:45:24 +08:00
|
|
|
if (Class->isGenericLambda()) {
|
2018-07-31 03:24:48 +08:00
|
|
|
FunctionTemplateDecl *TemplateCallOperator =
|
2013-09-29 16:45:24 +08:00
|
|
|
CallOperator->getDescribedFunctionTemplate();
|
|
|
|
FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
|
2013-10-24 09:05:22 +08:00
|
|
|
S.Context, Class, Loc, InvokerName,
|
2013-09-29 16:45:24 +08:00
|
|
|
TemplateCallOperator->getTemplateParameters(),
|
|
|
|
Invoke);
|
|
|
|
StaticInvokerTemplate->setAccess(AS_private);
|
|
|
|
StaticInvokerTemplate->setImplicit(true);
|
|
|
|
Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
|
|
|
|
Class->addDecl(StaticInvokerTemplate);
|
|
|
|
} else
|
|
|
|
Class->addDecl(Invoke);
|
2012-02-16 06:00:51 +08:00
|
|
|
}
|
|
|
|
|
2018-05-09 09:00:01 +08:00
|
|
|
/// Add a lambda's conversion to block pointer.
|
2018-07-31 03:24:48 +08:00
|
|
|
static void addBlockPointerConversion(Sema &S,
|
2012-02-16 06:08:38 +08:00
|
|
|
SourceRange IntroducerRange,
|
|
|
|
CXXRecordDecl *Class,
|
|
|
|
CXXMethodDecl *CallOperator) {
|
2018-01-03 07:52:42 +08:00
|
|
|
QualType FunctionTy = S.getLambdaConversionFunctionResultType(
|
|
|
|
CallOperator->getType()->castAs<FunctionProtoType>());
|
2015-04-02 04:22:13 +08:00
|
|
|
QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
|
|
|
|
|
|
|
|
FunctionProtoType::ExtProtoInfo ConversionEPI(
|
|
|
|
S.Context.getDefaultCallingConvention(
|
|
|
|
/*IsVariadic=*/false, /*IsCXXMethod=*/true));
|
2018-12-12 23:06:16 +08:00
|
|
|
ConversionEPI.TypeQuals = Qualifiers::Const;
|
2015-04-02 04:22:13 +08:00
|
|
|
QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ConversionEPI);
|
2013-08-28 07:08:25 +08:00
|
|
|
|
2012-02-16 06:08:38 +08:00
|
|
|
SourceLocation Loc = IntroducerRange.getBegin();
|
|
|
|
DeclarationName Name
|
|
|
|
= S.Context.DeclarationNames.getCXXConversionFunctionName(
|
|
|
|
S.Context.getCanonicalType(BlockPtrTy));
|
|
|
|
DeclarationNameLoc NameLoc;
|
|
|
|
NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
|
2018-08-10 05:09:38 +08:00
|
|
|
CXXConversionDecl *Conversion = CXXConversionDecl::Create(
|
|
|
|
S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
|
|
|
|
S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
|
|
|
|
/*isInline=*/true, /*isExplicit=*/false,
|
|
|
|
/*isConstexpr=*/false, CallOperator->getBody()->getEndLoc());
|
2012-02-16 06:08:38 +08:00
|
|
|
Conversion->setAccess(AS_public);
|
|
|
|
Conversion->setImplicit(true);
|
|
|
|
Class->addDecl(Conversion);
|
|
|
|
}
|
2015-04-28 05:27:54 +08:00
|
|
|
|
2018-09-14 07:28:25 +08:00
|
|
|
static ExprResult performLambdaVarCaptureInitialization(
|
|
|
|
Sema &S, const Capture &Capture, FieldDecl *Field,
|
|
|
|
SourceLocation ImplicitCaptureLoc, bool IsImplicitCapture) {
|
2015-04-28 05:27:54 +08:00
|
|
|
assert(Capture.isVariableCapture() && "not a variable capture");
|
|
|
|
|
|
|
|
auto *Var = Capture.getVariable();
|
2018-09-14 07:28:25 +08:00
|
|
|
SourceLocation Loc =
|
|
|
|
IsImplicitCapture ? ImplicitCaptureLoc : Capture.getLocation();
|
2015-04-28 05:27:54 +08:00
|
|
|
|
|
|
|
// C++11 [expr.prim.lambda]p21:
|
|
|
|
// When the lambda-expression is evaluated, the entities that
|
|
|
|
// are captured by copy are used to direct-initialize each
|
|
|
|
// corresponding non-static data member of the resulting closure
|
|
|
|
// object. (For array members, the array elements are
|
|
|
|
// direct-initialized in increasing subscript order.) These
|
|
|
|
// initializations are performed in the (unspecified) order in
|
|
|
|
// which the non-static data members are declared.
|
2018-07-31 03:24:48 +08:00
|
|
|
|
2015-04-28 05:27:54 +08:00
|
|
|
// C++ [expr.prim.lambda]p12:
|
|
|
|
// An entity captured by a lambda-expression is odr-used (3.2) in
|
|
|
|
// the scope containing the lambda-expression.
|
|
|
|
ExprResult RefResult = S.BuildDeclarationNameExpr(
|
|
|
|
CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
|
|
|
|
if (RefResult.isInvalid())
|
|
|
|
return ExprError();
|
|
|
|
Expr *Ref = RefResult.get();
|
|
|
|
|
2016-12-14 08:03:17 +08:00
|
|
|
auto Entity = InitializedEntity::InitializeLambdaCapture(
|
|
|
|
Var->getIdentifier(), Field->getType(), Loc);
|
2015-04-28 05:27:54 +08:00
|
|
|
InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
|
2016-12-14 08:03:17 +08:00
|
|
|
InitializationSequence Init(S, Entity, InitKind, Ref);
|
|
|
|
return Init.Perform(S, Entity, InitKind, Ref);
|
2015-04-28 05:27:54 +08:00
|
|
|
}
|
2018-07-31 03:24:48 +08:00
|
|
|
|
|
|
|
ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
|
2015-04-28 05:27:54 +08:00
|
|
|
Scope *CurScope) {
|
|
|
|
LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
|
|
|
|
ActOnFinishFunctionBody(LSI.CallOperator, Body);
|
2018-08-10 05:09:38 +08:00
|
|
|
return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
|
2015-04-28 05:27:54 +08:00
|
|
|
}
|
|
|
|
|
2015-04-29 01:34:38 +08:00
|
|
|
static LambdaCaptureDefault
|
|
|
|
mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {
|
|
|
|
switch (ICS) {
|
|
|
|
case CapturingScopeInfo::ImpCap_None:
|
|
|
|
return LCD_None;
|
|
|
|
case CapturingScopeInfo::ImpCap_LambdaByval:
|
|
|
|
return LCD_ByCopy;
|
|
|
|
case CapturingScopeInfo::ImpCap_CapturedRegion:
|
|
|
|
case CapturingScopeInfo::ImpCap_LambdaByref:
|
|
|
|
return LCD_ByRef;
|
|
|
|
case CapturingScopeInfo::ImpCap_Block:
|
|
|
|
llvm_unreachable("block capture in lambda");
|
|
|
|
}
|
|
|
|
llvm_unreachable("Unknown implicit capture style");
|
|
|
|
}
|
|
|
|
|
2018-03-08 06:48:35 +08:00
|
|
|
bool Sema::CaptureHasSideEffects(const Capture &From) {
|
2017-01-13 23:01:06 +08:00
|
|
|
if (!From.isVLATypeCapture()) {
|
|
|
|
Expr *Init = From.getInitExpr();
|
|
|
|
if (Init && Init->HasSideEffects(Context))
|
2017-03-01 18:23:38 +08:00
|
|
|
return true;
|
2017-01-13 23:01:06 +08:00
|
|
|
}
|
|
|
|
|
2017-03-01 18:23:38 +08:00
|
|
|
if (!From.isCopyCapture())
|
|
|
|
return false;
|
|
|
|
|
|
|
|
const QualType T = From.isThisCapture()
|
|
|
|
? getCurrentThisType()->getPointeeType()
|
|
|
|
: From.getCaptureType();
|
|
|
|
|
|
|
|
if (T.isVolatileQualified())
|
|
|
|
return true;
|
|
|
|
|
|
|
|
const Type *BaseT = T->getBaseElementTypeUnsafe();
|
|
|
|
if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
|
|
|
|
return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
|
|
|
|
!RD->hasTrivialDestructor();
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2018-07-16 15:23:47 +08:00
|
|
|
bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
|
|
|
|
const Capture &From) {
|
2017-03-01 18:23:38 +08:00
|
|
|
if (CaptureHasSideEffects(From))
|
2018-07-16 15:23:47 +08:00
|
|
|
return false;
|
2017-03-01 18:23:38 +08:00
|
|
|
|
2017-12-12 02:00:36 +08:00
|
|
|
if (From.isVLATypeCapture())
|
2018-07-16 15:23:47 +08:00
|
|
|
return false;
|
2017-12-12 02:00:36 +08:00
|
|
|
|
2017-01-13 23:01:06 +08:00
|
|
|
auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
|
|
|
|
if (From.isThisCapture())
|
|
|
|
diag << "'this'";
|
|
|
|
else
|
|
|
|
diag << From.getVariable();
|
|
|
|
diag << From.isNonODRUsed();
|
2018-07-16 15:23:47 +08:00
|
|
|
diag << FixItHint::CreateRemoval(CaptureRange);
|
|
|
|
return true;
|
2017-01-13 23:01:06 +08:00
|
|
|
}
|
|
|
|
|
2015-04-28 05:27:54 +08:00
|
|
|
ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
|
|
|
|
LambdaScopeInfo *LSI) {
|
2012-02-09 05:18:48 +08:00
|
|
|
// Collect information from the lambda scope.
|
2014-05-11 00:31:55 +08:00
|
|
|
SmallVector<LambdaCapture, 4> Captures;
|
2013-01-13 03:30:44 +08:00
|
|
|
SmallVector<Expr *, 4> CaptureInits;
|
2015-04-29 01:34:38 +08:00
|
|
|
SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
|
|
|
|
LambdaCaptureDefault CaptureDefault =
|
|
|
|
mapImplicitCaptureStyle(LSI->ImpCaptureStyle);
|
2012-02-09 05:18:48 +08:00
|
|
|
CXXRecordDecl *Class;
|
2012-02-10 16:36:38 +08:00
|
|
|
CXXMethodDecl *CallOperator;
|
2012-02-09 05:18:48 +08:00
|
|
|
SourceRange IntroducerRange;
|
|
|
|
bool ExplicitParams;
|
2012-02-14 06:00:16 +08:00
|
|
|
bool ExplicitResultType;
|
2016-06-22 04:29:17 +08:00
|
|
|
CleanupInfo LambdaCleanup;
|
2012-07-25 11:56:55 +08:00
|
|
|
bool ContainsUnexpandedParameterPack;
|
2017-06-14 02:38:31 +08:00
|
|
|
bool IsGenericLambda;
|
2012-02-09 05:18:48 +08:00
|
|
|
{
|
2012-02-10 16:36:38 +08:00
|
|
|
CallOperator = LSI->CallOperator;
|
2012-02-09 05:18:48 +08:00
|
|
|
Class = LSI->Lambda;
|
|
|
|
IntroducerRange = LSI->IntroducerRange;
|
|
|
|
ExplicitParams = LSI->ExplicitParams;
|
2012-02-14 06:00:16 +08:00
|
|
|
ExplicitResultType = !LSI->HasImplicitReturnType;
|
2016-06-22 04:29:17 +08:00
|
|
|
LambdaCleanup = LSI->Cleanup;
|
2012-07-25 11:56:55 +08:00
|
|
|
ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
|
2017-06-14 02:38:31 +08:00
|
|
|
IsGenericLambda = Class->isGenericLambda();
|
|
|
|
|
2015-04-28 05:27:54 +08:00
|
|
|
CallOperator->setLexicalDeclContext(Class);
|
2018-07-31 03:24:48 +08:00
|
|
|
Decl *TemplateOrNonTemplateCallOperatorDecl =
|
|
|
|
CallOperator->getDescribedFunctionTemplate()
|
|
|
|
? CallOperator->getDescribedFunctionTemplate()
|
2015-04-28 05:27:54 +08:00
|
|
|
: cast<Decl>(CallOperator);
|
|
|
|
|
|
|
|
TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
|
|
|
|
Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
|
|
|
|
|
|
|
|
PopExpressionEvaluationContext();
|
|
|
|
|
2012-02-09 05:18:48 +08:00
|
|
|
// Translate captures.
|
2015-04-28 05:27:54 +08:00
|
|
|
auto CurField = Class->field_begin();
|
2018-07-16 15:23:47 +08:00
|
|
|
// True if the current capture has a used capture or default before it.
|
|
|
|
bool CurHasPreviousCapture = CaptureDefault != LCD_None;
|
|
|
|
SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
|
|
|
|
CaptureDefaultLoc : IntroducerRange.getBegin();
|
|
|
|
|
2015-04-28 05:27:54 +08:00
|
|
|
for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I, ++CurField) {
|
2018-03-08 06:48:35 +08:00
|
|
|
const Capture &From = LSI->Captures[I];
|
2018-07-16 15:23:47 +08:00
|
|
|
|
2012-02-09 05:18:48 +08:00
|
|
|
assert(!From.isBlockCapture() && "Cannot capture __block variables");
|
|
|
|
bool IsImplicit = I >= LSI->NumExplicitCaptures;
|
|
|
|
|
2018-07-16 15:23:47 +08:00
|
|
|
// Use source ranges of explicit captures for fixits where available.
|
|
|
|
SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
|
|
|
|
|
2017-01-13 23:01:06 +08:00
|
|
|
// Warn about unused explicit captures.
|
2018-07-16 15:23:47 +08:00
|
|
|
bool IsCaptureUsed = true;
|
2017-06-14 02:38:31 +08:00
|
|
|
if (!CurContext->isDependentContext() && !IsImplicit && !From.isODRUsed()) {
|
|
|
|
// Initialized captures that are non-ODR used may not be eliminated.
|
|
|
|
bool NonODRUsedInitCapture =
|
|
|
|
IsGenericLambda && From.isNonODRUsed() && From.getInitExpr();
|
2018-07-16 15:23:47 +08:00
|
|
|
if (!NonODRUsedInitCapture) {
|
|
|
|
bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
|
2018-07-20 16:19:20 +08:00
|
|
|
SourceRange FixItRange;
|
2018-07-16 15:23:47 +08:00
|
|
|
if (CaptureRange.isValid()) {
|
|
|
|
if (!CurHasPreviousCapture && !IsLast) {
|
|
|
|
// If there are no captures preceding this capture, remove the
|
|
|
|
// following comma.
|
|
|
|
FixItRange = SourceRange(CaptureRange.getBegin(),
|
|
|
|
getLocForEndOfToken(CaptureRange.getEnd()));
|
|
|
|
} else {
|
|
|
|
// Otherwise, remove the comma since the last used capture.
|
|
|
|
FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
|
|
|
|
CaptureRange.getEnd());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (CaptureRange.isValid()) {
|
|
|
|
CurHasPreviousCapture |= IsCaptureUsed;
|
|
|
|
PrevCaptureLoc = CaptureRange.getEnd();
|
2017-06-14 02:38:31 +08:00
|
|
|
}
|
2017-01-13 23:01:06 +08:00
|
|
|
|
2012-02-09 05:18:48 +08:00
|
|
|
// Handle 'this' capture.
|
|
|
|
if (From.isThisCapture()) {
|
2018-07-07 13:58:48 +08:00
|
|
|
// Capturing 'this' implicitly with a default of '[=]' is deprecated,
|
|
|
|
// because it results in a reference capture. Don't warn prior to
|
|
|
|
// C++2a; there's nothing that can be done about it before then.
|
|
|
|
if (getLangOpts().CPlusPlus2a && IsImplicit &&
|
|
|
|
CaptureDefault == LCD_ByCopy) {
|
|
|
|
Diag(From.getLocation(), diag::warn_deprecated_this_capture);
|
|
|
|
Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
|
|
|
|
<< FixItHint::CreateInsertion(
|
|
|
|
getLocForEndOfToken(CaptureDefaultLoc), ", this");
|
|
|
|
}
|
|
|
|
|
2014-05-11 00:31:55 +08:00
|
|
|
Captures.push_back(
|
[Cxx1z] Implement Lambda Capture of *this by Value as [=,*this] (P0018R3)
Implement lambda capture of *this by copy.
For e.g.:
struct A {
int d = 10;
auto foo() { return [*this] (auto a) mutable { d+=a; return d; }; }
};
auto L = A{}.foo(); // A{}'s lifetime is gone.
// Below is still ok, because *this was captured by value.
assert(L(10) == 20);
assert(L(100) == 120);
If the capture was implicit, or [this] (i.e. *this was captured by reference), this code would be otherwise undefined.
Implementation Strategy:
- amend the parser to accept *this in the lambda introducer
- add a new king of capture LCK_StarThis
- teach Sema::CheckCXXThisCapture to handle by copy captures of the
enclosing object (i.e. *this)
- when CheckCXXThisCapture does capture by copy, the corresponding
initializer expression for the closure's data member
direct-initializes it thus making a copy of '*this'.
- in codegen, when assigning to CXXThisValue, if *this was captured by
copy, make sure it points to the corresponding field member, and
not, unlike when captured by reference, what the field member points
to.
- mark feature as implemented in svn
Much gratitude to Richard Smith for his carefully illuminating reviews!
llvm-svn: 263921
2016-03-21 17:25:37 +08:00
|
|
|
LambdaCapture(From.getLocation(), IsImplicit,
|
|
|
|
From.isCopyCapture() ? LCK_StarThis : LCK_This));
|
|
|
|
CaptureInits.push_back(From.getInitExpr());
|
2012-02-09 05:18:48 +08:00
|
|
|
continue;
|
|
|
|
}
|
2014-08-28 12:28:19 +08:00
|
|
|
if (From.isVLATypeCapture()) {
|
|
|
|
Captures.push_back(
|
|
|
|
LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType));
|
|
|
|
CaptureInits.push_back(nullptr);
|
|
|
|
continue;
|
|
|
|
}
|
2012-02-09 05:18:48 +08:00
|
|
|
|
|
|
|
VarDecl *Var = From.getVariable();
|
2015-04-28 05:27:54 +08:00
|
|
|
LambdaCaptureKind Kind = From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef;
|
2014-05-11 00:31:55 +08:00
|
|
|
Captures.push_back(LambdaCapture(From.getLocation(), IsImplicit, Kind,
|
|
|
|
Var, From.getEllipsisLoc()));
|
2015-04-28 05:27:54 +08:00
|
|
|
Expr *Init = From.getInitExpr();
|
|
|
|
if (!Init) {
|
2018-09-14 07:28:25 +08:00
|
|
|
auto InitResult = performLambdaVarCaptureInitialization(
|
|
|
|
*this, From, *CurField, CaptureDefaultLoc, IsImplicit);
|
2015-04-28 05:27:54 +08:00
|
|
|
if (InitResult.isInvalid())
|
|
|
|
return ExprError();
|
|
|
|
Init = InitResult.get();
|
|
|
|
}
|
|
|
|
CaptureInits.push_back(Init);
|
2012-02-09 05:18:48 +08:00
|
|
|
}
|
|
|
|
|
2012-02-11 00:13:20 +08:00
|
|
|
// C++11 [expr.prim.lambda]p6:
|
|
|
|
// The closure type for a lambda-expression with no lambda-capture
|
|
|
|
// has a public non-virtual non-explicit const conversion function
|
|
|
|
// to pointer to function having the same parameter and return
|
|
|
|
// types as the closure type's function call operator.
|
2012-02-16 06:00:51 +08:00
|
|
|
if (Captures.empty() && CaptureDefault == LCD_None)
|
|
|
|
addFunctionPointerConversion(*this, IntroducerRange, Class,
|
|
|
|
CallOperator);
|
2012-02-09 08:47:04 +08:00
|
|
|
|
2012-02-16 06:08:38 +08:00
|
|
|
// Objective-C++:
|
|
|
|
// The closure type for a lambda-expression has a public non-virtual
|
|
|
|
// non-explicit const conversion function to a block pointer having the
|
|
|
|
// same parameter and return types as the closure type's function call
|
|
|
|
// operator.
|
2013-09-29 16:45:24 +08:00
|
|
|
// FIXME: Fix generic lambda to block conversions.
|
2018-10-31 04:31:30 +08:00
|
|
|
if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
|
2012-02-16 06:08:38 +08:00
|
|
|
addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
|
2018-07-31 03:24:48 +08:00
|
|
|
|
2012-02-11 00:13:20 +08:00
|
|
|
// Finalize the lambda class.
|
2014-03-10 21:43:55 +08:00
|
|
|
SmallVector<Decl*, 4> Fields(Class->fields());
|
2014-05-26 14:22:03 +08:00
|
|
|
ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
|
2018-07-13 05:09:05 +08:00
|
|
|
SourceLocation(), ParsedAttributesView());
|
2012-02-11 00:13:20 +08:00
|
|
|
CheckCompletedCXXClass(Class);
|
2012-02-09 05:18:48 +08:00
|
|
|
}
|
|
|
|
|
2016-06-22 04:29:17 +08:00
|
|
|
Cleanup.mergeFrom(LambdaCleanup);
|
|
|
|
|
2018-07-31 03:24:48 +08:00
|
|
|
LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
|
2013-08-10 07:08:25 +08:00
|
|
|
CaptureDefault, CaptureDefaultLoc,
|
2018-07-31 03:24:48 +08:00
|
|
|
Captures,
|
2012-02-14 06:00:16 +08:00
|
|
|
ExplicitParams, ExplicitResultType,
|
2016-12-14 08:03:17 +08:00
|
|
|
CaptureInits, EndLoc,
|
2012-07-25 11:56:55 +08:00
|
|
|
ContainsUnexpandedParameterPack);
|
2016-03-27 00:11:37 +08:00
|
|
|
// If the lambda expression's call operator is not explicitly marked constexpr
|
|
|
|
// and we are not in a dependent context, analyze the call operator to infer
|
2017-07-05 13:37:45 +08:00
|
|
|
// its constexpr-ness, suppressing diagnostics while doing so.
|
2017-12-05 04:27:34 +08:00
|
|
|
if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
|
2016-03-27 00:11:37 +08:00
|
|
|
!CallOperator->isConstexpr() &&
|
2017-05-24 23:44:57 +08:00
|
|
|
!isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
|
2016-03-27 00:11:37 +08:00
|
|
|
!Class->getDeclContext()->isDependentContext()) {
|
|
|
|
TentativeAnalysisScope DiagnosticScopeGuard(*this);
|
|
|
|
CallOperator->setConstexpr(
|
|
|
|
CheckConstexprFunctionDecl(CallOperator) &&
|
|
|
|
CheckConstexprFunctionBody(CallOperator, CallOperator->getBody()));
|
|
|
|
}
|
2013-10-25 17:12:52 +08:00
|
|
|
|
2016-11-11 00:19:11 +08:00
|
|
|
// Emit delayed shadowing warnings now that the full capture list is known.
|
|
|
|
DiagnoseShadowingLambdaDecls(LSI);
|
|
|
|
|
2012-02-14 08:00:48 +08:00
|
|
|
if (!CurContext->isDependentContext()) {
|
|
|
|
switch (ExprEvalContexts.back().Context) {
|
2013-10-25 17:12:52 +08:00
|
|
|
// C++11 [expr.prim.lambda]p2:
|
|
|
|
// A lambda-expression shall not appear in an unevaluated operand
|
|
|
|
// (Clause 5).
|
2017-04-02 05:30:49 +08:00
|
|
|
case ExpressionEvaluationContext::Unevaluated:
|
|
|
|
case ExpressionEvaluationContext::UnevaluatedList:
|
|
|
|
case ExpressionEvaluationContext::UnevaluatedAbstract:
|
2013-10-25 17:12:52 +08:00
|
|
|
// C++1y [expr.const]p2:
|
|
|
|
// A conditional-expression e is a core constant expression unless the
|
|
|
|
// evaluation of e, following the rules of the abstract machine, would
|
|
|
|
// evaluate [...] a lambda-expression.
|
2013-11-05 16:01:18 +08:00
|
|
|
//
|
|
|
|
// This is technically incorrect, there are some constant evaluated contexts
|
|
|
|
// where this should be allowed. We should probably fix this when DR1607 is
|
|
|
|
// ratified, it lays out the exact set of conditions where we shouldn't
|
|
|
|
// allow a lambda-expression.
|
2017-04-02 05:30:49 +08:00
|
|
|
case ExpressionEvaluationContext::ConstantEvaluated:
|
2012-02-14 08:00:48 +08:00
|
|
|
// We don't actually diagnose this case immediately, because we
|
|
|
|
// could be within a context where we might find out later that
|
|
|
|
// the expression is potentially evaluated (e.g., for typeid).
|
|
|
|
ExprEvalContexts.back().Lambdas.push_back(Lambda);
|
|
|
|
break;
|
2012-02-09 16:14:43 +08:00
|
|
|
|
2017-04-02 05:30:49 +08:00
|
|
|
case ExpressionEvaluationContext::DiscardedStatement:
|
|
|
|
case ExpressionEvaluationContext::PotentiallyEvaluated:
|
|
|
|
case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
|
2012-02-14 08:00:48 +08:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
This patch implements capturing of variables within generic lambdas.
Both Richard and I felt that the current wording in the working paper needed some tweaking - Please see http://llvm-reviews.chandlerc.com/D2035 for additional context and references to core-reflector messages that discuss wording tweaks.
What is implemented is what we had intended to specify in Bristol; but, recently felt that the specification might benefit from some tweaking and fleshing.
As a rough attempt to explain the semantics: If a nested lambda with a default-capture names a variable within its body, and if the enclosing full expression that contains the name of that variable is instantiation-dependent - then an enclosing lambda that is capture-ready (i.e. within a non-dependent context) must capture that variable, if all intervening nested lambdas can potentially capture that variable if they need to, and all intervening parent lambdas of the capture-ready lambda can and do capture the variable.
Of note, 'this' capturing is also currently underspecified in the working paper for generic lambdas. What is implemented here is if the set of candidate functions in a nested generic lambda includes both static and non-static member functions (regardless of viability checking - i.e. num and type of parameters/arguments) - and if all intervening nested-inner lambdas between the capture-ready lambda and the function-call containing nested lambda can capture 'this' and if all enclosing lambdas of the capture-ready lambda can capture 'this', then 'this' is speculatively captured by that capture-ready lambda.
Hopefully a paper for the C++ committee (that Richard and I had started some preliminary work on) is forthcoming.
This essentially makes generic lambdas feature complete, except for known bugs. The more prominent ones (and the ones I am currently aware of) being:
- generic lambdas and init-captures are broken - but a patch that fixes this is already in the works ...
- nested variadic expansions such as:
auto K = [](auto ... OuterArgs) {
vp([=](auto ... Is) {
decltype(OuterArgs) OA = OuterArgs;
return 0;
}(5)...);
return 0;
};
auto M = K('a', ' ', 1, " -- ", 3.14);
currently cause crashes. I think I know how to fix this (since I had done so in my initial implementation) - but it will probably take some work and back & forth with Doug and Richard.
A warm thanks to all who provided feedback - and especially to Doug Gregor and Richard Smith for their pivotal guidance: their insight and prestidigitation in such matters is boundless!
Now let's hope this commit doesn't upset the buildbot gods ;)
Thanks!
llvm-svn: 194188
2013-11-07 13:17:06 +08:00
|
|
|
|
2012-02-09 08:47:04 +08:00
|
|
|
return MaybeBindToTemporary(Lambda);
|
2012-02-09 05:18:48 +08:00
|
|
|
}
|
2012-03-01 12:01:32 +08:00
|
|
|
|
|
|
|
ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
|
|
|
|
SourceLocation ConvLocation,
|
|
|
|
CXXConversionDecl *Conv,
|
|
|
|
Expr *Src) {
|
|
|
|
// Make sure that the lambda call operator is marked used.
|
|
|
|
CXXRecordDecl *Lambda = Conv->getParent();
|
2018-07-31 03:24:48 +08:00
|
|
|
CXXMethodDecl *CallOperator
|
2012-03-01 12:01:32 +08:00
|
|
|
= cast<CXXMethodDecl>(
|
2012-12-19 08:45:41 +08:00
|
|
|
Lambda->lookup(
|
|
|
|
Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
|
2012-03-01 12:01:32 +08:00
|
|
|
CallOperator->setReferenced();
|
2013-09-05 08:02:25 +08:00
|
|
|
CallOperator->markUsed(Context);
|
2012-03-01 12:01:32 +08:00
|
|
|
|
|
|
|
ExprResult Init = PerformCopyInitialization(
|
2017-04-06 20:53:43 +08:00
|
|
|
InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType(),
|
|
|
|
/*NRVO=*/false),
|
|
|
|
CurrentLocation, Src);
|
2012-03-01 12:01:32 +08:00
|
|
|
if (!Init.isInvalid())
|
2014-05-29 18:55:11 +08:00
|
|
|
Init = ActOnFinishFullExpr(Init.get());
|
2018-07-31 03:24:48 +08:00
|
|
|
|
2012-03-01 12:01:32 +08:00
|
|
|
if (Init.isInvalid())
|
|
|
|
return ExprError();
|
2018-07-31 03:24:48 +08:00
|
|
|
|
2012-03-01 12:01:32 +08:00
|
|
|
// Create the new block to be returned.
|
|
|
|
BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
|
|
|
|
|
|
|
|
// Set the type information.
|
|
|
|
Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
|
|
|
|
Block->setIsVariadic(CallOperator->isVariadic());
|
|
|
|
Block->setBlockMissingReturnType(false);
|
|
|
|
|
|
|
|
// Add parameters.
|
|
|
|
SmallVector<ParmVarDecl *, 4> BlockParams;
|
|
|
|
for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
|
|
|
|
ParmVarDecl *From = CallOperator->getParamDecl(I);
|
2018-08-10 05:08:08 +08:00
|
|
|
BlockParams.push_back(ParmVarDecl::Create(
|
|
|
|
Context, Block, From->getBeginLoc(), From->getLocation(),
|
|
|
|
From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
|
|
|
|
From->getStorageClass(),
|
|
|
|
/*DefaultArg=*/nullptr));
|
2012-03-01 12:01:32 +08:00
|
|
|
}
|
|
|
|
Block->setParams(BlockParams);
|
|
|
|
|
|
|
|
Block->setIsConversionFromLambda(true);
|
|
|
|
|
|
|
|
// Add capture. The capture uses a fake variable, which doesn't correspond
|
|
|
|
// to any actual memory location. However, the initializer copy-initializes
|
|
|
|
// the lambda object.
|
|
|
|
TypeSourceInfo *CapVarTSI =
|
|
|
|
Context.getTrivialTypeSourceInfo(Src->getType());
|
|
|
|
VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
|
2014-05-26 14:22:03 +08:00
|
|
|
ConvLocation, nullptr,
|
2012-03-01 12:01:32 +08:00
|
|
|
Src->getType(), CapVarTSI,
|
2013-04-04 03:27:57 +08:00
|
|
|
SC_None);
|
2012-03-01 12:01:32 +08:00
|
|
|
BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
|
2014-05-29 18:55:11 +08:00
|
|
|
/*Nested=*/false, /*Copy=*/Init.get());
|
2015-08-05 17:40:35 +08:00
|
|
|
Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
|
2012-03-01 12:01:32 +08:00
|
|
|
|
|
|
|
// Add a fake function body to the block. IR generation is responsible
|
|
|
|
// for filling in the actual body, which cannot be expressed as an AST.
|
2012-07-05 01:03:41 +08:00
|
|
|
Block->setBody(new (Context) CompoundStmt(ConvLocation));
|
2012-03-01 12:01:32 +08:00
|
|
|
|
|
|
|
// Create the block literal expression.
|
|
|
|
Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
|
|
|
|
ExprCleanupObjects.push_back(Block);
|
2016-06-22 04:29:17 +08:00
|
|
|
Cleanup.setExprNeedsCleanups(true);
|
2012-03-01 12:01:32 +08:00
|
|
|
|
|
|
|
return BuildBlock;
|
|
|
|
}
|