xref: /minix3/external/bsd/llvm/dist/clang/lib/Sema/SemaLambda.cpp (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1f4a2713aSLionel Sambuc //===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc //  This file implements semantic analysis for C++ lambda expressions.
11f4a2713aSLionel Sambuc //
12f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
13f4a2713aSLionel Sambuc #include "clang/Sema/DeclSpec.h"
14*0a6a1f1dSLionel Sambuc #include "TypeLocBuilder.h"
15f4a2713aSLionel Sambuc #include "clang/AST/ASTLambda.h"
16f4a2713aSLionel Sambuc #include "clang/AST/ExprCXX.h"
17f4a2713aSLionel Sambuc #include "clang/Basic/TargetInfo.h"
18f4a2713aSLionel Sambuc #include "clang/Sema/Initialization.h"
19f4a2713aSLionel Sambuc #include "clang/Sema/Lookup.h"
20f4a2713aSLionel Sambuc #include "clang/Sema/Scope.h"
21f4a2713aSLionel Sambuc #include "clang/Sema/ScopeInfo.h"
22f4a2713aSLionel Sambuc #include "clang/Sema/SemaInternal.h"
23f4a2713aSLionel Sambuc #include "clang/Sema/SemaLambda.h"
24f4a2713aSLionel Sambuc using namespace clang;
25f4a2713aSLionel Sambuc using namespace sema;
26f4a2713aSLionel Sambuc 
27*0a6a1f1dSLionel Sambuc /// \brief Examines the FunctionScopeInfo stack to determine the nearest
28*0a6a1f1dSLionel Sambuc /// enclosing lambda (to the current lambda) that is 'capture-ready' for
29*0a6a1f1dSLionel Sambuc /// the variable referenced in the current lambda (i.e. \p VarToCapture).
30*0a6a1f1dSLionel Sambuc /// If successful, returns the index into Sema's FunctionScopeInfo stack
31*0a6a1f1dSLionel Sambuc /// of the capture-ready lambda's LambdaScopeInfo.
32*0a6a1f1dSLionel Sambuc ///
33*0a6a1f1dSLionel Sambuc /// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
34*0a6a1f1dSLionel Sambuc /// lambda - is on top) to determine the index of the nearest enclosing/outer
35*0a6a1f1dSLionel Sambuc /// lambda that is ready to capture the \p VarToCapture being referenced in
36*0a6a1f1dSLionel Sambuc /// the current lambda.
37*0a6a1f1dSLionel Sambuc /// As we climb down the stack, we want the index of the first such lambda -
38*0a6a1f1dSLionel Sambuc /// that is the lambda with the highest index that is 'capture-ready'.
39*0a6a1f1dSLionel Sambuc ///
40*0a6a1f1dSLionel Sambuc /// A lambda 'L' is capture-ready for 'V' (var or this) if:
41*0a6a1f1dSLionel Sambuc ///  - its enclosing context is non-dependent
42*0a6a1f1dSLionel Sambuc ///  - and if the chain of lambdas between L and the lambda in which
43*0a6a1f1dSLionel Sambuc ///    V is potentially used (i.e. the lambda at the top of the scope info
44*0a6a1f1dSLionel Sambuc ///    stack), can all capture or have already captured V.
45*0a6a1f1dSLionel Sambuc /// If \p VarToCapture is 'null' then we are trying to capture 'this'.
46*0a6a1f1dSLionel Sambuc ///
47*0a6a1f1dSLionel Sambuc /// Note that a lambda that is deemed 'capture-ready' still needs to be checked
48*0a6a1f1dSLionel Sambuc /// for whether it is 'capture-capable' (see
49*0a6a1f1dSLionel Sambuc /// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
50*0a6a1f1dSLionel Sambuc /// capture.
51*0a6a1f1dSLionel Sambuc ///
52*0a6a1f1dSLionel Sambuc /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
53*0a6a1f1dSLionel Sambuc ///  LambdaScopeInfo inherits from).  The current/deepest/innermost lambda
54*0a6a1f1dSLionel Sambuc ///  is at the top of the stack and has the highest index.
55*0a6a1f1dSLionel Sambuc /// \param VarToCapture - the variable to capture.  If NULL, capture 'this'.
56*0a6a1f1dSLionel Sambuc ///
57*0a6a1f1dSLionel Sambuc /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
58*0a6a1f1dSLionel Sambuc /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
59*0a6a1f1dSLionel Sambuc /// which is capture-ready.  If the return value evaluates to 'false' then
60*0a6a1f1dSLionel Sambuc /// no lambda is capture-ready for \p VarToCapture.
61f4a2713aSLionel Sambuc 
62*0a6a1f1dSLionel Sambuc static inline Optional<unsigned>
getStackIndexOfNearestEnclosingCaptureReadyLambda(ArrayRef<const clang::sema::FunctionScopeInfo * > FunctionScopes,VarDecl * VarToCapture)63*0a6a1f1dSLionel Sambuc getStackIndexOfNearestEnclosingCaptureReadyLambda(
64*0a6a1f1dSLionel Sambuc     ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
65*0a6a1f1dSLionel Sambuc     VarDecl *VarToCapture) {
66*0a6a1f1dSLionel Sambuc   // Label failure to capture.
67*0a6a1f1dSLionel Sambuc   const Optional<unsigned> NoLambdaIsCaptureReady;
68*0a6a1f1dSLionel Sambuc 
69*0a6a1f1dSLionel Sambuc   assert(
70*0a6a1f1dSLionel Sambuc       isa<clang::sema::LambdaScopeInfo>(
71*0a6a1f1dSLionel Sambuc           FunctionScopes[FunctionScopes.size() - 1]) &&
72*0a6a1f1dSLionel Sambuc       "The function on the top of sema's function-info stack must be a lambda");
73*0a6a1f1dSLionel Sambuc 
74*0a6a1f1dSLionel Sambuc   // If VarToCapture is null, we are attempting to capture 'this'.
75*0a6a1f1dSLionel Sambuc   const bool IsCapturingThis = !VarToCapture;
76f4a2713aSLionel Sambuc   const bool IsCapturingVariable = !IsCapturingThis;
77*0a6a1f1dSLionel Sambuc 
78*0a6a1f1dSLionel Sambuc   // Start with the current lambda at the top of the stack (highest index).
79f4a2713aSLionel Sambuc   unsigned CurScopeIndex = FunctionScopes.size() - 1;
80*0a6a1f1dSLionel Sambuc   DeclContext *EnclosingDC =
81*0a6a1f1dSLionel Sambuc       cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
82*0a6a1f1dSLionel Sambuc 
83*0a6a1f1dSLionel Sambuc   do {
84*0a6a1f1dSLionel Sambuc     const clang::sema::LambdaScopeInfo *LSI =
85f4a2713aSLionel Sambuc         cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
86*0a6a1f1dSLionel Sambuc     // IF we have climbed down to an intervening enclosing lambda that contains
87*0a6a1f1dSLionel Sambuc     // the variable declaration - it obviously can/must not capture the
88f4a2713aSLionel Sambuc     // variable.
89*0a6a1f1dSLionel Sambuc     // Since its enclosing DC is dependent, all the lambdas between it and the
90*0a6a1f1dSLionel Sambuc     // innermost nested lambda are dependent (otherwise we wouldn't have
91*0a6a1f1dSLionel Sambuc     // arrived here) - so we don't yet have a lambda that can capture the
92*0a6a1f1dSLionel Sambuc     // variable.
93*0a6a1f1dSLionel Sambuc     if (IsCapturingVariable &&
94*0a6a1f1dSLionel Sambuc         VarToCapture->getDeclContext()->Equals(EnclosingDC))
95*0a6a1f1dSLionel Sambuc       return NoLambdaIsCaptureReady;
96*0a6a1f1dSLionel Sambuc 
97*0a6a1f1dSLionel Sambuc     // For an enclosing lambda to be capture ready for an entity, all
98*0a6a1f1dSLionel Sambuc     // intervening lambda's have to be able to capture that entity. If even
99*0a6a1f1dSLionel Sambuc     // one of the intervening lambda's is not capable of capturing the entity
100*0a6a1f1dSLionel Sambuc     // then no enclosing lambda can ever capture that entity.
101*0a6a1f1dSLionel Sambuc     // For e.g.
102*0a6a1f1dSLionel Sambuc     // const int x = 10;
103*0a6a1f1dSLionel Sambuc     // [=](auto a) {    #1
104*0a6a1f1dSLionel Sambuc     //   [](auto b) {   #2 <-- an intervening lambda that can never capture 'x'
105*0a6a1f1dSLionel Sambuc     //    [=](auto c) { #3
106*0a6a1f1dSLionel Sambuc     //       f(x, c);  <-- can not lead to x's speculative capture by #1 or #2
107*0a6a1f1dSLionel Sambuc     //    }; }; };
108f4a2713aSLionel Sambuc     // If they do not have a default implicit capture, check to see
109f4a2713aSLionel Sambuc     // if the entity has already been explicitly captured.
110f4a2713aSLionel Sambuc     // If even a single dependent enclosing lambda lacks the capability
111f4a2713aSLionel Sambuc     // to ever capture this variable, there is no further enclosing
112f4a2713aSLionel Sambuc     // non-dependent lambda that can capture this variable.
113f4a2713aSLionel Sambuc     if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
114*0a6a1f1dSLionel Sambuc       if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
115*0a6a1f1dSLionel Sambuc         return NoLambdaIsCaptureReady;
116f4a2713aSLionel Sambuc       if (IsCapturingThis && !LSI->isCXXThisCaptured())
117*0a6a1f1dSLionel Sambuc         return NoLambdaIsCaptureReady;
118f4a2713aSLionel Sambuc     }
119f4a2713aSLionel Sambuc     EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
120f4a2713aSLionel Sambuc 
121*0a6a1f1dSLionel Sambuc     assert(CurScopeIndex);
122*0a6a1f1dSLionel Sambuc     --CurScopeIndex;
123*0a6a1f1dSLionel Sambuc   } while (!EnclosingDC->isTranslationUnit() &&
124*0a6a1f1dSLionel Sambuc            EnclosingDC->isDependentContext() &&
125*0a6a1f1dSLionel Sambuc            isLambdaCallOperator(EnclosingDC));
126*0a6a1f1dSLionel Sambuc 
127*0a6a1f1dSLionel Sambuc   assert(CurScopeIndex < (FunctionScopes.size() - 1));
128*0a6a1f1dSLionel Sambuc   // If the enclosingDC is not dependent, then the immediately nested lambda
129*0a6a1f1dSLionel Sambuc   // (one index above) is capture-ready.
130*0a6a1f1dSLionel Sambuc   if (!EnclosingDC->isDependentContext())
131*0a6a1f1dSLionel Sambuc     return CurScopeIndex + 1;
132*0a6a1f1dSLionel Sambuc   return NoLambdaIsCaptureReady;
133*0a6a1f1dSLionel Sambuc }
134*0a6a1f1dSLionel Sambuc 
135*0a6a1f1dSLionel Sambuc /// \brief Examines the FunctionScopeInfo stack to determine the nearest
136*0a6a1f1dSLionel Sambuc /// enclosing lambda (to the current lambda) that is 'capture-capable' for
137*0a6a1f1dSLionel Sambuc /// the variable referenced in the current lambda (i.e. \p VarToCapture).
138*0a6a1f1dSLionel Sambuc /// If successful, returns the index into Sema's FunctionScopeInfo stack
139*0a6a1f1dSLionel Sambuc /// of the capture-capable lambda's LambdaScopeInfo.
140*0a6a1f1dSLionel Sambuc ///
141*0a6a1f1dSLionel Sambuc /// Given the current stack of lambdas being processed by Sema and
142*0a6a1f1dSLionel Sambuc /// the variable of interest, to identify the nearest enclosing lambda (to the
143*0a6a1f1dSLionel Sambuc /// current lambda at the top of the stack) that can truly capture
144*0a6a1f1dSLionel Sambuc /// a variable, it has to have the following two properties:
145*0a6a1f1dSLionel Sambuc ///  a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
146*0a6a1f1dSLionel Sambuc ///     - climb down the stack (i.e. starting from the innermost and examining
147*0a6a1f1dSLionel Sambuc ///       each outer lambda step by step) checking if each enclosing
148*0a6a1f1dSLionel Sambuc ///       lambda can either implicitly or explicitly capture the variable.
149*0a6a1f1dSLionel Sambuc ///       Record the first such lambda that is enclosed in a non-dependent
150*0a6a1f1dSLionel Sambuc ///       context. If no such lambda currently exists return failure.
151*0a6a1f1dSLionel Sambuc ///  b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
152*0a6a1f1dSLionel Sambuc ///  capture the variable by checking all its enclosing lambdas:
153*0a6a1f1dSLionel Sambuc ///     - check if all outer lambdas enclosing the 'capture-ready' lambda
154*0a6a1f1dSLionel Sambuc ///       identified above in 'a' can also capture the variable (this is done
155*0a6a1f1dSLionel Sambuc ///       via tryCaptureVariable for variables and CheckCXXThisCapture for
156*0a6a1f1dSLionel Sambuc ///       'this' by passing in the index of the Lambda identified in step 'a')
157*0a6a1f1dSLionel Sambuc ///
158*0a6a1f1dSLionel Sambuc /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
159*0a6a1f1dSLionel Sambuc /// LambdaScopeInfo inherits from).  The current/deepest/innermost lambda
160*0a6a1f1dSLionel Sambuc /// is at the top of the stack.
161*0a6a1f1dSLionel Sambuc ///
162*0a6a1f1dSLionel Sambuc /// \param VarToCapture - the variable to capture.  If NULL, capture 'this'.
163*0a6a1f1dSLionel Sambuc ///
164*0a6a1f1dSLionel Sambuc ///
165*0a6a1f1dSLionel Sambuc /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
166*0a6a1f1dSLionel Sambuc /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
167*0a6a1f1dSLionel Sambuc /// which is capture-capable.  If the return value evaluates to 'false' then
168*0a6a1f1dSLionel Sambuc /// no lambda is capture-capable for \p VarToCapture.
169*0a6a1f1dSLionel Sambuc 
getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef<const sema::FunctionScopeInfo * > FunctionScopes,VarDecl * VarToCapture,Sema & S)170*0a6a1f1dSLionel Sambuc Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
171*0a6a1f1dSLionel Sambuc     ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
172*0a6a1f1dSLionel Sambuc     VarDecl *VarToCapture, Sema &S) {
173*0a6a1f1dSLionel Sambuc 
174*0a6a1f1dSLionel Sambuc   const Optional<unsigned> NoLambdaIsCaptureCapable;
175*0a6a1f1dSLionel Sambuc 
176*0a6a1f1dSLionel Sambuc   const Optional<unsigned> OptionalStackIndex =
177*0a6a1f1dSLionel Sambuc       getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
178*0a6a1f1dSLionel Sambuc                                                         VarToCapture);
179*0a6a1f1dSLionel Sambuc   if (!OptionalStackIndex)
180*0a6a1f1dSLionel Sambuc     return NoLambdaIsCaptureCapable;
181*0a6a1f1dSLionel Sambuc 
182*0a6a1f1dSLionel Sambuc   const unsigned IndexOfCaptureReadyLambda = OptionalStackIndex.getValue();
183*0a6a1f1dSLionel Sambuc   assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
184*0a6a1f1dSLionel Sambuc           S.getCurGenericLambda()) &&
185*0a6a1f1dSLionel Sambuc          "The capture ready lambda for a potential capture can only be the "
186*0a6a1f1dSLionel Sambuc          "current lambda if it is a generic lambda");
187*0a6a1f1dSLionel Sambuc 
188*0a6a1f1dSLionel Sambuc   const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
189*0a6a1f1dSLionel Sambuc       cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
190*0a6a1f1dSLionel Sambuc 
191*0a6a1f1dSLionel Sambuc   // If VarToCapture is null, we are attempting to capture 'this'
192*0a6a1f1dSLionel Sambuc   const bool IsCapturingThis = !VarToCapture;
193f4a2713aSLionel Sambuc   const bool IsCapturingVariable = !IsCapturingThis;
194f4a2713aSLionel Sambuc 
195f4a2713aSLionel Sambuc   if (IsCapturingVariable) {
196*0a6a1f1dSLionel Sambuc     // Check if the capture-ready lambda can truly capture the variable, by
197*0a6a1f1dSLionel Sambuc     // checking whether all enclosing lambdas of the capture-ready lambda allow
198*0a6a1f1dSLionel Sambuc     // the capture - i.e. make sure it is capture-capable.
199f4a2713aSLionel Sambuc     QualType CaptureType, DeclRefType;
200*0a6a1f1dSLionel Sambuc     const bool CanCaptureVariable =
201*0a6a1f1dSLionel Sambuc         !S.tryCaptureVariable(VarToCapture,
202*0a6a1f1dSLionel Sambuc                               /*ExprVarIsUsedInLoc*/ SourceLocation(),
203*0a6a1f1dSLionel Sambuc                               clang::Sema::TryCapture_Implicit,
204f4a2713aSLionel Sambuc                               /*EllipsisLoc*/ SourceLocation(),
205*0a6a1f1dSLionel Sambuc                               /*BuildAndDiagnose*/ false, CaptureType,
206*0a6a1f1dSLionel Sambuc                               DeclRefType, &IndexOfCaptureReadyLambda);
207*0a6a1f1dSLionel Sambuc     if (!CanCaptureVariable)
208*0a6a1f1dSLionel Sambuc       return NoLambdaIsCaptureCapable;
209f4a2713aSLionel Sambuc   } else {
210*0a6a1f1dSLionel Sambuc     // Check if the capture-ready lambda can truly capture 'this' by checking
211*0a6a1f1dSLionel Sambuc     // whether all enclosing lambdas of the capture-ready lambda can capture
212*0a6a1f1dSLionel Sambuc     // 'this'.
213*0a6a1f1dSLionel Sambuc     const bool CanCaptureThis =
214*0a6a1f1dSLionel Sambuc         !S.CheckCXXThisCapture(
215*0a6a1f1dSLionel Sambuc              CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
216*0a6a1f1dSLionel Sambuc              /*Explicit*/ false, /*BuildAndDiagnose*/ false,
217*0a6a1f1dSLionel Sambuc              &IndexOfCaptureReadyLambda);
218*0a6a1f1dSLionel Sambuc     if (!CanCaptureThis)
219*0a6a1f1dSLionel Sambuc       return NoLambdaIsCaptureCapable;
220*0a6a1f1dSLionel Sambuc   }
221*0a6a1f1dSLionel Sambuc   return IndexOfCaptureReadyLambda;
222f4a2713aSLionel Sambuc }
223f4a2713aSLionel Sambuc 
224f4a2713aSLionel Sambuc static inline TemplateParameterList *
getGenericLambdaTemplateParameterList(LambdaScopeInfo * LSI,Sema & SemaRef)225f4a2713aSLionel Sambuc getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
226f4a2713aSLionel Sambuc   if (LSI->GLTemplateParameterList)
227f4a2713aSLionel Sambuc     return LSI->GLTemplateParameterList;
228f4a2713aSLionel Sambuc 
229f4a2713aSLionel Sambuc   if (LSI->AutoTemplateParams.size()) {
230f4a2713aSLionel Sambuc     SourceRange IntroRange = LSI->IntroducerRange;
231f4a2713aSLionel Sambuc     SourceLocation LAngleLoc = IntroRange.getBegin();
232f4a2713aSLionel Sambuc     SourceLocation RAngleLoc = IntroRange.getEnd();
233f4a2713aSLionel Sambuc     LSI->GLTemplateParameterList = TemplateParameterList::Create(
234f4a2713aSLionel Sambuc         SemaRef.Context,
235*0a6a1f1dSLionel Sambuc         /*Template kw loc*/ SourceLocation(), LAngleLoc,
236f4a2713aSLionel Sambuc         (NamedDecl **)LSI->AutoTemplateParams.data(),
237f4a2713aSLionel Sambuc         LSI->AutoTemplateParams.size(), RAngleLoc);
238f4a2713aSLionel Sambuc   }
239f4a2713aSLionel Sambuc   return LSI->GLTemplateParameterList;
240f4a2713aSLionel Sambuc }
241f4a2713aSLionel Sambuc 
createLambdaClosureType(SourceRange IntroducerRange,TypeSourceInfo * Info,bool KnownDependent,LambdaCaptureDefault CaptureDefault)242f4a2713aSLionel Sambuc CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
243f4a2713aSLionel Sambuc                                              TypeSourceInfo *Info,
244f4a2713aSLionel Sambuc                                              bool KnownDependent,
245f4a2713aSLionel Sambuc                                              LambdaCaptureDefault CaptureDefault) {
246f4a2713aSLionel Sambuc   DeclContext *DC = CurContext;
247f4a2713aSLionel Sambuc   while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
248f4a2713aSLionel Sambuc     DC = DC->getParent();
249f4a2713aSLionel Sambuc   bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
250f4a2713aSLionel Sambuc                                                                *this);
251f4a2713aSLionel Sambuc   // Start constructing the lambda class.
252f4a2713aSLionel Sambuc   CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
253f4a2713aSLionel Sambuc                                                      IntroducerRange.getBegin(),
254f4a2713aSLionel Sambuc                                                      KnownDependent,
255f4a2713aSLionel Sambuc                                                      IsGenericLambda,
256f4a2713aSLionel Sambuc                                                      CaptureDefault);
257f4a2713aSLionel Sambuc   DC->addDecl(Class);
258f4a2713aSLionel Sambuc 
259f4a2713aSLionel Sambuc   return Class;
260f4a2713aSLionel Sambuc }
261f4a2713aSLionel Sambuc 
262f4a2713aSLionel Sambuc /// \brief Determine whether the given context is or is enclosed in an inline
263f4a2713aSLionel Sambuc /// function.
isInInlineFunction(const DeclContext * DC)264f4a2713aSLionel Sambuc static bool isInInlineFunction(const DeclContext *DC) {
265f4a2713aSLionel Sambuc   while (!DC->isFileContext()) {
266f4a2713aSLionel Sambuc     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
267f4a2713aSLionel Sambuc       if (FD->isInlined())
268f4a2713aSLionel Sambuc         return true;
269f4a2713aSLionel Sambuc 
270f4a2713aSLionel Sambuc     DC = DC->getLexicalParent();
271f4a2713aSLionel Sambuc   }
272f4a2713aSLionel Sambuc 
273f4a2713aSLionel Sambuc   return false;
274f4a2713aSLionel Sambuc }
275f4a2713aSLionel Sambuc 
276f4a2713aSLionel Sambuc MangleNumberingContext *
getCurrentMangleNumberContext(const DeclContext * DC,Decl * & ManglingContextDecl)277f4a2713aSLionel Sambuc Sema::getCurrentMangleNumberContext(const DeclContext *DC,
278f4a2713aSLionel Sambuc                                     Decl *&ManglingContextDecl) {
279f4a2713aSLionel Sambuc   // Compute the context for allocating mangling numbers in the current
280f4a2713aSLionel Sambuc   // expression, if the ABI requires them.
281f4a2713aSLionel Sambuc   ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
282f4a2713aSLionel Sambuc 
283f4a2713aSLionel Sambuc   enum ContextKind {
284f4a2713aSLionel Sambuc     Normal,
285f4a2713aSLionel Sambuc     DefaultArgument,
286f4a2713aSLionel Sambuc     DataMember,
287f4a2713aSLionel Sambuc     StaticDataMember
288f4a2713aSLionel Sambuc   } Kind = Normal;
289f4a2713aSLionel Sambuc 
290f4a2713aSLionel Sambuc   // Default arguments of member function parameters that appear in a class
291f4a2713aSLionel Sambuc   // definition, as well as the initializers of data members, receive special
292f4a2713aSLionel Sambuc   // treatment. Identify them.
293f4a2713aSLionel Sambuc   if (ManglingContextDecl) {
294f4a2713aSLionel Sambuc     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
295f4a2713aSLionel Sambuc       if (const DeclContext *LexicalDC
296f4a2713aSLionel Sambuc           = Param->getDeclContext()->getLexicalParent())
297f4a2713aSLionel Sambuc         if (LexicalDC->isRecord())
298f4a2713aSLionel Sambuc           Kind = DefaultArgument;
299f4a2713aSLionel Sambuc     } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
300f4a2713aSLionel Sambuc       if (Var->getDeclContext()->isRecord())
301f4a2713aSLionel Sambuc         Kind = StaticDataMember;
302f4a2713aSLionel Sambuc     } else if (isa<FieldDecl>(ManglingContextDecl)) {
303f4a2713aSLionel Sambuc       Kind = DataMember;
304f4a2713aSLionel Sambuc     }
305f4a2713aSLionel Sambuc   }
306f4a2713aSLionel Sambuc 
307f4a2713aSLionel Sambuc   // Itanium ABI [5.1.7]:
308f4a2713aSLionel Sambuc   //   In the following contexts [...] the one-definition rule requires closure
309f4a2713aSLionel Sambuc   //   types in different translation units to "correspond":
310f4a2713aSLionel Sambuc   bool IsInNonspecializedTemplate =
311f4a2713aSLionel Sambuc     !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
312f4a2713aSLionel Sambuc   switch (Kind) {
313f4a2713aSLionel Sambuc   case Normal:
314f4a2713aSLionel Sambuc     //  -- the bodies of non-exported nonspecialized template functions
315f4a2713aSLionel Sambuc     //  -- the bodies of inline functions
316f4a2713aSLionel Sambuc     if ((IsInNonspecializedTemplate &&
317f4a2713aSLionel Sambuc          !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
318f4a2713aSLionel Sambuc         isInInlineFunction(CurContext)) {
319*0a6a1f1dSLionel Sambuc       ManglingContextDecl = nullptr;
320f4a2713aSLionel Sambuc       return &Context.getManglingNumberContext(DC);
321f4a2713aSLionel Sambuc     }
322f4a2713aSLionel Sambuc 
323*0a6a1f1dSLionel Sambuc     ManglingContextDecl = nullptr;
324*0a6a1f1dSLionel Sambuc     return nullptr;
325f4a2713aSLionel Sambuc 
326f4a2713aSLionel Sambuc   case StaticDataMember:
327f4a2713aSLionel Sambuc     //  -- the initializers of nonspecialized static members of template classes
328f4a2713aSLionel Sambuc     if (!IsInNonspecializedTemplate) {
329*0a6a1f1dSLionel Sambuc       ManglingContextDecl = nullptr;
330*0a6a1f1dSLionel Sambuc       return nullptr;
331f4a2713aSLionel Sambuc     }
332f4a2713aSLionel Sambuc     // Fall through to get the current context.
333f4a2713aSLionel Sambuc 
334f4a2713aSLionel Sambuc   case DataMember:
335f4a2713aSLionel Sambuc     //  -- the in-class initializers of class members
336f4a2713aSLionel Sambuc   case DefaultArgument:
337f4a2713aSLionel Sambuc     //  -- default arguments appearing in class definitions
338f4a2713aSLionel Sambuc     return &ExprEvalContexts.back().getMangleNumberingContext(Context);
339f4a2713aSLionel Sambuc   }
340f4a2713aSLionel Sambuc 
341f4a2713aSLionel Sambuc   llvm_unreachable("unexpected context");
342f4a2713aSLionel Sambuc }
343f4a2713aSLionel Sambuc 
344f4a2713aSLionel Sambuc MangleNumberingContext &
getMangleNumberingContext(ASTContext & Ctx)345f4a2713aSLionel Sambuc Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext(
346f4a2713aSLionel Sambuc     ASTContext &Ctx) {
347f4a2713aSLionel Sambuc   assert(ManglingContextDecl && "Need to have a context declaration");
348f4a2713aSLionel Sambuc   if (!MangleNumbering)
349f4a2713aSLionel Sambuc     MangleNumbering = Ctx.createMangleNumberingContext();
350f4a2713aSLionel Sambuc   return *MangleNumbering;
351f4a2713aSLionel Sambuc }
352f4a2713aSLionel Sambuc 
startLambdaDefinition(CXXRecordDecl * Class,SourceRange IntroducerRange,TypeSourceInfo * MethodTypeInfo,SourceLocation EndLoc,ArrayRef<ParmVarDecl * > Params)353f4a2713aSLionel Sambuc CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
354f4a2713aSLionel Sambuc                                            SourceRange IntroducerRange,
355f4a2713aSLionel Sambuc                                            TypeSourceInfo *MethodTypeInfo,
356f4a2713aSLionel Sambuc                                            SourceLocation EndLoc,
357f4a2713aSLionel Sambuc                                            ArrayRef<ParmVarDecl *> Params) {
358f4a2713aSLionel Sambuc   QualType MethodType = MethodTypeInfo->getType();
359f4a2713aSLionel Sambuc   TemplateParameterList *TemplateParams =
360f4a2713aSLionel Sambuc             getGenericLambdaTemplateParameterList(getCurLambda(), *this);
361f4a2713aSLionel Sambuc   // If a lambda appears in a dependent context or is a generic lambda (has
362f4a2713aSLionel Sambuc   // template parameters) and has an 'auto' return type, deduce it to a
363f4a2713aSLionel Sambuc   // dependent type.
364f4a2713aSLionel Sambuc   if (Class->isDependentContext() || TemplateParams) {
365f4a2713aSLionel Sambuc     const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
366*0a6a1f1dSLionel Sambuc     QualType Result = FPT->getReturnType();
367f4a2713aSLionel Sambuc     if (Result->isUndeducedType()) {
368f4a2713aSLionel Sambuc       Result = SubstAutoType(Result, Context.DependentTy);
369*0a6a1f1dSLionel Sambuc       MethodType = Context.getFunctionType(Result, FPT->getParamTypes(),
370f4a2713aSLionel Sambuc                                            FPT->getExtProtoInfo());
371f4a2713aSLionel Sambuc     }
372f4a2713aSLionel Sambuc   }
373f4a2713aSLionel Sambuc 
374f4a2713aSLionel Sambuc   // C++11 [expr.prim.lambda]p5:
375f4a2713aSLionel Sambuc   //   The closure type for a lambda-expression has a public inline function
376f4a2713aSLionel Sambuc   //   call operator (13.5.4) whose parameters and return type are described by
377f4a2713aSLionel Sambuc   //   the lambda-expression's parameter-declaration-clause and
378f4a2713aSLionel Sambuc   //   trailing-return-type respectively.
379f4a2713aSLionel Sambuc   DeclarationName MethodName
380f4a2713aSLionel Sambuc     = Context.DeclarationNames.getCXXOperatorName(OO_Call);
381f4a2713aSLionel Sambuc   DeclarationNameLoc MethodNameLoc;
382f4a2713aSLionel Sambuc   MethodNameLoc.CXXOperatorName.BeginOpNameLoc
383f4a2713aSLionel Sambuc     = IntroducerRange.getBegin().getRawEncoding();
384f4a2713aSLionel Sambuc   MethodNameLoc.CXXOperatorName.EndOpNameLoc
385f4a2713aSLionel Sambuc     = IntroducerRange.getEnd().getRawEncoding();
386f4a2713aSLionel Sambuc   CXXMethodDecl *Method
387f4a2713aSLionel Sambuc     = CXXMethodDecl::Create(Context, Class, EndLoc,
388f4a2713aSLionel Sambuc                             DeclarationNameInfo(MethodName,
389f4a2713aSLionel Sambuc                                                 IntroducerRange.getBegin(),
390f4a2713aSLionel Sambuc                                                 MethodNameLoc),
391f4a2713aSLionel Sambuc                             MethodType, MethodTypeInfo,
392f4a2713aSLionel Sambuc                             SC_None,
393f4a2713aSLionel Sambuc                             /*isInline=*/true,
394f4a2713aSLionel Sambuc                             /*isConstExpr=*/false,
395f4a2713aSLionel Sambuc                             EndLoc);
396f4a2713aSLionel Sambuc   Method->setAccess(AS_public);
397f4a2713aSLionel Sambuc 
398f4a2713aSLionel Sambuc   // Temporarily set the lexical declaration context to the current
399f4a2713aSLionel Sambuc   // context, so that the Scope stack matches the lexical nesting.
400f4a2713aSLionel Sambuc   Method->setLexicalDeclContext(CurContext);
401f4a2713aSLionel Sambuc   // Create a function template if we have a template parameter list
402f4a2713aSLionel Sambuc   FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
403f4a2713aSLionel Sambuc             FunctionTemplateDecl::Create(Context, Class,
404f4a2713aSLionel Sambuc                                          Method->getLocation(), MethodName,
405f4a2713aSLionel Sambuc                                          TemplateParams,
406*0a6a1f1dSLionel Sambuc                                          Method) : nullptr;
407f4a2713aSLionel Sambuc   if (TemplateMethod) {
408f4a2713aSLionel Sambuc     TemplateMethod->setLexicalDeclContext(CurContext);
409f4a2713aSLionel Sambuc     TemplateMethod->setAccess(AS_public);
410f4a2713aSLionel Sambuc     Method->setDescribedFunctionTemplate(TemplateMethod);
411f4a2713aSLionel Sambuc   }
412f4a2713aSLionel Sambuc 
413f4a2713aSLionel Sambuc   // Add parameters.
414f4a2713aSLionel Sambuc   if (!Params.empty()) {
415f4a2713aSLionel Sambuc     Method->setParams(Params);
416f4a2713aSLionel Sambuc     CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
417f4a2713aSLionel Sambuc                              const_cast<ParmVarDecl **>(Params.end()),
418f4a2713aSLionel Sambuc                              /*CheckParameterNames=*/false);
419f4a2713aSLionel Sambuc 
420*0a6a1f1dSLionel Sambuc     for (auto P : Method->params())
421*0a6a1f1dSLionel Sambuc       P->setOwningFunction(Method);
422f4a2713aSLionel Sambuc   }
423f4a2713aSLionel Sambuc 
424f4a2713aSLionel Sambuc   Decl *ManglingContextDecl;
425f4a2713aSLionel Sambuc   if (MangleNumberingContext *MCtx =
426f4a2713aSLionel Sambuc           getCurrentMangleNumberContext(Class->getDeclContext(),
427f4a2713aSLionel Sambuc                                         ManglingContextDecl)) {
428f4a2713aSLionel Sambuc     unsigned ManglingNumber = MCtx->getManglingNumber(Method);
429f4a2713aSLionel Sambuc     Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
430f4a2713aSLionel Sambuc   }
431f4a2713aSLionel Sambuc 
432f4a2713aSLionel Sambuc   return Method;
433f4a2713aSLionel Sambuc }
434f4a2713aSLionel Sambuc 
buildLambdaScope(LambdaScopeInfo * LSI,CXXMethodDecl * CallOperator,SourceRange IntroducerRange,LambdaCaptureDefault CaptureDefault,SourceLocation CaptureDefaultLoc,bool ExplicitParams,bool ExplicitResultType,bool Mutable)435f4a2713aSLionel Sambuc void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
436f4a2713aSLionel Sambuc                                         CXXMethodDecl *CallOperator,
437f4a2713aSLionel Sambuc                                         SourceRange IntroducerRange,
438f4a2713aSLionel Sambuc                                         LambdaCaptureDefault CaptureDefault,
439f4a2713aSLionel Sambuc                                         SourceLocation CaptureDefaultLoc,
440f4a2713aSLionel Sambuc                                         bool ExplicitParams,
441f4a2713aSLionel Sambuc                                         bool ExplicitResultType,
442f4a2713aSLionel Sambuc                                         bool Mutable) {
443f4a2713aSLionel Sambuc   LSI->CallOperator = CallOperator;
444f4a2713aSLionel Sambuc   CXXRecordDecl *LambdaClass = CallOperator->getParent();
445f4a2713aSLionel Sambuc   LSI->Lambda = LambdaClass;
446f4a2713aSLionel Sambuc   if (CaptureDefault == LCD_ByCopy)
447f4a2713aSLionel Sambuc     LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
448f4a2713aSLionel Sambuc   else if (CaptureDefault == LCD_ByRef)
449f4a2713aSLionel Sambuc     LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
450f4a2713aSLionel Sambuc   LSI->CaptureDefaultLoc = CaptureDefaultLoc;
451f4a2713aSLionel Sambuc   LSI->IntroducerRange = IntroducerRange;
452f4a2713aSLionel Sambuc   LSI->ExplicitParams = ExplicitParams;
453f4a2713aSLionel Sambuc   LSI->Mutable = Mutable;
454f4a2713aSLionel Sambuc 
455f4a2713aSLionel Sambuc   if (ExplicitResultType) {
456*0a6a1f1dSLionel Sambuc     LSI->ReturnType = CallOperator->getReturnType();
457f4a2713aSLionel Sambuc 
458f4a2713aSLionel Sambuc     if (!LSI->ReturnType->isDependentType() &&
459f4a2713aSLionel Sambuc         !LSI->ReturnType->isVoidType()) {
460f4a2713aSLionel Sambuc       if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
461f4a2713aSLionel Sambuc                               diag::err_lambda_incomplete_result)) {
462f4a2713aSLionel Sambuc         // Do nothing.
463f4a2713aSLionel Sambuc       }
464f4a2713aSLionel Sambuc     }
465f4a2713aSLionel Sambuc   } else {
466f4a2713aSLionel Sambuc     LSI->HasImplicitReturnType = true;
467f4a2713aSLionel Sambuc   }
468f4a2713aSLionel Sambuc }
469f4a2713aSLionel Sambuc 
finishLambdaExplicitCaptures(LambdaScopeInfo * LSI)470f4a2713aSLionel Sambuc void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
471f4a2713aSLionel Sambuc   LSI->finishedExplicitCaptures();
472f4a2713aSLionel Sambuc }
473f4a2713aSLionel Sambuc 
addLambdaParameters(CXXMethodDecl * CallOperator,Scope * CurScope)474f4a2713aSLionel Sambuc void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
475f4a2713aSLionel Sambuc   // Introduce our parameters into the function scope
476f4a2713aSLionel Sambuc   for (unsigned p = 0, NumParams = CallOperator->getNumParams();
477f4a2713aSLionel Sambuc        p < NumParams; ++p) {
478f4a2713aSLionel Sambuc     ParmVarDecl *Param = CallOperator->getParamDecl(p);
479f4a2713aSLionel Sambuc 
480f4a2713aSLionel Sambuc     // If this has an identifier, add it to the scope stack.
481f4a2713aSLionel Sambuc     if (CurScope && Param->getIdentifier()) {
482f4a2713aSLionel Sambuc       CheckShadow(CurScope, Param);
483f4a2713aSLionel Sambuc 
484f4a2713aSLionel Sambuc       PushOnScopeChains(Param, CurScope);
485f4a2713aSLionel Sambuc     }
486f4a2713aSLionel Sambuc   }
487f4a2713aSLionel Sambuc }
488f4a2713aSLionel Sambuc 
489f4a2713aSLionel Sambuc /// If this expression is an enumerator-like expression of some type
490f4a2713aSLionel Sambuc /// T, return the type T; otherwise, return null.
491f4a2713aSLionel Sambuc ///
492f4a2713aSLionel Sambuc /// Pointer comparisons on the result here should always work because
493f4a2713aSLionel Sambuc /// it's derived from either the parent of an EnumConstantDecl
494f4a2713aSLionel Sambuc /// (i.e. the definition) or the declaration returned by
495f4a2713aSLionel Sambuc /// EnumType::getDecl() (i.e. the definition).
findEnumForBlockReturn(Expr * E)496f4a2713aSLionel Sambuc static EnumDecl *findEnumForBlockReturn(Expr *E) {
497f4a2713aSLionel Sambuc   // An expression is an enumerator-like expression of type T if,
498f4a2713aSLionel Sambuc   // ignoring parens and parens-like expressions:
499f4a2713aSLionel Sambuc   E = E->IgnoreParens();
500f4a2713aSLionel Sambuc 
501f4a2713aSLionel Sambuc   //  - it is an enumerator whose enum type is T or
502f4a2713aSLionel Sambuc   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
503f4a2713aSLionel Sambuc     if (EnumConstantDecl *D
504f4a2713aSLionel Sambuc           = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
505f4a2713aSLionel Sambuc       return cast<EnumDecl>(D->getDeclContext());
506f4a2713aSLionel Sambuc     }
507*0a6a1f1dSLionel Sambuc     return nullptr;
508f4a2713aSLionel Sambuc   }
509f4a2713aSLionel Sambuc 
510f4a2713aSLionel Sambuc   //  - it is a comma expression whose RHS is an enumerator-like
511f4a2713aSLionel Sambuc   //    expression of type T or
512f4a2713aSLionel Sambuc   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
513f4a2713aSLionel Sambuc     if (BO->getOpcode() == BO_Comma)
514f4a2713aSLionel Sambuc       return findEnumForBlockReturn(BO->getRHS());
515*0a6a1f1dSLionel Sambuc     return nullptr;
516f4a2713aSLionel Sambuc   }
517f4a2713aSLionel Sambuc 
518f4a2713aSLionel Sambuc   //  - it is a statement-expression whose value expression is an
519f4a2713aSLionel Sambuc   //    enumerator-like expression of type T or
520f4a2713aSLionel Sambuc   if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
521f4a2713aSLionel Sambuc     if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
522f4a2713aSLionel Sambuc       return findEnumForBlockReturn(last);
523*0a6a1f1dSLionel Sambuc     return nullptr;
524f4a2713aSLionel Sambuc   }
525f4a2713aSLionel Sambuc 
526f4a2713aSLionel Sambuc   //   - it is a ternary conditional operator (not the GNU ?:
527f4a2713aSLionel Sambuc   //     extension) whose second and third operands are
528f4a2713aSLionel Sambuc   //     enumerator-like expressions of type T or
529f4a2713aSLionel Sambuc   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
530f4a2713aSLionel Sambuc     if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
531f4a2713aSLionel Sambuc       if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
532f4a2713aSLionel Sambuc         return ED;
533*0a6a1f1dSLionel Sambuc     return nullptr;
534f4a2713aSLionel Sambuc   }
535f4a2713aSLionel Sambuc 
536f4a2713aSLionel Sambuc   // (implicitly:)
537f4a2713aSLionel Sambuc   //   - it is an implicit integral conversion applied to an
538f4a2713aSLionel Sambuc   //     enumerator-like expression of type T or
539f4a2713aSLionel Sambuc   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
540f4a2713aSLionel Sambuc     // We can sometimes see integral conversions in valid
541f4a2713aSLionel Sambuc     // enumerator-like expressions.
542f4a2713aSLionel Sambuc     if (ICE->getCastKind() == CK_IntegralCast)
543f4a2713aSLionel Sambuc       return findEnumForBlockReturn(ICE->getSubExpr());
544f4a2713aSLionel Sambuc 
545f4a2713aSLionel Sambuc     // Otherwise, just rely on the type.
546f4a2713aSLionel Sambuc   }
547f4a2713aSLionel Sambuc 
548f4a2713aSLionel Sambuc   //   - it is an expression of that formal enum type.
549f4a2713aSLionel Sambuc   if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
550f4a2713aSLionel Sambuc     return ET->getDecl();
551f4a2713aSLionel Sambuc   }
552f4a2713aSLionel Sambuc 
553f4a2713aSLionel Sambuc   // Otherwise, nope.
554*0a6a1f1dSLionel Sambuc   return nullptr;
555f4a2713aSLionel Sambuc }
556f4a2713aSLionel Sambuc 
557f4a2713aSLionel Sambuc /// Attempt to find a type T for which the returned expression of the
558f4a2713aSLionel Sambuc /// given statement is an enumerator-like expression of that type.
findEnumForBlockReturn(ReturnStmt * ret)559f4a2713aSLionel Sambuc static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
560f4a2713aSLionel Sambuc   if (Expr *retValue = ret->getRetValue())
561f4a2713aSLionel Sambuc     return findEnumForBlockReturn(retValue);
562*0a6a1f1dSLionel Sambuc   return nullptr;
563f4a2713aSLionel Sambuc }
564f4a2713aSLionel Sambuc 
565f4a2713aSLionel Sambuc /// Attempt to find a common type T for which all of the returned
566f4a2713aSLionel Sambuc /// expressions in a block are enumerator-like expressions of that
567f4a2713aSLionel Sambuc /// type.
findCommonEnumForBlockReturns(ArrayRef<ReturnStmt * > returns)568f4a2713aSLionel Sambuc static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
569f4a2713aSLionel Sambuc   ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
570f4a2713aSLionel Sambuc 
571f4a2713aSLionel Sambuc   // Try to find one for the first return.
572f4a2713aSLionel Sambuc   EnumDecl *ED = findEnumForBlockReturn(*i);
573*0a6a1f1dSLionel Sambuc   if (!ED) return nullptr;
574f4a2713aSLionel Sambuc 
575f4a2713aSLionel Sambuc   // Check that the rest of the returns have the same enum.
576f4a2713aSLionel Sambuc   for (++i; i != e; ++i) {
577f4a2713aSLionel Sambuc     if (findEnumForBlockReturn(*i) != ED)
578*0a6a1f1dSLionel Sambuc       return nullptr;
579f4a2713aSLionel Sambuc   }
580f4a2713aSLionel Sambuc 
581f4a2713aSLionel Sambuc   // Never infer an anonymous enum type.
582*0a6a1f1dSLionel Sambuc   if (!ED->hasNameForLinkage()) return nullptr;
583f4a2713aSLionel Sambuc 
584f4a2713aSLionel Sambuc   return ED;
585f4a2713aSLionel Sambuc }
586f4a2713aSLionel Sambuc 
587f4a2713aSLionel Sambuc /// Adjust the given return statements so that they formally return
588f4a2713aSLionel Sambuc /// the given type.  It should require, at most, an IntegralCast.
adjustBlockReturnsToEnum(Sema & S,ArrayRef<ReturnStmt * > returns,QualType returnType)589f4a2713aSLionel Sambuc static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
590f4a2713aSLionel Sambuc                                      QualType returnType) {
591f4a2713aSLionel Sambuc   for (ArrayRef<ReturnStmt*>::iterator
592f4a2713aSLionel Sambuc          i = returns.begin(), e = returns.end(); i != e; ++i) {
593f4a2713aSLionel Sambuc     ReturnStmt *ret = *i;
594f4a2713aSLionel Sambuc     Expr *retValue = ret->getRetValue();
595f4a2713aSLionel Sambuc     if (S.Context.hasSameType(retValue->getType(), returnType))
596f4a2713aSLionel Sambuc       continue;
597f4a2713aSLionel Sambuc 
598f4a2713aSLionel Sambuc     // Right now we only support integral fixup casts.
599f4a2713aSLionel Sambuc     assert(returnType->isIntegralOrUnscopedEnumerationType());
600f4a2713aSLionel Sambuc     assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
601f4a2713aSLionel Sambuc 
602f4a2713aSLionel Sambuc     ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
603f4a2713aSLionel Sambuc 
604f4a2713aSLionel Sambuc     Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
605f4a2713aSLionel Sambuc     E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
606*0a6a1f1dSLionel Sambuc                                  E, /*base path*/ nullptr, VK_RValue);
607f4a2713aSLionel Sambuc     if (cleanups) {
608f4a2713aSLionel Sambuc       cleanups->setSubExpr(E);
609f4a2713aSLionel Sambuc     } else {
610f4a2713aSLionel Sambuc       ret->setRetValue(E);
611f4a2713aSLionel Sambuc     }
612f4a2713aSLionel Sambuc   }
613f4a2713aSLionel Sambuc }
614f4a2713aSLionel Sambuc 
deduceClosureReturnType(CapturingScopeInfo & CSI)615f4a2713aSLionel Sambuc void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
616f4a2713aSLionel Sambuc   assert(CSI.HasImplicitReturnType);
617f4a2713aSLionel Sambuc   // If it was ever a placeholder, it had to been deduced to DependentTy.
618f4a2713aSLionel Sambuc   assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
619f4a2713aSLionel Sambuc 
620*0a6a1f1dSLionel Sambuc   // C++ core issue 975:
621f4a2713aSLionel Sambuc   //   If a lambda-expression does not include a trailing-return-type,
622f4a2713aSLionel Sambuc   //   it is as if the trailing-return-type denotes the following type:
623f4a2713aSLionel Sambuc   //     - if there are no return statements in the compound-statement,
624f4a2713aSLionel Sambuc   //       or all return statements return either an expression of type
625f4a2713aSLionel Sambuc   //       void or no expression or braced-init-list, the type void;
626f4a2713aSLionel Sambuc   //     - otherwise, if all return statements return an expression
627f4a2713aSLionel Sambuc   //       and the types of the returned expressions after
628f4a2713aSLionel Sambuc   //       lvalue-to-rvalue conversion (4.1 [conv.lval]),
629f4a2713aSLionel Sambuc   //       array-to-pointer conversion (4.2 [conv.array]), and
630f4a2713aSLionel Sambuc   //       function-to-pointer conversion (4.3 [conv.func]) are the
631f4a2713aSLionel Sambuc   //       same, that common type;
632f4a2713aSLionel Sambuc   //     - otherwise, the program is ill-formed.
633f4a2713aSLionel Sambuc   //
634*0a6a1f1dSLionel Sambuc   // C++ core issue 1048 additionally removes top-level cv-qualifiers
635*0a6a1f1dSLionel Sambuc   // from the types of returned expressions to match the C++14 auto
636*0a6a1f1dSLionel Sambuc   // deduction rules.
637*0a6a1f1dSLionel Sambuc   //
638f4a2713aSLionel Sambuc   // In addition, in blocks in non-C++ modes, if all of the return
639f4a2713aSLionel Sambuc   // statements are enumerator-like expressions of some type T, where
640f4a2713aSLionel Sambuc   // T has a name for linkage, then we infer the return type of the
641f4a2713aSLionel Sambuc   // block to be that type.
642f4a2713aSLionel Sambuc 
643f4a2713aSLionel Sambuc   // First case: no return statements, implicit void return type.
644f4a2713aSLionel Sambuc   ASTContext &Ctx = getASTContext();
645f4a2713aSLionel Sambuc   if (CSI.Returns.empty()) {
646f4a2713aSLionel Sambuc     // It's possible there were simply no /valid/ return statements.
647f4a2713aSLionel Sambuc     // In this case, the first one we found may have at least given us a type.
648f4a2713aSLionel Sambuc     if (CSI.ReturnType.isNull())
649f4a2713aSLionel Sambuc       CSI.ReturnType = Ctx.VoidTy;
650f4a2713aSLionel Sambuc     return;
651f4a2713aSLionel Sambuc   }
652f4a2713aSLionel Sambuc 
653f4a2713aSLionel Sambuc   // Second case: at least one return statement has dependent type.
654f4a2713aSLionel Sambuc   // Delay type checking until instantiation.
655f4a2713aSLionel Sambuc   assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
656f4a2713aSLionel Sambuc   if (CSI.ReturnType->isDependentType())
657f4a2713aSLionel Sambuc     return;
658f4a2713aSLionel Sambuc 
659f4a2713aSLionel Sambuc   // Try to apply the enum-fuzz rule.
660f4a2713aSLionel Sambuc   if (!getLangOpts().CPlusPlus) {
661f4a2713aSLionel Sambuc     assert(isa<BlockScopeInfo>(CSI));
662f4a2713aSLionel Sambuc     const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
663f4a2713aSLionel Sambuc     if (ED) {
664f4a2713aSLionel Sambuc       CSI.ReturnType = Context.getTypeDeclType(ED);
665f4a2713aSLionel Sambuc       adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
666f4a2713aSLionel Sambuc       return;
667f4a2713aSLionel Sambuc     }
668f4a2713aSLionel Sambuc   }
669f4a2713aSLionel Sambuc 
670f4a2713aSLionel Sambuc   // Third case: only one return statement. Don't bother doing extra work!
671f4a2713aSLionel Sambuc   SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
672f4a2713aSLionel Sambuc                                          E = CSI.Returns.end();
673f4a2713aSLionel Sambuc   if (I+1 == E)
674f4a2713aSLionel Sambuc     return;
675f4a2713aSLionel Sambuc 
676f4a2713aSLionel Sambuc   // General case: many return statements.
677f4a2713aSLionel Sambuc   // Check that they all have compatible return types.
678f4a2713aSLionel Sambuc 
679f4a2713aSLionel Sambuc   // We require the return types to strictly match here.
680f4a2713aSLionel Sambuc   // Note that we've already done the required promotions as part of
681f4a2713aSLionel Sambuc   // processing the return statement.
682f4a2713aSLionel Sambuc   for (; I != E; ++I) {
683f4a2713aSLionel Sambuc     const ReturnStmt *RS = *I;
684f4a2713aSLionel Sambuc     const Expr *RetE = RS->getRetValue();
685f4a2713aSLionel Sambuc 
686*0a6a1f1dSLionel Sambuc     QualType ReturnType =
687*0a6a1f1dSLionel Sambuc         (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
688f4a2713aSLionel Sambuc     if (Context.hasSameType(ReturnType, CSI.ReturnType))
689f4a2713aSLionel Sambuc       continue;
690f4a2713aSLionel Sambuc 
691f4a2713aSLionel Sambuc     // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
692f4a2713aSLionel Sambuc     // TODO: It's possible that the *first* return is the divergent one.
693f4a2713aSLionel Sambuc     Diag(RS->getLocStart(),
694f4a2713aSLionel Sambuc          diag::err_typecheck_missing_return_type_incompatible)
695f4a2713aSLionel Sambuc       << ReturnType << CSI.ReturnType
696f4a2713aSLionel Sambuc       << isa<LambdaScopeInfo>(CSI);
697f4a2713aSLionel Sambuc     // Continue iterating so that we keep emitting diagnostics.
698f4a2713aSLionel Sambuc   }
699f4a2713aSLionel Sambuc }
700f4a2713aSLionel Sambuc 
performLambdaInitCaptureInitialization(SourceLocation Loc,bool ByRef,IdentifierInfo * Id,Expr * & Init)701*0a6a1f1dSLionel Sambuc QualType Sema::performLambdaInitCaptureInitialization(SourceLocation Loc,
702*0a6a1f1dSLionel Sambuc                                                       bool ByRef,
703*0a6a1f1dSLionel Sambuc                                                       IdentifierInfo *Id,
704*0a6a1f1dSLionel Sambuc                                                       Expr *&Init) {
705*0a6a1f1dSLionel Sambuc 
706*0a6a1f1dSLionel Sambuc   // We do not need to distinguish between direct-list-initialization
707*0a6a1f1dSLionel Sambuc   // and copy-list-initialization here, because we will always deduce
708*0a6a1f1dSLionel Sambuc   // std::initializer_list<T>, and direct- and copy-list-initialization
709*0a6a1f1dSLionel Sambuc   // always behave the same for such a type.
710*0a6a1f1dSLionel Sambuc   // FIXME: We should model whether an '=' was present.
711*0a6a1f1dSLionel Sambuc   const bool IsDirectInit = isa<ParenListExpr>(Init) || isa<InitListExpr>(Init);
712*0a6a1f1dSLionel Sambuc 
713*0a6a1f1dSLionel Sambuc   // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
714*0a6a1f1dSLionel Sambuc   // deduce against.
715f4a2713aSLionel Sambuc   QualType DeductType = Context.getAutoDeductType();
716f4a2713aSLionel Sambuc   TypeLocBuilder TLB;
717f4a2713aSLionel Sambuc   TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
718f4a2713aSLionel Sambuc   if (ByRef) {
719f4a2713aSLionel Sambuc     DeductType = BuildReferenceType(DeductType, true, Loc, Id);
720f4a2713aSLionel Sambuc     assert(!DeductType.isNull() && "can't build reference to auto");
721f4a2713aSLionel Sambuc     TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
722f4a2713aSLionel Sambuc   }
723f4a2713aSLionel Sambuc   TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
724f4a2713aSLionel Sambuc 
725*0a6a1f1dSLionel Sambuc   // Are we a non-list direct initialization?
726*0a6a1f1dSLionel Sambuc   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
727*0a6a1f1dSLionel Sambuc 
728*0a6a1f1dSLionel Sambuc   Expr *DeduceInit = Init;
729*0a6a1f1dSLionel Sambuc   // Initializer could be a C++ direct-initializer. Deduction only works if it
730*0a6a1f1dSLionel Sambuc   // contains exactly one expression.
731*0a6a1f1dSLionel Sambuc   if (CXXDirectInit) {
732*0a6a1f1dSLionel Sambuc     if (CXXDirectInit->getNumExprs() == 0) {
733*0a6a1f1dSLionel Sambuc       Diag(CXXDirectInit->getLocStart(), diag::err_init_capture_no_expression)
734*0a6a1f1dSLionel Sambuc           << DeclarationName(Id) << TSI->getType() << Loc;
735*0a6a1f1dSLionel Sambuc       return QualType();
736*0a6a1f1dSLionel Sambuc     } else if (CXXDirectInit->getNumExprs() > 1) {
737*0a6a1f1dSLionel Sambuc       Diag(CXXDirectInit->getExpr(1)->getLocStart(),
738*0a6a1f1dSLionel Sambuc            diag::err_init_capture_multiple_expressions)
739*0a6a1f1dSLionel Sambuc           << DeclarationName(Id) << TSI->getType() << Loc;
740*0a6a1f1dSLionel Sambuc       return QualType();
741*0a6a1f1dSLionel Sambuc     } else {
742*0a6a1f1dSLionel Sambuc       DeduceInit = CXXDirectInit->getExpr(0);
743*0a6a1f1dSLionel Sambuc       if (isa<InitListExpr>(DeduceInit))
744*0a6a1f1dSLionel Sambuc         Diag(CXXDirectInit->getLocStart(), diag::err_init_capture_paren_braces)
745*0a6a1f1dSLionel Sambuc           << DeclarationName(Id) << Loc;
746*0a6a1f1dSLionel Sambuc     }
747*0a6a1f1dSLionel Sambuc   }
748*0a6a1f1dSLionel Sambuc 
749*0a6a1f1dSLionel Sambuc   // Now deduce against the initialization expression and store the deduced
750*0a6a1f1dSLionel Sambuc   // type below.
751*0a6a1f1dSLionel Sambuc   QualType DeducedType;
752*0a6a1f1dSLionel Sambuc   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
753*0a6a1f1dSLionel Sambuc     if (isa<InitListExpr>(Init))
754*0a6a1f1dSLionel Sambuc       Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list)
755*0a6a1f1dSLionel Sambuc           << DeclarationName(Id)
756*0a6a1f1dSLionel Sambuc           << (DeduceInit->getType().isNull() ? TSI->getType()
757*0a6a1f1dSLionel Sambuc                                              : DeduceInit->getType())
758*0a6a1f1dSLionel Sambuc           << DeduceInit->getSourceRange();
759*0a6a1f1dSLionel Sambuc     else
760*0a6a1f1dSLionel Sambuc       Diag(Loc, diag::err_init_capture_deduction_failure)
761*0a6a1f1dSLionel Sambuc           << DeclarationName(Id) << TSI->getType()
762*0a6a1f1dSLionel Sambuc           << (DeduceInit->getType().isNull() ? TSI->getType()
763*0a6a1f1dSLionel Sambuc                                              : DeduceInit->getType())
764*0a6a1f1dSLionel Sambuc           << DeduceInit->getSourceRange();
765*0a6a1f1dSLionel Sambuc   }
766*0a6a1f1dSLionel Sambuc   if (DeducedType.isNull())
767*0a6a1f1dSLionel Sambuc     return QualType();
768*0a6a1f1dSLionel Sambuc 
769*0a6a1f1dSLionel Sambuc   // Perform initialization analysis and ensure any implicit conversions
770*0a6a1f1dSLionel Sambuc   // (such as lvalue-to-rvalue) are enforced.
771*0a6a1f1dSLionel Sambuc   InitializedEntity Entity =
772*0a6a1f1dSLionel Sambuc       InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
773*0a6a1f1dSLionel Sambuc   InitializationKind Kind =
774*0a6a1f1dSLionel Sambuc       IsDirectInit
775*0a6a1f1dSLionel Sambuc           ? (CXXDirectInit ? InitializationKind::CreateDirect(
776*0a6a1f1dSLionel Sambuc                                  Loc, Init->getLocStart(), Init->getLocEnd())
777*0a6a1f1dSLionel Sambuc                            : InitializationKind::CreateDirectList(Loc))
778*0a6a1f1dSLionel Sambuc           : InitializationKind::CreateCopy(Loc, Init->getLocStart());
779*0a6a1f1dSLionel Sambuc 
780*0a6a1f1dSLionel Sambuc   MultiExprArg Args = Init;
781*0a6a1f1dSLionel Sambuc   if (CXXDirectInit)
782*0a6a1f1dSLionel Sambuc     Args =
783*0a6a1f1dSLionel Sambuc         MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
784*0a6a1f1dSLionel Sambuc   QualType DclT;
785*0a6a1f1dSLionel Sambuc   InitializationSequence InitSeq(*this, Entity, Kind, Args);
786*0a6a1f1dSLionel Sambuc   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
787*0a6a1f1dSLionel Sambuc 
788*0a6a1f1dSLionel Sambuc   if (Result.isInvalid())
789*0a6a1f1dSLionel Sambuc     return QualType();
790*0a6a1f1dSLionel Sambuc   Init = Result.getAs<Expr>();
791*0a6a1f1dSLionel Sambuc 
792*0a6a1f1dSLionel Sambuc   // The init-capture initialization is a full-expression that must be
793*0a6a1f1dSLionel Sambuc   // processed as one before we enter the declcontext of the lambda's
794*0a6a1f1dSLionel Sambuc   // call-operator.
795*0a6a1f1dSLionel Sambuc   Result = ActOnFinishFullExpr(Init, Loc, /*DiscardedValue*/ false,
796*0a6a1f1dSLionel Sambuc                                /*IsConstexpr*/ false,
797*0a6a1f1dSLionel Sambuc                                /*IsLambdaInitCaptureInitalizer*/ true);
798*0a6a1f1dSLionel Sambuc   if (Result.isInvalid())
799*0a6a1f1dSLionel Sambuc     return QualType();
800*0a6a1f1dSLionel Sambuc 
801*0a6a1f1dSLionel Sambuc   Init = Result.getAs<Expr>();
802*0a6a1f1dSLionel Sambuc   return DeducedType;
803*0a6a1f1dSLionel Sambuc }
804*0a6a1f1dSLionel Sambuc 
createLambdaInitCaptureVarDecl(SourceLocation Loc,QualType InitCaptureType,IdentifierInfo * Id,Expr * Init)805*0a6a1f1dSLionel Sambuc VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
806*0a6a1f1dSLionel Sambuc     QualType InitCaptureType, IdentifierInfo *Id, Expr *Init) {
807*0a6a1f1dSLionel Sambuc 
808*0a6a1f1dSLionel Sambuc   TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType,
809*0a6a1f1dSLionel Sambuc       Loc);
810f4a2713aSLionel Sambuc   // Create a dummy variable representing the init-capture. This is not actually
811f4a2713aSLionel Sambuc   // used as a variable, and only exists as a way to name and refer to the
812f4a2713aSLionel Sambuc   // init-capture.
813f4a2713aSLionel Sambuc   // FIXME: Pass in separate source locations for '&' and identifier.
814f4a2713aSLionel Sambuc   VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
815*0a6a1f1dSLionel Sambuc                                    Loc, Id, InitCaptureType, TSI, SC_Auto);
816f4a2713aSLionel Sambuc   NewVD->setInitCapture(true);
817f4a2713aSLionel Sambuc   NewVD->setReferenced(true);
818f4a2713aSLionel Sambuc   NewVD->markUsed(Context);
819*0a6a1f1dSLionel Sambuc   NewVD->setInit(Init);
820f4a2713aSLionel Sambuc   return NewVD;
821*0a6a1f1dSLionel Sambuc 
822f4a2713aSLionel Sambuc }
823f4a2713aSLionel Sambuc 
buildInitCaptureField(LambdaScopeInfo * LSI,VarDecl * Var)824f4a2713aSLionel Sambuc FieldDecl *Sema::buildInitCaptureField(LambdaScopeInfo *LSI, VarDecl *Var) {
825f4a2713aSLionel Sambuc   FieldDecl *Field = FieldDecl::Create(
826f4a2713aSLionel Sambuc       Context, LSI->Lambda, Var->getLocation(), Var->getLocation(),
827*0a6a1f1dSLionel Sambuc       nullptr, Var->getType(), Var->getTypeSourceInfo(), nullptr, false,
828*0a6a1f1dSLionel Sambuc       ICIS_NoInit);
829f4a2713aSLionel Sambuc   Field->setImplicit(true);
830f4a2713aSLionel Sambuc   Field->setAccess(AS_private);
831f4a2713aSLionel Sambuc   LSI->Lambda->addDecl(Field);
832f4a2713aSLionel Sambuc 
833f4a2713aSLionel Sambuc   LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
834f4a2713aSLionel Sambuc                   /*isNested*/false, Var->getLocation(), SourceLocation(),
835f4a2713aSLionel Sambuc                   Var->getType(), Var->getInit());
836f4a2713aSLionel Sambuc   return Field;
837f4a2713aSLionel Sambuc }
838f4a2713aSLionel Sambuc 
ActOnStartOfLambdaDefinition(LambdaIntroducer & Intro,Declarator & ParamInfo,Scope * CurScope)839f4a2713aSLionel Sambuc void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
840f4a2713aSLionel Sambuc                   Declarator &ParamInfo, Scope *CurScope) {
841f4a2713aSLionel Sambuc   // Determine if we're within a context where we know that the lambda will
842f4a2713aSLionel Sambuc   // be dependent, because there are template parameters in scope.
843f4a2713aSLionel Sambuc   bool KnownDependent = false;
844f4a2713aSLionel Sambuc   LambdaScopeInfo *const LSI = getCurLambda();
845f4a2713aSLionel Sambuc   assert(LSI && "LambdaScopeInfo should be on stack!");
846f4a2713aSLionel Sambuc   TemplateParameterList *TemplateParams =
847f4a2713aSLionel Sambuc             getGenericLambdaTemplateParameterList(LSI, *this);
848f4a2713aSLionel Sambuc 
849f4a2713aSLionel Sambuc   if (Scope *TmplScope = CurScope->getTemplateParamParent()) {
850f4a2713aSLionel Sambuc     // Since we have our own TemplateParams, so check if an outer scope
851f4a2713aSLionel Sambuc     // has template params, only then are we in a dependent scope.
852f4a2713aSLionel Sambuc     if (TemplateParams)  {
853f4a2713aSLionel Sambuc       TmplScope = TmplScope->getParent();
854*0a6a1f1dSLionel Sambuc       TmplScope = TmplScope ? TmplScope->getTemplateParamParent() : nullptr;
855f4a2713aSLionel Sambuc     }
856f4a2713aSLionel Sambuc     if (TmplScope && !TmplScope->decl_empty())
857f4a2713aSLionel Sambuc       KnownDependent = true;
858f4a2713aSLionel Sambuc   }
859f4a2713aSLionel Sambuc   // Determine the signature of the call operator.
860f4a2713aSLionel Sambuc   TypeSourceInfo *MethodTyInfo;
861f4a2713aSLionel Sambuc   bool ExplicitParams = true;
862f4a2713aSLionel Sambuc   bool ExplicitResultType = true;
863f4a2713aSLionel Sambuc   bool ContainsUnexpandedParameterPack = false;
864f4a2713aSLionel Sambuc   SourceLocation EndLoc;
865f4a2713aSLionel Sambuc   SmallVector<ParmVarDecl *, 8> Params;
866f4a2713aSLionel Sambuc   if (ParamInfo.getNumTypeObjects() == 0) {
867f4a2713aSLionel Sambuc     // C++11 [expr.prim.lambda]p4:
868f4a2713aSLionel Sambuc     //   If a lambda-expression does not include a lambda-declarator, it is as
869f4a2713aSLionel Sambuc     //   if the lambda-declarator were ().
870f4a2713aSLionel Sambuc     FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
871f4a2713aSLionel Sambuc         /*IsVariadic=*/false, /*IsCXXMethod=*/true));
872f4a2713aSLionel Sambuc     EPI.HasTrailingReturn = true;
873f4a2713aSLionel Sambuc     EPI.TypeQuals |= DeclSpec::TQ_const;
874f4a2713aSLionel Sambuc     // C++1y [expr.prim.lambda]:
875f4a2713aSLionel Sambuc     //   The lambda return type is 'auto', which is replaced by the
876f4a2713aSLionel Sambuc     //   trailing-return type if provided and/or deduced from 'return'
877f4a2713aSLionel Sambuc     //   statements
878f4a2713aSLionel Sambuc     // We don't do this before C++1y, because we don't support deduced return
879f4a2713aSLionel Sambuc     // types there.
880f4a2713aSLionel Sambuc     QualType DefaultTypeForNoTrailingReturn =
881*0a6a1f1dSLionel Sambuc         getLangOpts().CPlusPlus14 ? Context.getAutoDeductType()
882f4a2713aSLionel Sambuc                                   : Context.DependentTy;
883f4a2713aSLionel Sambuc     QualType MethodTy =
884f4a2713aSLionel Sambuc         Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
885f4a2713aSLionel Sambuc     MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
886f4a2713aSLionel Sambuc     ExplicitParams = false;
887f4a2713aSLionel Sambuc     ExplicitResultType = false;
888f4a2713aSLionel Sambuc     EndLoc = Intro.Range.getEnd();
889f4a2713aSLionel Sambuc   } else {
890f4a2713aSLionel Sambuc     assert(ParamInfo.isFunctionDeclarator() &&
891f4a2713aSLionel Sambuc            "lambda-declarator is a function");
892f4a2713aSLionel Sambuc     DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
893f4a2713aSLionel Sambuc 
894f4a2713aSLionel Sambuc     // C++11 [expr.prim.lambda]p5:
895f4a2713aSLionel Sambuc     //   This function call operator is declared const (9.3.1) if and only if
896f4a2713aSLionel Sambuc     //   the lambda-expression's parameter-declaration-clause is not followed
897f4a2713aSLionel Sambuc     //   by mutable. It is neither virtual nor declared volatile. [...]
898f4a2713aSLionel Sambuc     if (!FTI.hasMutableQualifier())
899f4a2713aSLionel Sambuc       FTI.TypeQuals |= DeclSpec::TQ_const;
900f4a2713aSLionel Sambuc 
901f4a2713aSLionel Sambuc     MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
902f4a2713aSLionel Sambuc     assert(MethodTyInfo && "no type from lambda-declarator");
903f4a2713aSLionel Sambuc     EndLoc = ParamInfo.getSourceRange().getEnd();
904f4a2713aSLionel Sambuc 
905f4a2713aSLionel Sambuc     ExplicitResultType = FTI.hasTrailingReturnType();
906f4a2713aSLionel Sambuc 
907*0a6a1f1dSLionel Sambuc     if (FTIHasNonVoidParameters(FTI)) {
908*0a6a1f1dSLionel Sambuc       Params.reserve(FTI.NumParams);
909*0a6a1f1dSLionel Sambuc       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i)
910*0a6a1f1dSLionel Sambuc         Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param));
911f4a2713aSLionel Sambuc     }
912f4a2713aSLionel Sambuc 
913f4a2713aSLionel Sambuc     // Check for unexpanded parameter packs in the method type.
914f4a2713aSLionel Sambuc     if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
915f4a2713aSLionel Sambuc       ContainsUnexpandedParameterPack = true;
916f4a2713aSLionel Sambuc   }
917f4a2713aSLionel Sambuc 
918f4a2713aSLionel Sambuc   CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
919f4a2713aSLionel Sambuc                                                  KnownDependent, Intro.Default);
920f4a2713aSLionel Sambuc 
921f4a2713aSLionel Sambuc   CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
922f4a2713aSLionel Sambuc                                                 MethodTyInfo, EndLoc, Params);
923f4a2713aSLionel Sambuc   if (ExplicitParams)
924f4a2713aSLionel Sambuc     CheckCXXDefaultArguments(Method);
925f4a2713aSLionel Sambuc 
926f4a2713aSLionel Sambuc   // Attributes on the lambda apply to the method.
927f4a2713aSLionel Sambuc   ProcessDeclAttributes(CurScope, Method, ParamInfo);
928f4a2713aSLionel Sambuc 
929f4a2713aSLionel Sambuc   // Introduce the function call operator as the current declaration context.
930f4a2713aSLionel Sambuc   PushDeclContext(CurScope, Method);
931f4a2713aSLionel Sambuc 
932f4a2713aSLionel Sambuc   // Build the lambda scope.
933f4a2713aSLionel Sambuc   buildLambdaScope(LSI, Method,
934f4a2713aSLionel Sambuc                        Intro.Range,
935f4a2713aSLionel Sambuc                        Intro.Default, Intro.DefaultLoc,
936f4a2713aSLionel Sambuc                        ExplicitParams,
937f4a2713aSLionel Sambuc                        ExplicitResultType,
938f4a2713aSLionel Sambuc                        !Method->isConst());
939f4a2713aSLionel Sambuc 
940*0a6a1f1dSLionel Sambuc   // C++11 [expr.prim.lambda]p9:
941*0a6a1f1dSLionel Sambuc   //   A lambda-expression whose smallest enclosing scope is a block scope is a
942*0a6a1f1dSLionel Sambuc   //   local lambda expression; any other lambda expression shall not have a
943*0a6a1f1dSLionel Sambuc   //   capture-default or simple-capture in its lambda-introducer.
944*0a6a1f1dSLionel Sambuc   //
945*0a6a1f1dSLionel Sambuc   // For simple-captures, this is covered by the check below that any named
946*0a6a1f1dSLionel Sambuc   // entity is a variable that can be captured.
947*0a6a1f1dSLionel Sambuc   //
948*0a6a1f1dSLionel Sambuc   // For DR1632, we also allow a capture-default in any context where we can
949*0a6a1f1dSLionel Sambuc   // odr-use 'this' (in particular, in a default initializer for a non-static
950*0a6a1f1dSLionel Sambuc   // data member).
951*0a6a1f1dSLionel Sambuc   if (Intro.Default != LCD_None && !Class->getParent()->isFunctionOrMethod() &&
952*0a6a1f1dSLionel Sambuc       (getCurrentThisType().isNull() ||
953*0a6a1f1dSLionel Sambuc        CheckCXXThisCapture(SourceLocation(), /*Explicit*/true,
954*0a6a1f1dSLionel Sambuc                            /*BuildAndDiagnose*/false)))
955*0a6a1f1dSLionel Sambuc     Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
956*0a6a1f1dSLionel Sambuc 
957f4a2713aSLionel Sambuc   // Distinct capture names, for diagnostics.
958f4a2713aSLionel Sambuc   llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
959f4a2713aSLionel Sambuc 
960f4a2713aSLionel Sambuc   // Handle explicit captures.
961f4a2713aSLionel Sambuc   SourceLocation PrevCaptureLoc
962f4a2713aSLionel Sambuc     = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
963*0a6a1f1dSLionel Sambuc   for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
964f4a2713aSLionel Sambuc        PrevCaptureLoc = C->Loc, ++C) {
965f4a2713aSLionel Sambuc     if (C->Kind == LCK_This) {
966f4a2713aSLionel Sambuc       // C++11 [expr.prim.lambda]p8:
967f4a2713aSLionel Sambuc       //   An identifier or this shall not appear more than once in a
968f4a2713aSLionel Sambuc       //   lambda-capture.
969f4a2713aSLionel Sambuc       if (LSI->isCXXThisCaptured()) {
970f4a2713aSLionel Sambuc         Diag(C->Loc, diag::err_capture_more_than_once)
971*0a6a1f1dSLionel Sambuc             << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
972f4a2713aSLionel Sambuc             << FixItHint::CreateRemoval(
973*0a6a1f1dSLionel Sambuc                    SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
974f4a2713aSLionel Sambuc         continue;
975f4a2713aSLionel Sambuc       }
976f4a2713aSLionel Sambuc 
977f4a2713aSLionel Sambuc       // C++11 [expr.prim.lambda]p8:
978f4a2713aSLionel Sambuc       //   If a lambda-capture includes a capture-default that is =, the
979f4a2713aSLionel Sambuc       //   lambda-capture shall not contain this [...].
980f4a2713aSLionel Sambuc       if (Intro.Default == LCD_ByCopy) {
981f4a2713aSLionel Sambuc         Diag(C->Loc, diag::err_this_capture_with_copy_default)
982f4a2713aSLionel Sambuc             << FixItHint::CreateRemoval(
983*0a6a1f1dSLionel Sambuc                 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
984f4a2713aSLionel Sambuc         continue;
985f4a2713aSLionel Sambuc       }
986f4a2713aSLionel Sambuc 
987f4a2713aSLionel Sambuc       // C++11 [expr.prim.lambda]p12:
988f4a2713aSLionel Sambuc       //   If this is captured by a local lambda expression, its nearest
989f4a2713aSLionel Sambuc       //   enclosing function shall be a non-static member function.
990f4a2713aSLionel Sambuc       QualType ThisCaptureType = getCurrentThisType();
991f4a2713aSLionel Sambuc       if (ThisCaptureType.isNull()) {
992f4a2713aSLionel Sambuc         Diag(C->Loc, diag::err_this_capture) << true;
993f4a2713aSLionel Sambuc         continue;
994f4a2713aSLionel Sambuc       }
995f4a2713aSLionel Sambuc 
996f4a2713aSLionel Sambuc       CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
997f4a2713aSLionel Sambuc       continue;
998f4a2713aSLionel Sambuc     }
999f4a2713aSLionel Sambuc 
1000f4a2713aSLionel Sambuc     assert(C->Id && "missing identifier for capture");
1001f4a2713aSLionel Sambuc 
1002f4a2713aSLionel Sambuc     if (C->Init.isInvalid())
1003f4a2713aSLionel Sambuc       continue;
1004f4a2713aSLionel Sambuc 
1005*0a6a1f1dSLionel Sambuc     VarDecl *Var = nullptr;
1006f4a2713aSLionel Sambuc     if (C->Init.isUsable()) {
1007*0a6a1f1dSLionel Sambuc       Diag(C->Loc, getLangOpts().CPlusPlus14
1008f4a2713aSLionel Sambuc                        ? diag::warn_cxx11_compat_init_capture
1009f4a2713aSLionel Sambuc                        : diag::ext_init_capture);
1010f4a2713aSLionel Sambuc 
1011f4a2713aSLionel Sambuc       if (C->Init.get()->containsUnexpandedParameterPack())
1012f4a2713aSLionel Sambuc         ContainsUnexpandedParameterPack = true;
1013*0a6a1f1dSLionel Sambuc       // If the initializer expression is usable, but the InitCaptureType
1014*0a6a1f1dSLionel Sambuc       // is not, then an error has occurred - so ignore the capture for now.
1015*0a6a1f1dSLionel Sambuc       // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1016*0a6a1f1dSLionel Sambuc       // FIXME: we should create the init capture variable and mark it invalid
1017*0a6a1f1dSLionel Sambuc       // in this case.
1018*0a6a1f1dSLionel Sambuc       if (C->InitCaptureType.get().isNull())
1019*0a6a1f1dSLionel Sambuc         continue;
1020*0a6a1f1dSLionel Sambuc       Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1021*0a6a1f1dSLionel Sambuc             C->Id, C->Init.get());
1022f4a2713aSLionel Sambuc       // C++1y [expr.prim.lambda]p11:
1023f4a2713aSLionel Sambuc       //   An init-capture behaves as if it declares and explicitly
1024f4a2713aSLionel Sambuc       //   captures a variable [...] whose declarative region is the
1025f4a2713aSLionel Sambuc       //   lambda-expression's compound-statement
1026f4a2713aSLionel Sambuc       if (Var)
1027f4a2713aSLionel Sambuc         PushOnScopeChains(Var, CurScope, false);
1028f4a2713aSLionel Sambuc     } else {
1029f4a2713aSLionel Sambuc       // C++11 [expr.prim.lambda]p8:
1030f4a2713aSLionel Sambuc       //   If a lambda-capture includes a capture-default that is &, the
1031f4a2713aSLionel Sambuc       //   identifiers in the lambda-capture shall not be preceded by &.
1032f4a2713aSLionel Sambuc       //   If a lambda-capture includes a capture-default that is =, [...]
1033f4a2713aSLionel Sambuc       //   each identifier it contains shall be preceded by &.
1034f4a2713aSLionel Sambuc       if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1035f4a2713aSLionel Sambuc         Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1036f4a2713aSLionel Sambuc             << FixItHint::CreateRemoval(
1037*0a6a1f1dSLionel Sambuc                 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1038f4a2713aSLionel Sambuc         continue;
1039f4a2713aSLionel Sambuc       } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1040f4a2713aSLionel Sambuc         Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1041f4a2713aSLionel Sambuc             << FixItHint::CreateRemoval(
1042*0a6a1f1dSLionel Sambuc                 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1043f4a2713aSLionel Sambuc         continue;
1044f4a2713aSLionel Sambuc       }
1045f4a2713aSLionel Sambuc 
1046f4a2713aSLionel Sambuc       // C++11 [expr.prim.lambda]p10:
1047f4a2713aSLionel Sambuc       //   The identifiers in a capture-list are looked up using the usual
1048f4a2713aSLionel Sambuc       //   rules for unqualified name lookup (3.4.1)
1049f4a2713aSLionel Sambuc       DeclarationNameInfo Name(C->Id, C->Loc);
1050f4a2713aSLionel Sambuc       LookupResult R(*this, Name, LookupOrdinaryName);
1051f4a2713aSLionel Sambuc       LookupName(R, CurScope);
1052f4a2713aSLionel Sambuc       if (R.isAmbiguous())
1053f4a2713aSLionel Sambuc         continue;
1054f4a2713aSLionel Sambuc       if (R.empty()) {
1055f4a2713aSLionel Sambuc         // FIXME: Disable corrections that would add qualification?
1056f4a2713aSLionel Sambuc         CXXScopeSpec ScopeSpec;
1057*0a6a1f1dSLionel Sambuc         if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R,
1058*0a6a1f1dSLionel Sambuc                                 llvm::make_unique<DeclFilterCCC<VarDecl>>()))
1059f4a2713aSLionel Sambuc           continue;
1060f4a2713aSLionel Sambuc       }
1061f4a2713aSLionel Sambuc 
1062f4a2713aSLionel Sambuc       Var = R.getAsSingle<VarDecl>();
1063*0a6a1f1dSLionel Sambuc       if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1064*0a6a1f1dSLionel Sambuc         continue;
1065f4a2713aSLionel Sambuc     }
1066f4a2713aSLionel Sambuc 
1067f4a2713aSLionel Sambuc     // C++11 [expr.prim.lambda]p8:
1068f4a2713aSLionel Sambuc     //   An identifier or this shall not appear more than once in a
1069f4a2713aSLionel Sambuc     //   lambda-capture.
1070*0a6a1f1dSLionel Sambuc     if (!CaptureNames.insert(C->Id).second) {
1071f4a2713aSLionel Sambuc       if (Var && LSI->isCaptured(Var)) {
1072f4a2713aSLionel Sambuc         Diag(C->Loc, diag::err_capture_more_than_once)
1073f4a2713aSLionel Sambuc             << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
1074f4a2713aSLionel Sambuc             << FixItHint::CreateRemoval(
1075*0a6a1f1dSLionel Sambuc                    SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1076f4a2713aSLionel Sambuc       } else
1077f4a2713aSLionel Sambuc         // Previous capture captured something different (one or both was
1078f4a2713aSLionel Sambuc         // an init-cpature): no fixit.
1079f4a2713aSLionel Sambuc         Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1080f4a2713aSLionel Sambuc       continue;
1081f4a2713aSLionel Sambuc     }
1082f4a2713aSLionel Sambuc 
1083f4a2713aSLionel Sambuc     // C++11 [expr.prim.lambda]p10:
1084f4a2713aSLionel Sambuc     //   [...] each such lookup shall find a variable with automatic storage
1085f4a2713aSLionel Sambuc     //   duration declared in the reaching scope of the local lambda expression.
1086f4a2713aSLionel Sambuc     // Note that the 'reaching scope' check happens in tryCaptureVariable().
1087f4a2713aSLionel Sambuc     if (!Var) {
1088f4a2713aSLionel Sambuc       Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1089f4a2713aSLionel Sambuc       continue;
1090f4a2713aSLionel Sambuc     }
1091f4a2713aSLionel Sambuc 
1092f4a2713aSLionel Sambuc     // Ignore invalid decls; they'll just confuse the code later.
1093f4a2713aSLionel Sambuc     if (Var->isInvalidDecl())
1094f4a2713aSLionel Sambuc       continue;
1095f4a2713aSLionel Sambuc 
1096f4a2713aSLionel Sambuc     if (!Var->hasLocalStorage()) {
1097f4a2713aSLionel Sambuc       Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1098f4a2713aSLionel Sambuc       Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1099f4a2713aSLionel Sambuc       continue;
1100f4a2713aSLionel Sambuc     }
1101f4a2713aSLionel Sambuc 
1102f4a2713aSLionel Sambuc     // C++11 [expr.prim.lambda]p23:
1103f4a2713aSLionel Sambuc     //   A capture followed by an ellipsis is a pack expansion (14.5.3).
1104f4a2713aSLionel Sambuc     SourceLocation EllipsisLoc;
1105f4a2713aSLionel Sambuc     if (C->EllipsisLoc.isValid()) {
1106f4a2713aSLionel Sambuc       if (Var->isParameterPack()) {
1107f4a2713aSLionel Sambuc         EllipsisLoc = C->EllipsisLoc;
1108f4a2713aSLionel Sambuc       } else {
1109f4a2713aSLionel Sambuc         Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1110f4a2713aSLionel Sambuc           << SourceRange(C->Loc);
1111f4a2713aSLionel Sambuc 
1112f4a2713aSLionel Sambuc         // Just ignore the ellipsis.
1113f4a2713aSLionel Sambuc       }
1114f4a2713aSLionel Sambuc     } else if (Var->isParameterPack()) {
1115f4a2713aSLionel Sambuc       ContainsUnexpandedParameterPack = true;
1116f4a2713aSLionel Sambuc     }
1117f4a2713aSLionel Sambuc 
1118f4a2713aSLionel Sambuc     if (C->Init.isUsable()) {
1119f4a2713aSLionel Sambuc       buildInitCaptureField(LSI, Var);
1120f4a2713aSLionel Sambuc     } else {
1121f4a2713aSLionel Sambuc       TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
1122f4a2713aSLionel Sambuc                                                    TryCapture_ExplicitByVal;
1123f4a2713aSLionel Sambuc       tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1124f4a2713aSLionel Sambuc     }
1125f4a2713aSLionel Sambuc   }
1126f4a2713aSLionel Sambuc   finishLambdaExplicitCaptures(LSI);
1127f4a2713aSLionel Sambuc 
1128f4a2713aSLionel Sambuc   LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1129f4a2713aSLionel Sambuc 
1130f4a2713aSLionel Sambuc   // Add lambda parameters into scope.
1131f4a2713aSLionel Sambuc   addLambdaParameters(Method, CurScope);
1132f4a2713aSLionel Sambuc 
1133f4a2713aSLionel Sambuc   // Enter a new evaluation context to insulate the lambda from any
1134f4a2713aSLionel Sambuc   // cleanups from the enclosing full-expression.
1135f4a2713aSLionel Sambuc   PushExpressionEvaluationContext(PotentiallyEvaluated);
1136f4a2713aSLionel Sambuc }
1137f4a2713aSLionel Sambuc 
ActOnLambdaError(SourceLocation StartLoc,Scope * CurScope,bool IsInstantiation)1138f4a2713aSLionel Sambuc void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
1139f4a2713aSLionel Sambuc                             bool IsInstantiation) {
1140*0a6a1f1dSLionel Sambuc   LambdaScopeInfo *LSI = getCurLambda();
1141*0a6a1f1dSLionel Sambuc 
1142f4a2713aSLionel Sambuc   // Leave the expression-evaluation context.
1143f4a2713aSLionel Sambuc   DiscardCleanupsInEvaluationContext();
1144f4a2713aSLionel Sambuc   PopExpressionEvaluationContext();
1145f4a2713aSLionel Sambuc 
1146f4a2713aSLionel Sambuc   // Leave the context of the lambda.
1147f4a2713aSLionel Sambuc   if (!IsInstantiation)
1148f4a2713aSLionel Sambuc     PopDeclContext();
1149f4a2713aSLionel Sambuc 
1150f4a2713aSLionel Sambuc   // Finalize the lambda.
1151f4a2713aSLionel Sambuc   CXXRecordDecl *Class = LSI->Lambda;
1152f4a2713aSLionel Sambuc   Class->setInvalidDecl();
1153*0a6a1f1dSLionel Sambuc   SmallVector<Decl*, 4> Fields(Class->fields());
1154*0a6a1f1dSLionel Sambuc   ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1155*0a6a1f1dSLionel Sambuc               SourceLocation(), nullptr);
1156f4a2713aSLionel Sambuc   CheckCompletedCXXClass(Class);
1157f4a2713aSLionel Sambuc 
1158f4a2713aSLionel Sambuc   PopFunctionScopeInfo();
1159f4a2713aSLionel Sambuc }
1160f4a2713aSLionel Sambuc 
1161f4a2713aSLionel Sambuc /// \brief Add a lambda's conversion to function pointer, as described in
1162f4a2713aSLionel Sambuc /// C++11 [expr.prim.lambda]p6.
addFunctionPointerConversion(Sema & S,SourceRange IntroducerRange,CXXRecordDecl * Class,CXXMethodDecl * CallOperator)1163f4a2713aSLionel Sambuc static void addFunctionPointerConversion(Sema &S,
1164f4a2713aSLionel Sambuc                                          SourceRange IntroducerRange,
1165f4a2713aSLionel Sambuc                                          CXXRecordDecl *Class,
1166f4a2713aSLionel Sambuc                                          CXXMethodDecl *CallOperator) {
1167f4a2713aSLionel Sambuc   // Add the conversion to function pointer.
1168f4a2713aSLionel Sambuc   const FunctionProtoType *CallOpProto =
1169f4a2713aSLionel Sambuc       CallOperator->getType()->getAs<FunctionProtoType>();
1170f4a2713aSLionel Sambuc   const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1171f4a2713aSLionel Sambuc       CallOpProto->getExtProtoInfo();
1172f4a2713aSLionel Sambuc   QualType PtrToFunctionTy;
1173f4a2713aSLionel Sambuc   QualType InvokerFunctionTy;
1174f4a2713aSLionel Sambuc   {
1175f4a2713aSLionel Sambuc     FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1176f4a2713aSLionel Sambuc     CallingConv CC = S.Context.getDefaultCallingConvention(
1177f4a2713aSLionel Sambuc         CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1178f4a2713aSLionel Sambuc     InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1179f4a2713aSLionel Sambuc     InvokerExtInfo.TypeQuals = 0;
1180f4a2713aSLionel Sambuc     assert(InvokerExtInfo.RefQualifier == RQ_None &&
1181f4a2713aSLionel Sambuc         "Lambda's call operator should not have a reference qualifier");
1182*0a6a1f1dSLionel Sambuc     InvokerFunctionTy =
1183*0a6a1f1dSLionel Sambuc         S.Context.getFunctionType(CallOpProto->getReturnType(),
1184*0a6a1f1dSLionel Sambuc                                   CallOpProto->getParamTypes(), InvokerExtInfo);
1185f4a2713aSLionel Sambuc     PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1186f4a2713aSLionel Sambuc   }
1187f4a2713aSLionel Sambuc 
1188f4a2713aSLionel Sambuc   // Create the type of the conversion function.
1189f4a2713aSLionel Sambuc   FunctionProtoType::ExtProtoInfo ConvExtInfo(
1190f4a2713aSLionel Sambuc       S.Context.getDefaultCallingConvention(
1191f4a2713aSLionel Sambuc       /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1192f4a2713aSLionel Sambuc   // The conversion function is always const.
1193f4a2713aSLionel Sambuc   ConvExtInfo.TypeQuals = Qualifiers::Const;
1194f4a2713aSLionel Sambuc   QualType ConvTy =
1195f4a2713aSLionel Sambuc       S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
1196f4a2713aSLionel Sambuc 
1197f4a2713aSLionel Sambuc   SourceLocation Loc = IntroducerRange.getBegin();
1198f4a2713aSLionel Sambuc   DeclarationName ConversionName
1199f4a2713aSLionel Sambuc     = S.Context.DeclarationNames.getCXXConversionFunctionName(
1200f4a2713aSLionel Sambuc         S.Context.getCanonicalType(PtrToFunctionTy));
1201f4a2713aSLionel Sambuc   DeclarationNameLoc ConvNameLoc;
1202f4a2713aSLionel Sambuc   // Construct a TypeSourceInfo for the conversion function, and wire
1203f4a2713aSLionel Sambuc   // all the parameters appropriately for the FunctionProtoTypeLoc
1204f4a2713aSLionel Sambuc   // so that everything works during transformation/instantiation of
1205f4a2713aSLionel Sambuc   // generic lambdas.
1206f4a2713aSLionel Sambuc   // The main reason for wiring up the parameters of the conversion
1207f4a2713aSLionel Sambuc   // function with that of the call operator is so that constructs
1208f4a2713aSLionel Sambuc   // like the following work:
1209f4a2713aSLionel Sambuc   // auto L = [](auto b) {                <-- 1
1210f4a2713aSLionel Sambuc   //   return [](auto a) -> decltype(a) { <-- 2
1211f4a2713aSLionel Sambuc   //      return a;
1212f4a2713aSLionel Sambuc   //   };
1213f4a2713aSLionel Sambuc   // };
1214f4a2713aSLionel Sambuc   // int (*fp)(int) = L(5);
1215f4a2713aSLionel Sambuc   // Because the trailing return type can contain DeclRefExprs that refer
1216f4a2713aSLionel Sambuc   // to the original call operator's variables, we hijack the call
1217f4a2713aSLionel Sambuc   // operators ParmVarDecls below.
1218f4a2713aSLionel Sambuc   TypeSourceInfo *ConvNamePtrToFunctionTSI =
1219f4a2713aSLionel Sambuc       S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1220f4a2713aSLionel Sambuc   ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI;
1221f4a2713aSLionel Sambuc 
1222f4a2713aSLionel Sambuc   // The conversion function is a conversion to a pointer-to-function.
1223f4a2713aSLionel Sambuc   TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1224f4a2713aSLionel Sambuc   FunctionProtoTypeLoc ConvTL =
1225f4a2713aSLionel Sambuc       ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1226f4a2713aSLionel Sambuc   // Get the result of the conversion function which is a pointer-to-function.
1227f4a2713aSLionel Sambuc   PointerTypeLoc PtrToFunctionTL =
1228*0a6a1f1dSLionel Sambuc       ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1229f4a2713aSLionel Sambuc   // Do the same for the TypeSourceInfo that is used to name the conversion
1230f4a2713aSLionel Sambuc   // operator.
1231f4a2713aSLionel Sambuc   PointerTypeLoc ConvNamePtrToFunctionTL =
1232f4a2713aSLionel Sambuc       ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1233f4a2713aSLionel Sambuc 
1234f4a2713aSLionel Sambuc   // Get the underlying function types that the conversion function will
1235f4a2713aSLionel Sambuc   // be converting to (should match the type of the call operator).
1236f4a2713aSLionel Sambuc   FunctionProtoTypeLoc CallOpConvTL =
1237f4a2713aSLionel Sambuc       PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1238f4a2713aSLionel Sambuc   FunctionProtoTypeLoc CallOpConvNameTL =
1239f4a2713aSLionel Sambuc     ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1240f4a2713aSLionel Sambuc 
1241f4a2713aSLionel Sambuc   // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1242f4a2713aSLionel Sambuc   // These parameter's are essentially used to transform the name and
1243f4a2713aSLionel Sambuc   // the type of the conversion operator.  By using the same parameters
1244f4a2713aSLionel Sambuc   // as the call operator's we don't have to fix any back references that
1245f4a2713aSLionel Sambuc   // the trailing return type of the call operator's uses (such as
1246f4a2713aSLionel Sambuc   // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1247f4a2713aSLionel Sambuc   // - we can simply use the return type of the call operator, and
1248f4a2713aSLionel Sambuc   // everything should work.
1249f4a2713aSLionel Sambuc   SmallVector<ParmVarDecl *, 4> InvokerParams;
1250f4a2713aSLionel Sambuc   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1251f4a2713aSLionel Sambuc     ParmVarDecl *From = CallOperator->getParamDecl(I);
1252f4a2713aSLionel Sambuc 
1253f4a2713aSLionel Sambuc     InvokerParams.push_back(ParmVarDecl::Create(S.Context,
1254f4a2713aSLionel Sambuc            // Temporarily add to the TU. This is set to the invoker below.
1255f4a2713aSLionel Sambuc                                              S.Context.getTranslationUnitDecl(),
1256f4a2713aSLionel Sambuc                                              From->getLocStart(),
1257f4a2713aSLionel Sambuc                                              From->getLocation(),
1258f4a2713aSLionel Sambuc                                              From->getIdentifier(),
1259f4a2713aSLionel Sambuc                                              From->getType(),
1260f4a2713aSLionel Sambuc                                              From->getTypeSourceInfo(),
1261f4a2713aSLionel Sambuc                                              From->getStorageClass(),
1262*0a6a1f1dSLionel Sambuc                                              /*DefaultArg=*/nullptr));
1263*0a6a1f1dSLionel Sambuc     CallOpConvTL.setParam(I, From);
1264*0a6a1f1dSLionel Sambuc     CallOpConvNameTL.setParam(I, From);
1265f4a2713aSLionel Sambuc   }
1266f4a2713aSLionel Sambuc 
1267f4a2713aSLionel Sambuc   CXXConversionDecl *Conversion
1268f4a2713aSLionel Sambuc     = CXXConversionDecl::Create(S.Context, Class, Loc,
1269f4a2713aSLionel Sambuc                                 DeclarationNameInfo(ConversionName,
1270f4a2713aSLionel Sambuc                                   Loc, ConvNameLoc),
1271f4a2713aSLionel Sambuc                                 ConvTy,
1272f4a2713aSLionel Sambuc                                 ConvTSI,
1273f4a2713aSLionel Sambuc                                 /*isInline=*/true, /*isExplicit=*/false,
1274f4a2713aSLionel Sambuc                                 /*isConstexpr=*/false,
1275f4a2713aSLionel Sambuc                                 CallOperator->getBody()->getLocEnd());
1276f4a2713aSLionel Sambuc   Conversion->setAccess(AS_public);
1277f4a2713aSLionel Sambuc   Conversion->setImplicit(true);
1278f4a2713aSLionel Sambuc 
1279f4a2713aSLionel Sambuc   if (Class->isGenericLambda()) {
1280f4a2713aSLionel Sambuc     // Create a template version of the conversion operator, using the template
1281f4a2713aSLionel Sambuc     // parameter list of the function call operator.
1282f4a2713aSLionel Sambuc     FunctionTemplateDecl *TemplateCallOperator =
1283f4a2713aSLionel Sambuc             CallOperator->getDescribedFunctionTemplate();
1284f4a2713aSLionel Sambuc     FunctionTemplateDecl *ConversionTemplate =
1285f4a2713aSLionel Sambuc                   FunctionTemplateDecl::Create(S.Context, Class,
1286f4a2713aSLionel Sambuc                                       Loc, ConversionName,
1287f4a2713aSLionel Sambuc                                       TemplateCallOperator->getTemplateParameters(),
1288f4a2713aSLionel Sambuc                                       Conversion);
1289f4a2713aSLionel Sambuc     ConversionTemplate->setAccess(AS_public);
1290f4a2713aSLionel Sambuc     ConversionTemplate->setImplicit(true);
1291f4a2713aSLionel Sambuc     Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1292f4a2713aSLionel Sambuc     Class->addDecl(ConversionTemplate);
1293f4a2713aSLionel Sambuc   } else
1294f4a2713aSLionel Sambuc     Class->addDecl(Conversion);
1295f4a2713aSLionel Sambuc   // Add a non-static member function that will be the result of
1296f4a2713aSLionel Sambuc   // the conversion with a certain unique ID.
1297f4a2713aSLionel Sambuc   DeclarationName InvokerName = &S.Context.Idents.get(
1298f4a2713aSLionel Sambuc                                                  getLambdaStaticInvokerName());
1299f4a2713aSLionel Sambuc   // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1300f4a2713aSLionel Sambuc   // we should get a prebuilt TrivialTypeSourceInfo from Context
1301f4a2713aSLionel Sambuc   // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1302f4a2713aSLionel Sambuc   // then rewire the parameters accordingly, by hoisting up the InvokeParams
1303f4a2713aSLionel Sambuc   // loop below and then use its Params to set Invoke->setParams(...) below.
1304f4a2713aSLionel Sambuc   // This would avoid the 'const' qualifier of the calloperator from
1305f4a2713aSLionel Sambuc   // contaminating the type of the invoker, which is currently adjusted
1306f4a2713aSLionel Sambuc   // in SemaTemplateDeduction.cpp:DeduceTemplateArguments.  Fixing the
1307f4a2713aSLionel Sambuc   // trailing return type of the invoker would require a visitor to rebuild
1308f4a2713aSLionel Sambuc   // the trailing return type and adjusting all back DeclRefExpr's to refer
1309f4a2713aSLionel Sambuc   // to the new static invoker parameters - not the call operator's.
1310f4a2713aSLionel Sambuc   CXXMethodDecl *Invoke
1311f4a2713aSLionel Sambuc     = CXXMethodDecl::Create(S.Context, Class, Loc,
1312f4a2713aSLionel Sambuc                             DeclarationNameInfo(InvokerName, Loc),
1313f4a2713aSLionel Sambuc                             InvokerFunctionTy,
1314f4a2713aSLionel Sambuc                             CallOperator->getTypeSourceInfo(),
1315f4a2713aSLionel Sambuc                             SC_Static, /*IsInline=*/true,
1316f4a2713aSLionel Sambuc                             /*IsConstexpr=*/false,
1317f4a2713aSLionel Sambuc                             CallOperator->getBody()->getLocEnd());
1318f4a2713aSLionel Sambuc   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1319f4a2713aSLionel Sambuc     InvokerParams[I]->setOwningFunction(Invoke);
1320f4a2713aSLionel Sambuc   Invoke->setParams(InvokerParams);
1321f4a2713aSLionel Sambuc   Invoke->setAccess(AS_private);
1322f4a2713aSLionel Sambuc   Invoke->setImplicit(true);
1323f4a2713aSLionel Sambuc   if (Class->isGenericLambda()) {
1324f4a2713aSLionel Sambuc     FunctionTemplateDecl *TemplateCallOperator =
1325f4a2713aSLionel Sambuc             CallOperator->getDescribedFunctionTemplate();
1326f4a2713aSLionel Sambuc     FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
1327f4a2713aSLionel Sambuc                           S.Context, Class, Loc, InvokerName,
1328f4a2713aSLionel Sambuc                           TemplateCallOperator->getTemplateParameters(),
1329f4a2713aSLionel Sambuc                           Invoke);
1330f4a2713aSLionel Sambuc     StaticInvokerTemplate->setAccess(AS_private);
1331f4a2713aSLionel Sambuc     StaticInvokerTemplate->setImplicit(true);
1332f4a2713aSLionel Sambuc     Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1333f4a2713aSLionel Sambuc     Class->addDecl(StaticInvokerTemplate);
1334f4a2713aSLionel Sambuc   } else
1335f4a2713aSLionel Sambuc     Class->addDecl(Invoke);
1336f4a2713aSLionel Sambuc }
1337f4a2713aSLionel Sambuc 
1338f4a2713aSLionel Sambuc /// \brief Add a lambda's conversion to block pointer.
addBlockPointerConversion(Sema & S,SourceRange IntroducerRange,CXXRecordDecl * Class,CXXMethodDecl * CallOperator)1339f4a2713aSLionel Sambuc static void addBlockPointerConversion(Sema &S,
1340f4a2713aSLionel Sambuc                                       SourceRange IntroducerRange,
1341f4a2713aSLionel Sambuc                                       CXXRecordDecl *Class,
1342f4a2713aSLionel Sambuc                                       CXXMethodDecl *CallOperator) {
1343f4a2713aSLionel Sambuc   const FunctionProtoType *Proto
1344f4a2713aSLionel Sambuc     = CallOperator->getType()->getAs<FunctionProtoType>();
1345f4a2713aSLionel Sambuc   QualType BlockPtrTy;
1346f4a2713aSLionel Sambuc   {
1347f4a2713aSLionel Sambuc     FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
1348f4a2713aSLionel Sambuc     ExtInfo.TypeQuals = 0;
1349f4a2713aSLionel Sambuc     QualType FunctionTy = S.Context.getFunctionType(
1350*0a6a1f1dSLionel Sambuc         Proto->getReturnType(), Proto->getParamTypes(), ExtInfo);
1351f4a2713aSLionel Sambuc     BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1352f4a2713aSLionel Sambuc   }
1353f4a2713aSLionel Sambuc 
1354f4a2713aSLionel Sambuc   FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
1355f4a2713aSLionel Sambuc       /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1356f4a2713aSLionel Sambuc   ExtInfo.TypeQuals = Qualifiers::Const;
1357f4a2713aSLionel Sambuc   QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
1358f4a2713aSLionel Sambuc 
1359f4a2713aSLionel Sambuc   SourceLocation Loc = IntroducerRange.getBegin();
1360f4a2713aSLionel Sambuc   DeclarationName Name
1361f4a2713aSLionel Sambuc     = S.Context.DeclarationNames.getCXXConversionFunctionName(
1362f4a2713aSLionel Sambuc         S.Context.getCanonicalType(BlockPtrTy));
1363f4a2713aSLionel Sambuc   DeclarationNameLoc NameLoc;
1364f4a2713aSLionel Sambuc   NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
1365f4a2713aSLionel Sambuc   CXXConversionDecl *Conversion
1366f4a2713aSLionel Sambuc     = CXXConversionDecl::Create(S.Context, Class, Loc,
1367f4a2713aSLionel Sambuc                                 DeclarationNameInfo(Name, Loc, NameLoc),
1368f4a2713aSLionel Sambuc                                 ConvTy,
1369f4a2713aSLionel Sambuc                                 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1370f4a2713aSLionel Sambuc                                 /*isInline=*/true, /*isExplicit=*/false,
1371f4a2713aSLionel Sambuc                                 /*isConstexpr=*/false,
1372f4a2713aSLionel Sambuc                                 CallOperator->getBody()->getLocEnd());
1373f4a2713aSLionel Sambuc   Conversion->setAccess(AS_public);
1374f4a2713aSLionel Sambuc   Conversion->setImplicit(true);
1375f4a2713aSLionel Sambuc   Class->addDecl(Conversion);
1376f4a2713aSLionel Sambuc }
1377f4a2713aSLionel Sambuc 
ActOnLambdaExpr(SourceLocation StartLoc,Stmt * Body,Scope * CurScope,bool IsInstantiation)1378f4a2713aSLionel Sambuc ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
1379f4a2713aSLionel Sambuc                                  Scope *CurScope,
1380f4a2713aSLionel Sambuc                                  bool IsInstantiation) {
1381f4a2713aSLionel Sambuc   // Collect information from the lambda scope.
1382*0a6a1f1dSLionel Sambuc   SmallVector<LambdaCapture, 4> Captures;
1383f4a2713aSLionel Sambuc   SmallVector<Expr *, 4> CaptureInits;
1384f4a2713aSLionel Sambuc   LambdaCaptureDefault CaptureDefault;
1385f4a2713aSLionel Sambuc   SourceLocation CaptureDefaultLoc;
1386f4a2713aSLionel Sambuc   CXXRecordDecl *Class;
1387f4a2713aSLionel Sambuc   CXXMethodDecl *CallOperator;
1388f4a2713aSLionel Sambuc   SourceRange IntroducerRange;
1389f4a2713aSLionel Sambuc   bool ExplicitParams;
1390f4a2713aSLionel Sambuc   bool ExplicitResultType;
1391f4a2713aSLionel Sambuc   bool LambdaExprNeedsCleanups;
1392f4a2713aSLionel Sambuc   bool ContainsUnexpandedParameterPack;
1393f4a2713aSLionel Sambuc   SmallVector<VarDecl *, 4> ArrayIndexVars;
1394f4a2713aSLionel Sambuc   SmallVector<unsigned, 4> ArrayIndexStarts;
1395f4a2713aSLionel Sambuc   {
1396f4a2713aSLionel Sambuc     LambdaScopeInfo *LSI = getCurLambda();
1397f4a2713aSLionel Sambuc     CallOperator = LSI->CallOperator;
1398f4a2713aSLionel Sambuc     Class = LSI->Lambda;
1399f4a2713aSLionel Sambuc     IntroducerRange = LSI->IntroducerRange;
1400f4a2713aSLionel Sambuc     ExplicitParams = LSI->ExplicitParams;
1401f4a2713aSLionel Sambuc     ExplicitResultType = !LSI->HasImplicitReturnType;
1402f4a2713aSLionel Sambuc     LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
1403f4a2713aSLionel Sambuc     ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
1404f4a2713aSLionel Sambuc     ArrayIndexVars.swap(LSI->ArrayIndexVars);
1405f4a2713aSLionel Sambuc     ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
1406f4a2713aSLionel Sambuc 
1407f4a2713aSLionel Sambuc     // Translate captures.
1408f4a2713aSLionel Sambuc     for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1409f4a2713aSLionel Sambuc       LambdaScopeInfo::Capture From = LSI->Captures[I];
1410f4a2713aSLionel Sambuc       assert(!From.isBlockCapture() && "Cannot capture __block variables");
1411f4a2713aSLionel Sambuc       bool IsImplicit = I >= LSI->NumExplicitCaptures;
1412f4a2713aSLionel Sambuc 
1413f4a2713aSLionel Sambuc       // Handle 'this' capture.
1414f4a2713aSLionel Sambuc       if (From.isThisCapture()) {
1415*0a6a1f1dSLionel Sambuc         Captures.push_back(
1416*0a6a1f1dSLionel Sambuc             LambdaCapture(From.getLocation(), IsImplicit, LCK_This));
1417f4a2713aSLionel Sambuc         CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
1418f4a2713aSLionel Sambuc                                                          getCurrentThisType(),
1419f4a2713aSLionel Sambuc                                                          /*isImplicit=*/true));
1420f4a2713aSLionel Sambuc         continue;
1421f4a2713aSLionel Sambuc       }
1422*0a6a1f1dSLionel Sambuc       if (From.isVLATypeCapture()) {
1423*0a6a1f1dSLionel Sambuc         Captures.push_back(
1424*0a6a1f1dSLionel Sambuc             LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType));
1425*0a6a1f1dSLionel Sambuc         CaptureInits.push_back(nullptr);
1426*0a6a1f1dSLionel Sambuc         continue;
1427*0a6a1f1dSLionel Sambuc       }
1428f4a2713aSLionel Sambuc 
1429f4a2713aSLionel Sambuc       VarDecl *Var = From.getVariable();
1430f4a2713aSLionel Sambuc       LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
1431*0a6a1f1dSLionel Sambuc       Captures.push_back(LambdaCapture(From.getLocation(), IsImplicit, Kind,
1432*0a6a1f1dSLionel Sambuc                                        Var, From.getEllipsisLoc()));
1433f4a2713aSLionel Sambuc       CaptureInits.push_back(From.getInitExpr());
1434f4a2713aSLionel Sambuc     }
1435f4a2713aSLionel Sambuc 
1436f4a2713aSLionel Sambuc     switch (LSI->ImpCaptureStyle) {
1437f4a2713aSLionel Sambuc     case CapturingScopeInfo::ImpCap_None:
1438f4a2713aSLionel Sambuc       CaptureDefault = LCD_None;
1439f4a2713aSLionel Sambuc       break;
1440f4a2713aSLionel Sambuc 
1441f4a2713aSLionel Sambuc     case CapturingScopeInfo::ImpCap_LambdaByval:
1442f4a2713aSLionel Sambuc       CaptureDefault = LCD_ByCopy;
1443f4a2713aSLionel Sambuc       break;
1444f4a2713aSLionel Sambuc 
1445f4a2713aSLionel Sambuc     case CapturingScopeInfo::ImpCap_CapturedRegion:
1446f4a2713aSLionel Sambuc     case CapturingScopeInfo::ImpCap_LambdaByref:
1447f4a2713aSLionel Sambuc       CaptureDefault = LCD_ByRef;
1448f4a2713aSLionel Sambuc       break;
1449f4a2713aSLionel Sambuc 
1450f4a2713aSLionel Sambuc     case CapturingScopeInfo::ImpCap_Block:
1451f4a2713aSLionel Sambuc       llvm_unreachable("block capture in lambda");
1452f4a2713aSLionel Sambuc       break;
1453f4a2713aSLionel Sambuc     }
1454f4a2713aSLionel Sambuc     CaptureDefaultLoc = LSI->CaptureDefaultLoc;
1455f4a2713aSLionel Sambuc 
1456f4a2713aSLionel Sambuc     // C++11 [expr.prim.lambda]p4:
1457f4a2713aSLionel Sambuc     //   If a lambda-expression does not include a
1458f4a2713aSLionel Sambuc     //   trailing-return-type, it is as if the trailing-return-type
1459f4a2713aSLionel Sambuc     //   denotes the following type:
1460f4a2713aSLionel Sambuc     //
1461f4a2713aSLionel Sambuc     // Skip for C++1y return type deduction semantics which uses
1462f4a2713aSLionel Sambuc     // different machinery.
1463f4a2713aSLionel Sambuc     // FIXME: Refactor and Merge the return type deduction machinery.
1464f4a2713aSLionel Sambuc     // FIXME: Assumes current resolution to core issue 975.
1465*0a6a1f1dSLionel Sambuc     if (LSI->HasImplicitReturnType && !getLangOpts().CPlusPlus14) {
1466f4a2713aSLionel Sambuc       deduceClosureReturnType(*LSI);
1467f4a2713aSLionel Sambuc 
1468f4a2713aSLionel Sambuc       //   - if there are no return statements in the
1469f4a2713aSLionel Sambuc       //     compound-statement, or all return statements return
1470f4a2713aSLionel Sambuc       //     either an expression of type void or no expression or
1471f4a2713aSLionel Sambuc       //     braced-init-list, the type void;
1472f4a2713aSLionel Sambuc       if (LSI->ReturnType.isNull()) {
1473f4a2713aSLionel Sambuc         LSI->ReturnType = Context.VoidTy;
1474f4a2713aSLionel Sambuc       }
1475f4a2713aSLionel Sambuc 
1476f4a2713aSLionel Sambuc       // Create a function type with the inferred return type.
1477f4a2713aSLionel Sambuc       const FunctionProtoType *Proto
1478f4a2713aSLionel Sambuc         = CallOperator->getType()->getAs<FunctionProtoType>();
1479f4a2713aSLionel Sambuc       QualType FunctionTy = Context.getFunctionType(
1480*0a6a1f1dSLionel Sambuc           LSI->ReturnType, Proto->getParamTypes(), Proto->getExtProtoInfo());
1481f4a2713aSLionel Sambuc       CallOperator->setType(FunctionTy);
1482f4a2713aSLionel Sambuc     }
1483f4a2713aSLionel Sambuc     // C++ [expr.prim.lambda]p7:
1484f4a2713aSLionel Sambuc     //   The lambda-expression's compound-statement yields the
1485f4a2713aSLionel Sambuc     //   function-body (8.4) of the function call operator [...].
1486f4a2713aSLionel Sambuc     ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
1487f4a2713aSLionel Sambuc     CallOperator->setLexicalDeclContext(Class);
1488f4a2713aSLionel Sambuc     Decl *TemplateOrNonTemplateCallOperatorDecl =
1489f4a2713aSLionel Sambuc         CallOperator->getDescribedFunctionTemplate()
1490f4a2713aSLionel Sambuc         ? CallOperator->getDescribedFunctionTemplate()
1491f4a2713aSLionel Sambuc         : cast<Decl>(CallOperator);
1492f4a2713aSLionel Sambuc 
1493f4a2713aSLionel Sambuc     TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1494f4a2713aSLionel Sambuc     Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
1495f4a2713aSLionel Sambuc 
1496f4a2713aSLionel Sambuc     PopExpressionEvaluationContext();
1497f4a2713aSLionel Sambuc 
1498f4a2713aSLionel Sambuc     // C++11 [expr.prim.lambda]p6:
1499f4a2713aSLionel Sambuc     //   The closure type for a lambda-expression with no lambda-capture
1500f4a2713aSLionel Sambuc     //   has a public non-virtual non-explicit const conversion function
1501f4a2713aSLionel Sambuc     //   to pointer to function having the same parameter and return
1502f4a2713aSLionel Sambuc     //   types as the closure type's function call operator.
1503f4a2713aSLionel Sambuc     if (Captures.empty() && CaptureDefault == LCD_None)
1504f4a2713aSLionel Sambuc       addFunctionPointerConversion(*this, IntroducerRange, Class,
1505f4a2713aSLionel Sambuc                                    CallOperator);
1506f4a2713aSLionel Sambuc 
1507f4a2713aSLionel Sambuc     // Objective-C++:
1508f4a2713aSLionel Sambuc     //   The closure type for a lambda-expression has a public non-virtual
1509f4a2713aSLionel Sambuc     //   non-explicit const conversion function to a block pointer having the
1510f4a2713aSLionel Sambuc     //   same parameter and return types as the closure type's function call
1511f4a2713aSLionel Sambuc     //   operator.
1512f4a2713aSLionel Sambuc     // FIXME: Fix generic lambda to block conversions.
1513f4a2713aSLionel Sambuc     if (getLangOpts().Blocks && getLangOpts().ObjC1 &&
1514f4a2713aSLionel Sambuc                                               !Class->isGenericLambda())
1515f4a2713aSLionel Sambuc       addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1516f4a2713aSLionel Sambuc 
1517f4a2713aSLionel Sambuc     // Finalize the lambda class.
1518*0a6a1f1dSLionel Sambuc     SmallVector<Decl*, 4> Fields(Class->fields());
1519*0a6a1f1dSLionel Sambuc     ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1520*0a6a1f1dSLionel Sambuc                 SourceLocation(), nullptr);
1521f4a2713aSLionel Sambuc     CheckCompletedCXXClass(Class);
1522f4a2713aSLionel Sambuc   }
1523f4a2713aSLionel Sambuc 
1524f4a2713aSLionel Sambuc   if (LambdaExprNeedsCleanups)
1525f4a2713aSLionel Sambuc     ExprNeedsCleanups = true;
1526f4a2713aSLionel Sambuc 
1527f4a2713aSLionel Sambuc   LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
1528f4a2713aSLionel Sambuc                                           CaptureDefault, CaptureDefaultLoc,
1529f4a2713aSLionel Sambuc                                           Captures,
1530f4a2713aSLionel Sambuc                                           ExplicitParams, ExplicitResultType,
1531f4a2713aSLionel Sambuc                                           CaptureInits, ArrayIndexVars,
1532f4a2713aSLionel Sambuc                                           ArrayIndexStarts, Body->getLocEnd(),
1533f4a2713aSLionel Sambuc                                           ContainsUnexpandedParameterPack);
1534f4a2713aSLionel Sambuc 
1535f4a2713aSLionel Sambuc   if (!CurContext->isDependentContext()) {
1536f4a2713aSLionel Sambuc     switch (ExprEvalContexts.back().Context) {
1537f4a2713aSLionel Sambuc     // C++11 [expr.prim.lambda]p2:
1538f4a2713aSLionel Sambuc     //   A lambda-expression shall not appear in an unevaluated operand
1539f4a2713aSLionel Sambuc     //   (Clause 5).
1540f4a2713aSLionel Sambuc     case Unevaluated:
1541f4a2713aSLionel Sambuc     case UnevaluatedAbstract:
1542f4a2713aSLionel Sambuc     // C++1y [expr.const]p2:
1543f4a2713aSLionel Sambuc     //   A conditional-expression e is a core constant expression unless the
1544f4a2713aSLionel Sambuc     //   evaluation of e, following the rules of the abstract machine, would
1545f4a2713aSLionel Sambuc     //   evaluate [...] a lambda-expression.
1546f4a2713aSLionel Sambuc     //
1547f4a2713aSLionel Sambuc     // This is technically incorrect, there are some constant evaluated contexts
1548f4a2713aSLionel Sambuc     // where this should be allowed.  We should probably fix this when DR1607 is
1549f4a2713aSLionel Sambuc     // ratified, it lays out the exact set of conditions where we shouldn't
1550f4a2713aSLionel Sambuc     // allow a lambda-expression.
1551f4a2713aSLionel Sambuc     case ConstantEvaluated:
1552f4a2713aSLionel Sambuc       // We don't actually diagnose this case immediately, because we
1553f4a2713aSLionel Sambuc       // could be within a context where we might find out later that
1554f4a2713aSLionel Sambuc       // the expression is potentially evaluated (e.g., for typeid).
1555f4a2713aSLionel Sambuc       ExprEvalContexts.back().Lambdas.push_back(Lambda);
1556f4a2713aSLionel Sambuc       break;
1557f4a2713aSLionel Sambuc 
1558f4a2713aSLionel Sambuc     case PotentiallyEvaluated:
1559f4a2713aSLionel Sambuc     case PotentiallyEvaluatedIfUsed:
1560f4a2713aSLionel Sambuc       break;
1561f4a2713aSLionel Sambuc     }
1562f4a2713aSLionel Sambuc   }
1563f4a2713aSLionel Sambuc 
1564f4a2713aSLionel Sambuc   return MaybeBindToTemporary(Lambda);
1565f4a2713aSLionel Sambuc }
1566f4a2713aSLionel Sambuc 
BuildBlockForLambdaConversion(SourceLocation CurrentLocation,SourceLocation ConvLocation,CXXConversionDecl * Conv,Expr * Src)1567f4a2713aSLionel Sambuc ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1568f4a2713aSLionel Sambuc                                                SourceLocation ConvLocation,
1569f4a2713aSLionel Sambuc                                                CXXConversionDecl *Conv,
1570f4a2713aSLionel Sambuc                                                Expr *Src) {
1571f4a2713aSLionel Sambuc   // Make sure that the lambda call operator is marked used.
1572f4a2713aSLionel Sambuc   CXXRecordDecl *Lambda = Conv->getParent();
1573f4a2713aSLionel Sambuc   CXXMethodDecl *CallOperator
1574f4a2713aSLionel Sambuc     = cast<CXXMethodDecl>(
1575f4a2713aSLionel Sambuc         Lambda->lookup(
1576f4a2713aSLionel Sambuc           Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
1577f4a2713aSLionel Sambuc   CallOperator->setReferenced();
1578f4a2713aSLionel Sambuc   CallOperator->markUsed(Context);
1579f4a2713aSLionel Sambuc 
1580f4a2713aSLionel Sambuc   ExprResult Init = PerformCopyInitialization(
1581f4a2713aSLionel Sambuc                       InitializedEntity::InitializeBlock(ConvLocation,
1582f4a2713aSLionel Sambuc                                                          Src->getType(),
1583f4a2713aSLionel Sambuc                                                          /*NRVO=*/false),
1584f4a2713aSLionel Sambuc                       CurrentLocation, Src);
1585f4a2713aSLionel Sambuc   if (!Init.isInvalid())
1586*0a6a1f1dSLionel Sambuc     Init = ActOnFinishFullExpr(Init.get());
1587f4a2713aSLionel Sambuc 
1588f4a2713aSLionel Sambuc   if (Init.isInvalid())
1589f4a2713aSLionel Sambuc     return ExprError();
1590f4a2713aSLionel Sambuc 
1591f4a2713aSLionel Sambuc   // Create the new block to be returned.
1592f4a2713aSLionel Sambuc   BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1593f4a2713aSLionel Sambuc 
1594f4a2713aSLionel Sambuc   // Set the type information.
1595f4a2713aSLionel Sambuc   Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1596f4a2713aSLionel Sambuc   Block->setIsVariadic(CallOperator->isVariadic());
1597f4a2713aSLionel Sambuc   Block->setBlockMissingReturnType(false);
1598f4a2713aSLionel Sambuc 
1599f4a2713aSLionel Sambuc   // Add parameters.
1600f4a2713aSLionel Sambuc   SmallVector<ParmVarDecl *, 4> BlockParams;
1601f4a2713aSLionel Sambuc   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1602f4a2713aSLionel Sambuc     ParmVarDecl *From = CallOperator->getParamDecl(I);
1603f4a2713aSLionel Sambuc     BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1604f4a2713aSLionel Sambuc                                               From->getLocStart(),
1605f4a2713aSLionel Sambuc                                               From->getLocation(),
1606f4a2713aSLionel Sambuc                                               From->getIdentifier(),
1607f4a2713aSLionel Sambuc                                               From->getType(),
1608f4a2713aSLionel Sambuc                                               From->getTypeSourceInfo(),
1609f4a2713aSLionel Sambuc                                               From->getStorageClass(),
1610*0a6a1f1dSLionel Sambuc                                               /*DefaultArg=*/nullptr));
1611f4a2713aSLionel Sambuc   }
1612f4a2713aSLionel Sambuc   Block->setParams(BlockParams);
1613f4a2713aSLionel Sambuc 
1614f4a2713aSLionel Sambuc   Block->setIsConversionFromLambda(true);
1615f4a2713aSLionel Sambuc 
1616f4a2713aSLionel Sambuc   // Add capture. The capture uses a fake variable, which doesn't correspond
1617f4a2713aSLionel Sambuc   // to any actual memory location. However, the initializer copy-initializes
1618f4a2713aSLionel Sambuc   // the lambda object.
1619f4a2713aSLionel Sambuc   TypeSourceInfo *CapVarTSI =
1620f4a2713aSLionel Sambuc       Context.getTrivialTypeSourceInfo(Src->getType());
1621f4a2713aSLionel Sambuc   VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1622*0a6a1f1dSLionel Sambuc                                     ConvLocation, nullptr,
1623f4a2713aSLionel Sambuc                                     Src->getType(), CapVarTSI,
1624f4a2713aSLionel Sambuc                                     SC_None);
1625f4a2713aSLionel Sambuc   BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1626*0a6a1f1dSLionel Sambuc                              /*Nested=*/false, /*Copy=*/Init.get());
1627f4a2713aSLionel Sambuc   Block->setCaptures(Context, &Capture, &Capture + 1,
1628f4a2713aSLionel Sambuc                      /*CapturesCXXThis=*/false);
1629f4a2713aSLionel Sambuc 
1630f4a2713aSLionel Sambuc   // Add a fake function body to the block. IR generation is responsible
1631f4a2713aSLionel Sambuc   // for filling in the actual body, which cannot be expressed as an AST.
1632f4a2713aSLionel Sambuc   Block->setBody(new (Context) CompoundStmt(ConvLocation));
1633f4a2713aSLionel Sambuc 
1634f4a2713aSLionel Sambuc   // Create the block literal expression.
1635f4a2713aSLionel Sambuc   Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1636f4a2713aSLionel Sambuc   ExprCleanupObjects.push_back(Block);
1637f4a2713aSLionel Sambuc   ExprNeedsCleanups = true;
1638f4a2713aSLionel Sambuc 
1639f4a2713aSLionel Sambuc   return BuildBlock;
1640f4a2713aSLionel Sambuc }
1641