1*67e74705SXin Li //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
2*67e74705SXin Li //
3*67e74705SXin Li // The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // This contains code to emit Stmt nodes as LLVM code.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li
14*67e74705SXin Li #include "CodeGenFunction.h"
15*67e74705SXin Li #include "CGDebugInfo.h"
16*67e74705SXin Li #include "CodeGenModule.h"
17*67e74705SXin Li #include "TargetInfo.h"
18*67e74705SXin Li #include "clang/AST/StmtVisitor.h"
19*67e74705SXin Li #include "clang/Basic/Builtins.h"
20*67e74705SXin Li #include "clang/Basic/PrettyStackTrace.h"
21*67e74705SXin Li #include "clang/Basic/TargetInfo.h"
22*67e74705SXin Li #include "clang/Sema/LoopHint.h"
23*67e74705SXin Li #include "clang/Sema/SemaDiagnostic.h"
24*67e74705SXin Li #include "llvm/ADT/StringExtras.h"
25*67e74705SXin Li #include "llvm/IR/CallSite.h"
26*67e74705SXin Li #include "llvm/IR/DataLayout.h"
27*67e74705SXin Li #include "llvm/IR/InlineAsm.h"
28*67e74705SXin Li #include "llvm/IR/Intrinsics.h"
29*67e74705SXin Li #include "llvm/IR/MDBuilder.h"
30*67e74705SXin Li
31*67e74705SXin Li using namespace clang;
32*67e74705SXin Li using namespace CodeGen;
33*67e74705SXin Li
34*67e74705SXin Li //===----------------------------------------------------------------------===//
35*67e74705SXin Li // Statement Emission
36*67e74705SXin Li //===----------------------------------------------------------------------===//
37*67e74705SXin Li
EmitStopPoint(const Stmt * S)38*67e74705SXin Li void CodeGenFunction::EmitStopPoint(const Stmt *S) {
39*67e74705SXin Li if (CGDebugInfo *DI = getDebugInfo()) {
40*67e74705SXin Li SourceLocation Loc;
41*67e74705SXin Li Loc = S->getLocStart();
42*67e74705SXin Li DI->EmitLocation(Builder, Loc);
43*67e74705SXin Li
44*67e74705SXin Li LastStopPoint = Loc;
45*67e74705SXin Li }
46*67e74705SXin Li }
47*67e74705SXin Li
EmitStmt(const Stmt * S)48*67e74705SXin Li void CodeGenFunction::EmitStmt(const Stmt *S) {
49*67e74705SXin Li assert(S && "Null statement?");
50*67e74705SXin Li PGO.setCurrentStmt(S);
51*67e74705SXin Li
52*67e74705SXin Li // These statements have their own debug info handling.
53*67e74705SXin Li if (EmitSimpleStmt(S))
54*67e74705SXin Li return;
55*67e74705SXin Li
56*67e74705SXin Li // Check if we are generating unreachable code.
57*67e74705SXin Li if (!HaveInsertPoint()) {
58*67e74705SXin Li // If so, and the statement doesn't contain a label, then we do not need to
59*67e74705SXin Li // generate actual code. This is safe because (1) the current point is
60*67e74705SXin Li // unreachable, so we don't need to execute the code, and (2) we've already
61*67e74705SXin Li // handled the statements which update internal data structures (like the
62*67e74705SXin Li // local variable map) which could be used by subsequent statements.
63*67e74705SXin Li if (!ContainsLabel(S)) {
64*67e74705SXin Li // Verify that any decl statements were handled as simple, they may be in
65*67e74705SXin Li // scope of subsequent reachable statements.
66*67e74705SXin Li assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
67*67e74705SXin Li return;
68*67e74705SXin Li }
69*67e74705SXin Li
70*67e74705SXin Li // Otherwise, make a new block to hold the code.
71*67e74705SXin Li EnsureInsertPoint();
72*67e74705SXin Li }
73*67e74705SXin Li
74*67e74705SXin Li // Generate a stoppoint if we are emitting debug info.
75*67e74705SXin Li EmitStopPoint(S);
76*67e74705SXin Li
77*67e74705SXin Li switch (S->getStmtClass()) {
78*67e74705SXin Li case Stmt::NoStmtClass:
79*67e74705SXin Li case Stmt::CXXCatchStmtClass:
80*67e74705SXin Li case Stmt::SEHExceptStmtClass:
81*67e74705SXin Li case Stmt::SEHFinallyStmtClass:
82*67e74705SXin Li case Stmt::MSDependentExistsStmtClass:
83*67e74705SXin Li llvm_unreachable("invalid statement class to emit generically");
84*67e74705SXin Li case Stmt::NullStmtClass:
85*67e74705SXin Li case Stmt::CompoundStmtClass:
86*67e74705SXin Li case Stmt::DeclStmtClass:
87*67e74705SXin Li case Stmt::LabelStmtClass:
88*67e74705SXin Li case Stmt::AttributedStmtClass:
89*67e74705SXin Li case Stmt::GotoStmtClass:
90*67e74705SXin Li case Stmt::BreakStmtClass:
91*67e74705SXin Li case Stmt::ContinueStmtClass:
92*67e74705SXin Li case Stmt::DefaultStmtClass:
93*67e74705SXin Li case Stmt::CaseStmtClass:
94*67e74705SXin Li case Stmt::SEHLeaveStmtClass:
95*67e74705SXin Li llvm_unreachable("should have emitted these statements as simple");
96*67e74705SXin Li
97*67e74705SXin Li #define STMT(Type, Base)
98*67e74705SXin Li #define ABSTRACT_STMT(Op)
99*67e74705SXin Li #define EXPR(Type, Base) \
100*67e74705SXin Li case Stmt::Type##Class:
101*67e74705SXin Li #include "clang/AST/StmtNodes.inc"
102*67e74705SXin Li {
103*67e74705SXin Li // Remember the block we came in on.
104*67e74705SXin Li llvm::BasicBlock *incoming = Builder.GetInsertBlock();
105*67e74705SXin Li assert(incoming && "expression emission must have an insertion point");
106*67e74705SXin Li
107*67e74705SXin Li EmitIgnoredExpr(cast<Expr>(S));
108*67e74705SXin Li
109*67e74705SXin Li llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
110*67e74705SXin Li assert(outgoing && "expression emission cleared block!");
111*67e74705SXin Li
112*67e74705SXin Li // The expression emitters assume (reasonably!) that the insertion
113*67e74705SXin Li // point is always set. To maintain that, the call-emission code
114*67e74705SXin Li // for noreturn functions has to enter a new block with no
115*67e74705SXin Li // predecessors. We want to kill that block and mark the current
116*67e74705SXin Li // insertion point unreachable in the common case of a call like
117*67e74705SXin Li // "exit();". Since expression emission doesn't otherwise create
118*67e74705SXin Li // blocks with no predecessors, we can just test for that.
119*67e74705SXin Li // However, we must be careful not to do this to our incoming
120*67e74705SXin Li // block, because *statement* emission does sometimes create
121*67e74705SXin Li // reachable blocks which will have no predecessors until later in
122*67e74705SXin Li // the function. This occurs with, e.g., labels that are not
123*67e74705SXin Li // reachable by fallthrough.
124*67e74705SXin Li if (incoming != outgoing && outgoing->use_empty()) {
125*67e74705SXin Li outgoing->eraseFromParent();
126*67e74705SXin Li Builder.ClearInsertionPoint();
127*67e74705SXin Li }
128*67e74705SXin Li break;
129*67e74705SXin Li }
130*67e74705SXin Li
131*67e74705SXin Li case Stmt::IndirectGotoStmtClass:
132*67e74705SXin Li EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
133*67e74705SXin Li
134*67e74705SXin Li case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
135*67e74705SXin Li case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
136*67e74705SXin Li case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
137*67e74705SXin Li case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
138*67e74705SXin Li
139*67e74705SXin Li case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
140*67e74705SXin Li
141*67e74705SXin Li case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
142*67e74705SXin Li case Stmt::GCCAsmStmtClass: // Intentional fall-through.
143*67e74705SXin Li case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
144*67e74705SXin Li case Stmt::CoroutineBodyStmtClass:
145*67e74705SXin Li case Stmt::CoreturnStmtClass:
146*67e74705SXin Li CGM.ErrorUnsupported(S, "coroutine");
147*67e74705SXin Li break;
148*67e74705SXin Li case Stmt::CapturedStmtClass: {
149*67e74705SXin Li const CapturedStmt *CS = cast<CapturedStmt>(S);
150*67e74705SXin Li EmitCapturedStmt(*CS, CS->getCapturedRegionKind());
151*67e74705SXin Li }
152*67e74705SXin Li break;
153*67e74705SXin Li case Stmt::ObjCAtTryStmtClass:
154*67e74705SXin Li EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
155*67e74705SXin Li break;
156*67e74705SXin Li case Stmt::ObjCAtCatchStmtClass:
157*67e74705SXin Li llvm_unreachable(
158*67e74705SXin Li "@catch statements should be handled by EmitObjCAtTryStmt");
159*67e74705SXin Li case Stmt::ObjCAtFinallyStmtClass:
160*67e74705SXin Li llvm_unreachable(
161*67e74705SXin Li "@finally statements should be handled by EmitObjCAtTryStmt");
162*67e74705SXin Li case Stmt::ObjCAtThrowStmtClass:
163*67e74705SXin Li EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
164*67e74705SXin Li break;
165*67e74705SXin Li case Stmt::ObjCAtSynchronizedStmtClass:
166*67e74705SXin Li EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
167*67e74705SXin Li break;
168*67e74705SXin Li case Stmt::ObjCForCollectionStmtClass:
169*67e74705SXin Li EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
170*67e74705SXin Li break;
171*67e74705SXin Li case Stmt::ObjCAutoreleasePoolStmtClass:
172*67e74705SXin Li EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
173*67e74705SXin Li break;
174*67e74705SXin Li
175*67e74705SXin Li case Stmt::CXXTryStmtClass:
176*67e74705SXin Li EmitCXXTryStmt(cast<CXXTryStmt>(*S));
177*67e74705SXin Li break;
178*67e74705SXin Li case Stmt::CXXForRangeStmtClass:
179*67e74705SXin Li EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
180*67e74705SXin Li break;
181*67e74705SXin Li case Stmt::SEHTryStmtClass:
182*67e74705SXin Li EmitSEHTryStmt(cast<SEHTryStmt>(*S));
183*67e74705SXin Li break;
184*67e74705SXin Li case Stmt::OMPParallelDirectiveClass:
185*67e74705SXin Li EmitOMPParallelDirective(cast<OMPParallelDirective>(*S));
186*67e74705SXin Li break;
187*67e74705SXin Li case Stmt::OMPSimdDirectiveClass:
188*67e74705SXin Li EmitOMPSimdDirective(cast<OMPSimdDirective>(*S));
189*67e74705SXin Li break;
190*67e74705SXin Li case Stmt::OMPForDirectiveClass:
191*67e74705SXin Li EmitOMPForDirective(cast<OMPForDirective>(*S));
192*67e74705SXin Li break;
193*67e74705SXin Li case Stmt::OMPForSimdDirectiveClass:
194*67e74705SXin Li EmitOMPForSimdDirective(cast<OMPForSimdDirective>(*S));
195*67e74705SXin Li break;
196*67e74705SXin Li case Stmt::OMPSectionsDirectiveClass:
197*67e74705SXin Li EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S));
198*67e74705SXin Li break;
199*67e74705SXin Li case Stmt::OMPSectionDirectiveClass:
200*67e74705SXin Li EmitOMPSectionDirective(cast<OMPSectionDirective>(*S));
201*67e74705SXin Li break;
202*67e74705SXin Li case Stmt::OMPSingleDirectiveClass:
203*67e74705SXin Li EmitOMPSingleDirective(cast<OMPSingleDirective>(*S));
204*67e74705SXin Li break;
205*67e74705SXin Li case Stmt::OMPMasterDirectiveClass:
206*67e74705SXin Li EmitOMPMasterDirective(cast<OMPMasterDirective>(*S));
207*67e74705SXin Li break;
208*67e74705SXin Li case Stmt::OMPCriticalDirectiveClass:
209*67e74705SXin Li EmitOMPCriticalDirective(cast<OMPCriticalDirective>(*S));
210*67e74705SXin Li break;
211*67e74705SXin Li case Stmt::OMPParallelForDirectiveClass:
212*67e74705SXin Li EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S));
213*67e74705SXin Li break;
214*67e74705SXin Li case Stmt::OMPParallelForSimdDirectiveClass:
215*67e74705SXin Li EmitOMPParallelForSimdDirective(cast<OMPParallelForSimdDirective>(*S));
216*67e74705SXin Li break;
217*67e74705SXin Li case Stmt::OMPParallelSectionsDirectiveClass:
218*67e74705SXin Li EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S));
219*67e74705SXin Li break;
220*67e74705SXin Li case Stmt::OMPTaskDirectiveClass:
221*67e74705SXin Li EmitOMPTaskDirective(cast<OMPTaskDirective>(*S));
222*67e74705SXin Li break;
223*67e74705SXin Li case Stmt::OMPTaskyieldDirectiveClass:
224*67e74705SXin Li EmitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S));
225*67e74705SXin Li break;
226*67e74705SXin Li case Stmt::OMPBarrierDirectiveClass:
227*67e74705SXin Li EmitOMPBarrierDirective(cast<OMPBarrierDirective>(*S));
228*67e74705SXin Li break;
229*67e74705SXin Li case Stmt::OMPTaskwaitDirectiveClass:
230*67e74705SXin Li EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S));
231*67e74705SXin Li break;
232*67e74705SXin Li case Stmt::OMPTaskgroupDirectiveClass:
233*67e74705SXin Li EmitOMPTaskgroupDirective(cast<OMPTaskgroupDirective>(*S));
234*67e74705SXin Li break;
235*67e74705SXin Li case Stmt::OMPFlushDirectiveClass:
236*67e74705SXin Li EmitOMPFlushDirective(cast<OMPFlushDirective>(*S));
237*67e74705SXin Li break;
238*67e74705SXin Li case Stmt::OMPOrderedDirectiveClass:
239*67e74705SXin Li EmitOMPOrderedDirective(cast<OMPOrderedDirective>(*S));
240*67e74705SXin Li break;
241*67e74705SXin Li case Stmt::OMPAtomicDirectiveClass:
242*67e74705SXin Li EmitOMPAtomicDirective(cast<OMPAtomicDirective>(*S));
243*67e74705SXin Li break;
244*67e74705SXin Li case Stmt::OMPTargetDirectiveClass:
245*67e74705SXin Li EmitOMPTargetDirective(cast<OMPTargetDirective>(*S));
246*67e74705SXin Li break;
247*67e74705SXin Li case Stmt::OMPTeamsDirectiveClass:
248*67e74705SXin Li EmitOMPTeamsDirective(cast<OMPTeamsDirective>(*S));
249*67e74705SXin Li break;
250*67e74705SXin Li case Stmt::OMPCancellationPointDirectiveClass:
251*67e74705SXin Li EmitOMPCancellationPointDirective(cast<OMPCancellationPointDirective>(*S));
252*67e74705SXin Li break;
253*67e74705SXin Li case Stmt::OMPCancelDirectiveClass:
254*67e74705SXin Li EmitOMPCancelDirective(cast<OMPCancelDirective>(*S));
255*67e74705SXin Li break;
256*67e74705SXin Li case Stmt::OMPTargetDataDirectiveClass:
257*67e74705SXin Li EmitOMPTargetDataDirective(cast<OMPTargetDataDirective>(*S));
258*67e74705SXin Li break;
259*67e74705SXin Li case Stmt::OMPTargetEnterDataDirectiveClass:
260*67e74705SXin Li EmitOMPTargetEnterDataDirective(cast<OMPTargetEnterDataDirective>(*S));
261*67e74705SXin Li break;
262*67e74705SXin Li case Stmt::OMPTargetExitDataDirectiveClass:
263*67e74705SXin Li EmitOMPTargetExitDataDirective(cast<OMPTargetExitDataDirective>(*S));
264*67e74705SXin Li break;
265*67e74705SXin Li case Stmt::OMPTargetParallelDirectiveClass:
266*67e74705SXin Li EmitOMPTargetParallelDirective(cast<OMPTargetParallelDirective>(*S));
267*67e74705SXin Li break;
268*67e74705SXin Li case Stmt::OMPTargetParallelForDirectiveClass:
269*67e74705SXin Li EmitOMPTargetParallelForDirective(cast<OMPTargetParallelForDirective>(*S));
270*67e74705SXin Li break;
271*67e74705SXin Li case Stmt::OMPTaskLoopDirectiveClass:
272*67e74705SXin Li EmitOMPTaskLoopDirective(cast<OMPTaskLoopDirective>(*S));
273*67e74705SXin Li break;
274*67e74705SXin Li case Stmt::OMPTaskLoopSimdDirectiveClass:
275*67e74705SXin Li EmitOMPTaskLoopSimdDirective(cast<OMPTaskLoopSimdDirective>(*S));
276*67e74705SXin Li break;
277*67e74705SXin Li case Stmt::OMPDistributeDirectiveClass:
278*67e74705SXin Li EmitOMPDistributeDirective(cast<OMPDistributeDirective>(*S));
279*67e74705SXin Li break;
280*67e74705SXin Li case Stmt::OMPTargetUpdateDirectiveClass:
281*67e74705SXin Li EmitOMPTargetUpdateDirective(cast<OMPTargetUpdateDirective>(*S));
282*67e74705SXin Li break;
283*67e74705SXin Li case Stmt::OMPDistributeParallelForDirectiveClass:
284*67e74705SXin Li EmitOMPDistributeParallelForDirective(
285*67e74705SXin Li cast<OMPDistributeParallelForDirective>(*S));
286*67e74705SXin Li break;
287*67e74705SXin Li case Stmt::OMPDistributeParallelForSimdDirectiveClass:
288*67e74705SXin Li EmitOMPDistributeParallelForSimdDirective(
289*67e74705SXin Li cast<OMPDistributeParallelForSimdDirective>(*S));
290*67e74705SXin Li break;
291*67e74705SXin Li case Stmt::OMPDistributeSimdDirectiveClass:
292*67e74705SXin Li EmitOMPDistributeSimdDirective(cast<OMPDistributeSimdDirective>(*S));
293*67e74705SXin Li break;
294*67e74705SXin Li case Stmt::OMPTargetParallelForSimdDirectiveClass:
295*67e74705SXin Li EmitOMPTargetParallelForSimdDirective(
296*67e74705SXin Li cast<OMPTargetParallelForSimdDirective>(*S));
297*67e74705SXin Li break;
298*67e74705SXin Li }
299*67e74705SXin Li }
300*67e74705SXin Li
EmitSimpleStmt(const Stmt * S)301*67e74705SXin Li bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
302*67e74705SXin Li switch (S->getStmtClass()) {
303*67e74705SXin Li default: return false;
304*67e74705SXin Li case Stmt::NullStmtClass: break;
305*67e74705SXin Li case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
306*67e74705SXin Li case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
307*67e74705SXin Li case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
308*67e74705SXin Li case Stmt::AttributedStmtClass:
309*67e74705SXin Li EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
310*67e74705SXin Li case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
311*67e74705SXin Li case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
312*67e74705SXin Li case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
313*67e74705SXin Li case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
314*67e74705SXin Li case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
315*67e74705SXin Li case Stmt::SEHLeaveStmtClass: EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S)); break;
316*67e74705SXin Li }
317*67e74705SXin Li
318*67e74705SXin Li return true;
319*67e74705SXin Li }
320*67e74705SXin Li
321*67e74705SXin Li /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
322*67e74705SXin Li /// this captures the expression result of the last sub-statement and returns it
323*67e74705SXin Li /// (for use by the statement expression extension).
EmitCompoundStmt(const CompoundStmt & S,bool GetLast,AggValueSlot AggSlot)324*67e74705SXin Li Address CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
325*67e74705SXin Li AggValueSlot AggSlot) {
326*67e74705SXin Li PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
327*67e74705SXin Li "LLVM IR generation of compound statement ('{}')");
328*67e74705SXin Li
329*67e74705SXin Li // Keep track of the current cleanup stack depth, including debug scopes.
330*67e74705SXin Li LexicalScope Scope(*this, S.getSourceRange());
331*67e74705SXin Li
332*67e74705SXin Li return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
333*67e74705SXin Li }
334*67e74705SXin Li
335*67e74705SXin Li Address
EmitCompoundStmtWithoutScope(const CompoundStmt & S,bool GetLast,AggValueSlot AggSlot)336*67e74705SXin Li CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S,
337*67e74705SXin Li bool GetLast,
338*67e74705SXin Li AggValueSlot AggSlot) {
339*67e74705SXin Li
340*67e74705SXin Li for (CompoundStmt::const_body_iterator I = S.body_begin(),
341*67e74705SXin Li E = S.body_end()-GetLast; I != E; ++I)
342*67e74705SXin Li EmitStmt(*I);
343*67e74705SXin Li
344*67e74705SXin Li Address RetAlloca = Address::invalid();
345*67e74705SXin Li if (GetLast) {
346*67e74705SXin Li // We have to special case labels here. They are statements, but when put
347*67e74705SXin Li // at the end of a statement expression, they yield the value of their
348*67e74705SXin Li // subexpression. Handle this by walking through all labels we encounter,
349*67e74705SXin Li // emitting them before we evaluate the subexpr.
350*67e74705SXin Li const Stmt *LastStmt = S.body_back();
351*67e74705SXin Li while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
352*67e74705SXin Li EmitLabel(LS->getDecl());
353*67e74705SXin Li LastStmt = LS->getSubStmt();
354*67e74705SXin Li }
355*67e74705SXin Li
356*67e74705SXin Li EnsureInsertPoint();
357*67e74705SXin Li
358*67e74705SXin Li QualType ExprTy = cast<Expr>(LastStmt)->getType();
359*67e74705SXin Li if (hasAggregateEvaluationKind(ExprTy)) {
360*67e74705SXin Li EmitAggExpr(cast<Expr>(LastStmt), AggSlot);
361*67e74705SXin Li } else {
362*67e74705SXin Li // We can't return an RValue here because there might be cleanups at
363*67e74705SXin Li // the end of the StmtExpr. Because of that, we have to emit the result
364*67e74705SXin Li // here into a temporary alloca.
365*67e74705SXin Li RetAlloca = CreateMemTemp(ExprTy);
366*67e74705SXin Li EmitAnyExprToMem(cast<Expr>(LastStmt), RetAlloca, Qualifiers(),
367*67e74705SXin Li /*IsInit*/false);
368*67e74705SXin Li }
369*67e74705SXin Li
370*67e74705SXin Li }
371*67e74705SXin Li
372*67e74705SXin Li return RetAlloca;
373*67e74705SXin Li }
374*67e74705SXin Li
SimplifyForwardingBlocks(llvm::BasicBlock * BB)375*67e74705SXin Li void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
376*67e74705SXin Li llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
377*67e74705SXin Li
378*67e74705SXin Li // If there is a cleanup stack, then we it isn't worth trying to
379*67e74705SXin Li // simplify this block (we would need to remove it from the scope map
380*67e74705SXin Li // and cleanup entry).
381*67e74705SXin Li if (!EHStack.empty())
382*67e74705SXin Li return;
383*67e74705SXin Li
384*67e74705SXin Li // Can only simplify direct branches.
385*67e74705SXin Li if (!BI || !BI->isUnconditional())
386*67e74705SXin Li return;
387*67e74705SXin Li
388*67e74705SXin Li // Can only simplify empty blocks.
389*67e74705SXin Li if (BI->getIterator() != BB->begin())
390*67e74705SXin Li return;
391*67e74705SXin Li
392*67e74705SXin Li BB->replaceAllUsesWith(BI->getSuccessor(0));
393*67e74705SXin Li BI->eraseFromParent();
394*67e74705SXin Li BB->eraseFromParent();
395*67e74705SXin Li }
396*67e74705SXin Li
EmitBlock(llvm::BasicBlock * BB,bool IsFinished)397*67e74705SXin Li void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
398*67e74705SXin Li llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
399*67e74705SXin Li
400*67e74705SXin Li // Fall out of the current block (if necessary).
401*67e74705SXin Li EmitBranch(BB);
402*67e74705SXin Li
403*67e74705SXin Li if (IsFinished && BB->use_empty()) {
404*67e74705SXin Li delete BB;
405*67e74705SXin Li return;
406*67e74705SXin Li }
407*67e74705SXin Li
408*67e74705SXin Li // Place the block after the current block, if possible, or else at
409*67e74705SXin Li // the end of the function.
410*67e74705SXin Li if (CurBB && CurBB->getParent())
411*67e74705SXin Li CurFn->getBasicBlockList().insertAfter(CurBB->getIterator(), BB);
412*67e74705SXin Li else
413*67e74705SXin Li CurFn->getBasicBlockList().push_back(BB);
414*67e74705SXin Li Builder.SetInsertPoint(BB);
415*67e74705SXin Li }
416*67e74705SXin Li
EmitBranch(llvm::BasicBlock * Target)417*67e74705SXin Li void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
418*67e74705SXin Li // Emit a branch from the current block to the target one if this
419*67e74705SXin Li // was a real block. If this was just a fall-through block after a
420*67e74705SXin Li // terminator, don't emit it.
421*67e74705SXin Li llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
422*67e74705SXin Li
423*67e74705SXin Li if (!CurBB || CurBB->getTerminator()) {
424*67e74705SXin Li // If there is no insert point or the previous block is already
425*67e74705SXin Li // terminated, don't touch it.
426*67e74705SXin Li } else {
427*67e74705SXin Li // Otherwise, create a fall-through branch.
428*67e74705SXin Li Builder.CreateBr(Target);
429*67e74705SXin Li }
430*67e74705SXin Li
431*67e74705SXin Li Builder.ClearInsertionPoint();
432*67e74705SXin Li }
433*67e74705SXin Li
EmitBlockAfterUses(llvm::BasicBlock * block)434*67e74705SXin Li void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
435*67e74705SXin Li bool inserted = false;
436*67e74705SXin Li for (llvm::User *u : block->users()) {
437*67e74705SXin Li if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
438*67e74705SXin Li CurFn->getBasicBlockList().insertAfter(insn->getParent()->getIterator(),
439*67e74705SXin Li block);
440*67e74705SXin Li inserted = true;
441*67e74705SXin Li break;
442*67e74705SXin Li }
443*67e74705SXin Li }
444*67e74705SXin Li
445*67e74705SXin Li if (!inserted)
446*67e74705SXin Li CurFn->getBasicBlockList().push_back(block);
447*67e74705SXin Li
448*67e74705SXin Li Builder.SetInsertPoint(block);
449*67e74705SXin Li }
450*67e74705SXin Li
451*67e74705SXin Li CodeGenFunction::JumpDest
getJumpDestForLabel(const LabelDecl * D)452*67e74705SXin Li CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
453*67e74705SXin Li JumpDest &Dest = LabelMap[D];
454*67e74705SXin Li if (Dest.isValid()) return Dest;
455*67e74705SXin Li
456*67e74705SXin Li // Create, but don't insert, the new block.
457*67e74705SXin Li Dest = JumpDest(createBasicBlock(D->getName()),
458*67e74705SXin Li EHScopeStack::stable_iterator::invalid(),
459*67e74705SXin Li NextCleanupDestIndex++);
460*67e74705SXin Li return Dest;
461*67e74705SXin Li }
462*67e74705SXin Li
EmitLabel(const LabelDecl * D)463*67e74705SXin Li void CodeGenFunction::EmitLabel(const LabelDecl *D) {
464*67e74705SXin Li // Add this label to the current lexical scope if we're within any
465*67e74705SXin Li // normal cleanups. Jumps "in" to this label --- when permitted by
466*67e74705SXin Li // the language --- may need to be routed around such cleanups.
467*67e74705SXin Li if (EHStack.hasNormalCleanups() && CurLexicalScope)
468*67e74705SXin Li CurLexicalScope->addLabel(D);
469*67e74705SXin Li
470*67e74705SXin Li JumpDest &Dest = LabelMap[D];
471*67e74705SXin Li
472*67e74705SXin Li // If we didn't need a forward reference to this label, just go
473*67e74705SXin Li // ahead and create a destination at the current scope.
474*67e74705SXin Li if (!Dest.isValid()) {
475*67e74705SXin Li Dest = getJumpDestInCurrentScope(D->getName());
476*67e74705SXin Li
477*67e74705SXin Li // Otherwise, we need to give this label a target depth and remove
478*67e74705SXin Li // it from the branch-fixups list.
479*67e74705SXin Li } else {
480*67e74705SXin Li assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
481*67e74705SXin Li Dest.setScopeDepth(EHStack.stable_begin());
482*67e74705SXin Li ResolveBranchFixups(Dest.getBlock());
483*67e74705SXin Li }
484*67e74705SXin Li
485*67e74705SXin Li EmitBlock(Dest.getBlock());
486*67e74705SXin Li incrementProfileCounter(D->getStmt());
487*67e74705SXin Li }
488*67e74705SXin Li
489*67e74705SXin Li /// Change the cleanup scope of the labels in this lexical scope to
490*67e74705SXin Li /// match the scope of the enclosing context.
rescopeLabels()491*67e74705SXin Li void CodeGenFunction::LexicalScope::rescopeLabels() {
492*67e74705SXin Li assert(!Labels.empty());
493*67e74705SXin Li EHScopeStack::stable_iterator innermostScope
494*67e74705SXin Li = CGF.EHStack.getInnermostNormalCleanup();
495*67e74705SXin Li
496*67e74705SXin Li // Change the scope depth of all the labels.
497*67e74705SXin Li for (SmallVectorImpl<const LabelDecl*>::const_iterator
498*67e74705SXin Li i = Labels.begin(), e = Labels.end(); i != e; ++i) {
499*67e74705SXin Li assert(CGF.LabelMap.count(*i));
500*67e74705SXin Li JumpDest &dest = CGF.LabelMap.find(*i)->second;
501*67e74705SXin Li assert(dest.getScopeDepth().isValid());
502*67e74705SXin Li assert(innermostScope.encloses(dest.getScopeDepth()));
503*67e74705SXin Li dest.setScopeDepth(innermostScope);
504*67e74705SXin Li }
505*67e74705SXin Li
506*67e74705SXin Li // Reparent the labels if the new scope also has cleanups.
507*67e74705SXin Li if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
508*67e74705SXin Li ParentScope->Labels.append(Labels.begin(), Labels.end());
509*67e74705SXin Li }
510*67e74705SXin Li }
511*67e74705SXin Li
512*67e74705SXin Li
EmitLabelStmt(const LabelStmt & S)513*67e74705SXin Li void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
514*67e74705SXin Li EmitLabel(S.getDecl());
515*67e74705SXin Li EmitStmt(S.getSubStmt());
516*67e74705SXin Li }
517*67e74705SXin Li
EmitAttributedStmt(const AttributedStmt & S)518*67e74705SXin Li void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
519*67e74705SXin Li const Stmt *SubStmt = S.getSubStmt();
520*67e74705SXin Li switch (SubStmt->getStmtClass()) {
521*67e74705SXin Li case Stmt::DoStmtClass:
522*67e74705SXin Li EmitDoStmt(cast<DoStmt>(*SubStmt), S.getAttrs());
523*67e74705SXin Li break;
524*67e74705SXin Li case Stmt::ForStmtClass:
525*67e74705SXin Li EmitForStmt(cast<ForStmt>(*SubStmt), S.getAttrs());
526*67e74705SXin Li break;
527*67e74705SXin Li case Stmt::WhileStmtClass:
528*67e74705SXin Li EmitWhileStmt(cast<WhileStmt>(*SubStmt), S.getAttrs());
529*67e74705SXin Li break;
530*67e74705SXin Li case Stmt::CXXForRangeStmtClass:
531*67e74705SXin Li EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*SubStmt), S.getAttrs());
532*67e74705SXin Li break;
533*67e74705SXin Li default:
534*67e74705SXin Li EmitStmt(SubStmt);
535*67e74705SXin Li }
536*67e74705SXin Li }
537*67e74705SXin Li
EmitGotoStmt(const GotoStmt & S)538*67e74705SXin Li void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
539*67e74705SXin Li // If this code is reachable then emit a stop point (if generating
540*67e74705SXin Li // debug info). We have to do this ourselves because we are on the
541*67e74705SXin Li // "simple" statement path.
542*67e74705SXin Li if (HaveInsertPoint())
543*67e74705SXin Li EmitStopPoint(&S);
544*67e74705SXin Li
545*67e74705SXin Li EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
546*67e74705SXin Li }
547*67e74705SXin Li
548*67e74705SXin Li
EmitIndirectGotoStmt(const IndirectGotoStmt & S)549*67e74705SXin Li void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
550*67e74705SXin Li if (const LabelDecl *Target = S.getConstantTarget()) {
551*67e74705SXin Li EmitBranchThroughCleanup(getJumpDestForLabel(Target));
552*67e74705SXin Li return;
553*67e74705SXin Li }
554*67e74705SXin Li
555*67e74705SXin Li // Ensure that we have an i8* for our PHI node.
556*67e74705SXin Li llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
557*67e74705SXin Li Int8PtrTy, "addr");
558*67e74705SXin Li llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
559*67e74705SXin Li
560*67e74705SXin Li // Get the basic block for the indirect goto.
561*67e74705SXin Li llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
562*67e74705SXin Li
563*67e74705SXin Li // The first instruction in the block has to be the PHI for the switch dest,
564*67e74705SXin Li // add an entry for this branch.
565*67e74705SXin Li cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
566*67e74705SXin Li
567*67e74705SXin Li EmitBranch(IndGotoBB);
568*67e74705SXin Li }
569*67e74705SXin Li
EmitIfStmt(const IfStmt & S)570*67e74705SXin Li void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
571*67e74705SXin Li // C99 6.8.4.1: The first substatement is executed if the expression compares
572*67e74705SXin Li // unequal to 0. The condition must be a scalar type.
573*67e74705SXin Li LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
574*67e74705SXin Li
575*67e74705SXin Li if (S.getInit())
576*67e74705SXin Li EmitStmt(S.getInit());
577*67e74705SXin Li
578*67e74705SXin Li if (S.getConditionVariable())
579*67e74705SXin Li EmitAutoVarDecl(*S.getConditionVariable());
580*67e74705SXin Li
581*67e74705SXin Li // If the condition constant folds and can be elided, try to avoid emitting
582*67e74705SXin Li // the condition and the dead arm of the if/else.
583*67e74705SXin Li bool CondConstant;
584*67e74705SXin Li if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant,
585*67e74705SXin Li S.isConstexpr())) {
586*67e74705SXin Li // Figure out which block (then or else) is executed.
587*67e74705SXin Li const Stmt *Executed = S.getThen();
588*67e74705SXin Li const Stmt *Skipped = S.getElse();
589*67e74705SXin Li if (!CondConstant) // Condition false?
590*67e74705SXin Li std::swap(Executed, Skipped);
591*67e74705SXin Li
592*67e74705SXin Li // If the skipped block has no labels in it, just emit the executed block.
593*67e74705SXin Li // This avoids emitting dead code and simplifies the CFG substantially.
594*67e74705SXin Li if (S.isConstexpr() || !ContainsLabel(Skipped)) {
595*67e74705SXin Li if (CondConstant)
596*67e74705SXin Li incrementProfileCounter(&S);
597*67e74705SXin Li if (Executed) {
598*67e74705SXin Li RunCleanupsScope ExecutedScope(*this);
599*67e74705SXin Li EmitStmt(Executed);
600*67e74705SXin Li }
601*67e74705SXin Li return;
602*67e74705SXin Li }
603*67e74705SXin Li }
604*67e74705SXin Li
605*67e74705SXin Li // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
606*67e74705SXin Li // the conditional branch.
607*67e74705SXin Li llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
608*67e74705SXin Li llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
609*67e74705SXin Li llvm::BasicBlock *ElseBlock = ContBlock;
610*67e74705SXin Li if (S.getElse())
611*67e74705SXin Li ElseBlock = createBasicBlock("if.else");
612*67e74705SXin Li
613*67e74705SXin Li EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock,
614*67e74705SXin Li getProfileCount(S.getThen()));
615*67e74705SXin Li
616*67e74705SXin Li // Emit the 'then' code.
617*67e74705SXin Li EmitBlock(ThenBlock);
618*67e74705SXin Li incrementProfileCounter(&S);
619*67e74705SXin Li {
620*67e74705SXin Li RunCleanupsScope ThenScope(*this);
621*67e74705SXin Li EmitStmt(S.getThen());
622*67e74705SXin Li }
623*67e74705SXin Li {
624*67e74705SXin Li auto CurBlock = Builder.GetInsertBlock();
625*67e74705SXin Li EmitBranch(ContBlock);
626*67e74705SXin Li // Eliminate any empty blocks that may have been created by nested
627*67e74705SXin Li // control flow statements in the 'then' clause.
628*67e74705SXin Li if (CurBlock)
629*67e74705SXin Li SimplifyForwardingBlocks(CurBlock);
630*67e74705SXin Li }
631*67e74705SXin Li
632*67e74705SXin Li // Emit the 'else' code if present.
633*67e74705SXin Li if (const Stmt *Else = S.getElse()) {
634*67e74705SXin Li {
635*67e74705SXin Li // There is no need to emit line number for an unconditional branch.
636*67e74705SXin Li auto NL = ApplyDebugLocation::CreateEmpty(*this);
637*67e74705SXin Li EmitBlock(ElseBlock);
638*67e74705SXin Li }
639*67e74705SXin Li {
640*67e74705SXin Li RunCleanupsScope ElseScope(*this);
641*67e74705SXin Li EmitStmt(Else);
642*67e74705SXin Li }
643*67e74705SXin Li {
644*67e74705SXin Li // There is no need to emit line number for an unconditional branch.
645*67e74705SXin Li auto NL = ApplyDebugLocation::CreateEmpty(*this);
646*67e74705SXin Li auto CurBlock = Builder.GetInsertBlock();
647*67e74705SXin Li EmitBranch(ContBlock);
648*67e74705SXin Li // Eliminate any empty blocks that may have been created by nested
649*67e74705SXin Li // control flow statements emitted in the 'else' clause.
650*67e74705SXin Li if (CurBlock)
651*67e74705SXin Li SimplifyForwardingBlocks(CurBlock);
652*67e74705SXin Li }
653*67e74705SXin Li }
654*67e74705SXin Li
655*67e74705SXin Li // Emit the continuation block for code after the if.
656*67e74705SXin Li EmitBlock(ContBlock, true);
657*67e74705SXin Li }
658*67e74705SXin Li
EmitWhileStmt(const WhileStmt & S,ArrayRef<const Attr * > WhileAttrs)659*67e74705SXin Li void CodeGenFunction::EmitWhileStmt(const WhileStmt &S,
660*67e74705SXin Li ArrayRef<const Attr *> WhileAttrs) {
661*67e74705SXin Li // Emit the header for the loop, which will also become
662*67e74705SXin Li // the continue target.
663*67e74705SXin Li JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
664*67e74705SXin Li EmitBlock(LoopHeader.getBlock());
665*67e74705SXin Li
666*67e74705SXin Li LoopStack.push(LoopHeader.getBlock(), CGM.getContext(), WhileAttrs,
667*67e74705SXin Li Builder.getCurrentDebugLocation());
668*67e74705SXin Li
669*67e74705SXin Li // Create an exit block for when the condition fails, which will
670*67e74705SXin Li // also become the break target.
671*67e74705SXin Li JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
672*67e74705SXin Li
673*67e74705SXin Li // Store the blocks to use for break and continue.
674*67e74705SXin Li BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
675*67e74705SXin Li
676*67e74705SXin Li // C++ [stmt.while]p2:
677*67e74705SXin Li // When the condition of a while statement is a declaration, the
678*67e74705SXin Li // scope of the variable that is declared extends from its point
679*67e74705SXin Li // of declaration (3.3.2) to the end of the while statement.
680*67e74705SXin Li // [...]
681*67e74705SXin Li // The object created in a condition is destroyed and created
682*67e74705SXin Li // with each iteration of the loop.
683*67e74705SXin Li RunCleanupsScope ConditionScope(*this);
684*67e74705SXin Li
685*67e74705SXin Li if (S.getConditionVariable())
686*67e74705SXin Li EmitAutoVarDecl(*S.getConditionVariable());
687*67e74705SXin Li
688*67e74705SXin Li // Evaluate the conditional in the while header. C99 6.8.5.1: The
689*67e74705SXin Li // evaluation of the controlling expression takes place before each
690*67e74705SXin Li // execution of the loop body.
691*67e74705SXin Li llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
692*67e74705SXin Li
693*67e74705SXin Li // while(1) is common, avoid extra exit blocks. Be sure
694*67e74705SXin Li // to correctly handle break/continue though.
695*67e74705SXin Li bool EmitBoolCondBranch = true;
696*67e74705SXin Li if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
697*67e74705SXin Li if (C->isOne())
698*67e74705SXin Li EmitBoolCondBranch = false;
699*67e74705SXin Li
700*67e74705SXin Li // As long as the condition is true, go to the loop body.
701*67e74705SXin Li llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
702*67e74705SXin Li if (EmitBoolCondBranch) {
703*67e74705SXin Li llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
704*67e74705SXin Li if (ConditionScope.requiresCleanups())
705*67e74705SXin Li ExitBlock = createBasicBlock("while.exit");
706*67e74705SXin Li Builder.CreateCondBr(
707*67e74705SXin Li BoolCondVal, LoopBody, ExitBlock,
708*67e74705SXin Li createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
709*67e74705SXin Li
710*67e74705SXin Li if (ExitBlock != LoopExit.getBlock()) {
711*67e74705SXin Li EmitBlock(ExitBlock);
712*67e74705SXin Li EmitBranchThroughCleanup(LoopExit);
713*67e74705SXin Li }
714*67e74705SXin Li }
715*67e74705SXin Li
716*67e74705SXin Li // Emit the loop body. We have to emit this in a cleanup scope
717*67e74705SXin Li // because it might be a singleton DeclStmt.
718*67e74705SXin Li {
719*67e74705SXin Li RunCleanupsScope BodyScope(*this);
720*67e74705SXin Li EmitBlock(LoopBody);
721*67e74705SXin Li incrementProfileCounter(&S);
722*67e74705SXin Li EmitStmt(S.getBody());
723*67e74705SXin Li }
724*67e74705SXin Li
725*67e74705SXin Li BreakContinueStack.pop_back();
726*67e74705SXin Li
727*67e74705SXin Li // Immediately force cleanup.
728*67e74705SXin Li ConditionScope.ForceCleanup();
729*67e74705SXin Li
730*67e74705SXin Li EmitStopPoint(&S);
731*67e74705SXin Li // Branch to the loop header again.
732*67e74705SXin Li EmitBranch(LoopHeader.getBlock());
733*67e74705SXin Li
734*67e74705SXin Li LoopStack.pop();
735*67e74705SXin Li
736*67e74705SXin Li // Emit the exit block.
737*67e74705SXin Li EmitBlock(LoopExit.getBlock(), true);
738*67e74705SXin Li
739*67e74705SXin Li // The LoopHeader typically is just a branch if we skipped emitting
740*67e74705SXin Li // a branch, try to erase it.
741*67e74705SXin Li if (!EmitBoolCondBranch)
742*67e74705SXin Li SimplifyForwardingBlocks(LoopHeader.getBlock());
743*67e74705SXin Li }
744*67e74705SXin Li
EmitDoStmt(const DoStmt & S,ArrayRef<const Attr * > DoAttrs)745*67e74705SXin Li void CodeGenFunction::EmitDoStmt(const DoStmt &S,
746*67e74705SXin Li ArrayRef<const Attr *> DoAttrs) {
747*67e74705SXin Li JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
748*67e74705SXin Li JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
749*67e74705SXin Li
750*67e74705SXin Li uint64_t ParentCount = getCurrentProfileCount();
751*67e74705SXin Li
752*67e74705SXin Li // Store the blocks to use for break and continue.
753*67e74705SXin Li BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
754*67e74705SXin Li
755*67e74705SXin Li // Emit the body of the loop.
756*67e74705SXin Li llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
757*67e74705SXin Li
758*67e74705SXin Li LoopStack.push(LoopBody, CGM.getContext(), DoAttrs,
759*67e74705SXin Li Builder.getCurrentDebugLocation());
760*67e74705SXin Li
761*67e74705SXin Li EmitBlockWithFallThrough(LoopBody, &S);
762*67e74705SXin Li {
763*67e74705SXin Li RunCleanupsScope BodyScope(*this);
764*67e74705SXin Li EmitStmt(S.getBody());
765*67e74705SXin Li }
766*67e74705SXin Li
767*67e74705SXin Li EmitBlock(LoopCond.getBlock());
768*67e74705SXin Li
769*67e74705SXin Li // C99 6.8.5.2: "The evaluation of the controlling expression takes place
770*67e74705SXin Li // after each execution of the loop body."
771*67e74705SXin Li
772*67e74705SXin Li // Evaluate the conditional in the while header.
773*67e74705SXin Li // C99 6.8.5p2/p4: The first substatement is executed if the expression
774*67e74705SXin Li // compares unequal to 0. The condition must be a scalar type.
775*67e74705SXin Li llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
776*67e74705SXin Li
777*67e74705SXin Li BreakContinueStack.pop_back();
778*67e74705SXin Li
779*67e74705SXin Li // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
780*67e74705SXin Li // to correctly handle break/continue though.
781*67e74705SXin Li bool EmitBoolCondBranch = true;
782*67e74705SXin Li if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
783*67e74705SXin Li if (C->isZero())
784*67e74705SXin Li EmitBoolCondBranch = false;
785*67e74705SXin Li
786*67e74705SXin Li // As long as the condition is true, iterate the loop.
787*67e74705SXin Li if (EmitBoolCondBranch) {
788*67e74705SXin Li uint64_t BackedgeCount = getProfileCount(S.getBody()) - ParentCount;
789*67e74705SXin Li Builder.CreateCondBr(
790*67e74705SXin Li BoolCondVal, LoopBody, LoopExit.getBlock(),
791*67e74705SXin Li createProfileWeightsForLoop(S.getCond(), BackedgeCount));
792*67e74705SXin Li }
793*67e74705SXin Li
794*67e74705SXin Li LoopStack.pop();
795*67e74705SXin Li
796*67e74705SXin Li // Emit the exit block.
797*67e74705SXin Li EmitBlock(LoopExit.getBlock());
798*67e74705SXin Li
799*67e74705SXin Li // The DoCond block typically is just a branch if we skipped
800*67e74705SXin Li // emitting a branch, try to erase it.
801*67e74705SXin Li if (!EmitBoolCondBranch)
802*67e74705SXin Li SimplifyForwardingBlocks(LoopCond.getBlock());
803*67e74705SXin Li }
804*67e74705SXin Li
EmitForStmt(const ForStmt & S,ArrayRef<const Attr * > ForAttrs)805*67e74705SXin Li void CodeGenFunction::EmitForStmt(const ForStmt &S,
806*67e74705SXin Li ArrayRef<const Attr *> ForAttrs) {
807*67e74705SXin Li JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
808*67e74705SXin Li
809*67e74705SXin Li LexicalScope ForScope(*this, S.getSourceRange());
810*67e74705SXin Li
811*67e74705SXin Li llvm::DebugLoc DL = Builder.getCurrentDebugLocation();
812*67e74705SXin Li
813*67e74705SXin Li // Evaluate the first part before the loop.
814*67e74705SXin Li if (S.getInit())
815*67e74705SXin Li EmitStmt(S.getInit());
816*67e74705SXin Li
817*67e74705SXin Li // Start the loop with a block that tests the condition.
818*67e74705SXin Li // If there's an increment, the continue scope will be overwritten
819*67e74705SXin Li // later.
820*67e74705SXin Li JumpDest Continue = getJumpDestInCurrentScope("for.cond");
821*67e74705SXin Li llvm::BasicBlock *CondBlock = Continue.getBlock();
822*67e74705SXin Li EmitBlock(CondBlock);
823*67e74705SXin Li
824*67e74705SXin Li LoopStack.push(CondBlock, CGM.getContext(), ForAttrs, DL);
825*67e74705SXin Li
826*67e74705SXin Li // If the for loop doesn't have an increment we can just use the
827*67e74705SXin Li // condition as the continue block. Otherwise we'll need to create
828*67e74705SXin Li // a block for it (in the current scope, i.e. in the scope of the
829*67e74705SXin Li // condition), and that we will become our continue block.
830*67e74705SXin Li if (S.getInc())
831*67e74705SXin Li Continue = getJumpDestInCurrentScope("for.inc");
832*67e74705SXin Li
833*67e74705SXin Li // Store the blocks to use for break and continue.
834*67e74705SXin Li BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
835*67e74705SXin Li
836*67e74705SXin Li // Create a cleanup scope for the condition variable cleanups.
837*67e74705SXin Li LexicalScope ConditionScope(*this, S.getSourceRange());
838*67e74705SXin Li
839*67e74705SXin Li if (S.getCond()) {
840*67e74705SXin Li // If the for statement has a condition scope, emit the local variable
841*67e74705SXin Li // declaration.
842*67e74705SXin Li if (S.getConditionVariable()) {
843*67e74705SXin Li EmitAutoVarDecl(*S.getConditionVariable());
844*67e74705SXin Li }
845*67e74705SXin Li
846*67e74705SXin Li llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
847*67e74705SXin Li // If there are any cleanups between here and the loop-exit scope,
848*67e74705SXin Li // create a block to stage a loop exit along.
849*67e74705SXin Li if (ForScope.requiresCleanups())
850*67e74705SXin Li ExitBlock = createBasicBlock("for.cond.cleanup");
851*67e74705SXin Li
852*67e74705SXin Li // As long as the condition is true, iterate the loop.
853*67e74705SXin Li llvm::BasicBlock *ForBody = createBasicBlock("for.body");
854*67e74705SXin Li
855*67e74705SXin Li // C99 6.8.5p2/p4: The first substatement is executed if the expression
856*67e74705SXin Li // compares unequal to 0. The condition must be a scalar type.
857*67e74705SXin Li llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
858*67e74705SXin Li Builder.CreateCondBr(
859*67e74705SXin Li BoolCondVal, ForBody, ExitBlock,
860*67e74705SXin Li createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
861*67e74705SXin Li
862*67e74705SXin Li if (ExitBlock != LoopExit.getBlock()) {
863*67e74705SXin Li EmitBlock(ExitBlock);
864*67e74705SXin Li EmitBranchThroughCleanup(LoopExit);
865*67e74705SXin Li }
866*67e74705SXin Li
867*67e74705SXin Li EmitBlock(ForBody);
868*67e74705SXin Li } else {
869*67e74705SXin Li // Treat it as a non-zero constant. Don't even create a new block for the
870*67e74705SXin Li // body, just fall into it.
871*67e74705SXin Li }
872*67e74705SXin Li incrementProfileCounter(&S);
873*67e74705SXin Li
874*67e74705SXin Li {
875*67e74705SXin Li // Create a separate cleanup scope for the body, in case it is not
876*67e74705SXin Li // a compound statement.
877*67e74705SXin Li RunCleanupsScope BodyScope(*this);
878*67e74705SXin Li EmitStmt(S.getBody());
879*67e74705SXin Li }
880*67e74705SXin Li
881*67e74705SXin Li // If there is an increment, emit it next.
882*67e74705SXin Li if (S.getInc()) {
883*67e74705SXin Li EmitBlock(Continue.getBlock());
884*67e74705SXin Li EmitStmt(S.getInc());
885*67e74705SXin Li }
886*67e74705SXin Li
887*67e74705SXin Li BreakContinueStack.pop_back();
888*67e74705SXin Li
889*67e74705SXin Li ConditionScope.ForceCleanup();
890*67e74705SXin Li
891*67e74705SXin Li EmitStopPoint(&S);
892*67e74705SXin Li EmitBranch(CondBlock);
893*67e74705SXin Li
894*67e74705SXin Li ForScope.ForceCleanup();
895*67e74705SXin Li
896*67e74705SXin Li LoopStack.pop();
897*67e74705SXin Li
898*67e74705SXin Li // Emit the fall-through block.
899*67e74705SXin Li EmitBlock(LoopExit.getBlock(), true);
900*67e74705SXin Li }
901*67e74705SXin Li
902*67e74705SXin Li void
EmitCXXForRangeStmt(const CXXForRangeStmt & S,ArrayRef<const Attr * > ForAttrs)903*67e74705SXin Li CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
904*67e74705SXin Li ArrayRef<const Attr *> ForAttrs) {
905*67e74705SXin Li JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
906*67e74705SXin Li
907*67e74705SXin Li LexicalScope ForScope(*this, S.getSourceRange());
908*67e74705SXin Li
909*67e74705SXin Li llvm::DebugLoc DL = Builder.getCurrentDebugLocation();
910*67e74705SXin Li
911*67e74705SXin Li // Evaluate the first pieces before the loop.
912*67e74705SXin Li EmitStmt(S.getRangeStmt());
913*67e74705SXin Li EmitStmt(S.getBeginStmt());
914*67e74705SXin Li EmitStmt(S.getEndStmt());
915*67e74705SXin Li
916*67e74705SXin Li // Start the loop with a block that tests the condition.
917*67e74705SXin Li // If there's an increment, the continue scope will be overwritten
918*67e74705SXin Li // later.
919*67e74705SXin Li llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
920*67e74705SXin Li EmitBlock(CondBlock);
921*67e74705SXin Li
922*67e74705SXin Li LoopStack.push(CondBlock, CGM.getContext(), ForAttrs, DL);
923*67e74705SXin Li
924*67e74705SXin Li // If there are any cleanups between here and the loop-exit scope,
925*67e74705SXin Li // create a block to stage a loop exit along.
926*67e74705SXin Li llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
927*67e74705SXin Li if (ForScope.requiresCleanups())
928*67e74705SXin Li ExitBlock = createBasicBlock("for.cond.cleanup");
929*67e74705SXin Li
930*67e74705SXin Li // The loop body, consisting of the specified body and the loop variable.
931*67e74705SXin Li llvm::BasicBlock *ForBody = createBasicBlock("for.body");
932*67e74705SXin Li
933*67e74705SXin Li // The body is executed if the expression, contextually converted
934*67e74705SXin Li // to bool, is true.
935*67e74705SXin Li llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
936*67e74705SXin Li Builder.CreateCondBr(
937*67e74705SXin Li BoolCondVal, ForBody, ExitBlock,
938*67e74705SXin Li createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
939*67e74705SXin Li
940*67e74705SXin Li if (ExitBlock != LoopExit.getBlock()) {
941*67e74705SXin Li EmitBlock(ExitBlock);
942*67e74705SXin Li EmitBranchThroughCleanup(LoopExit);
943*67e74705SXin Li }
944*67e74705SXin Li
945*67e74705SXin Li EmitBlock(ForBody);
946*67e74705SXin Li incrementProfileCounter(&S);
947*67e74705SXin Li
948*67e74705SXin Li // Create a block for the increment. In case of a 'continue', we jump there.
949*67e74705SXin Li JumpDest Continue = getJumpDestInCurrentScope("for.inc");
950*67e74705SXin Li
951*67e74705SXin Li // Store the blocks to use for break and continue.
952*67e74705SXin Li BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
953*67e74705SXin Li
954*67e74705SXin Li {
955*67e74705SXin Li // Create a separate cleanup scope for the loop variable and body.
956*67e74705SXin Li LexicalScope BodyScope(*this, S.getSourceRange());
957*67e74705SXin Li EmitStmt(S.getLoopVarStmt());
958*67e74705SXin Li EmitStmt(S.getBody());
959*67e74705SXin Li }
960*67e74705SXin Li
961*67e74705SXin Li EmitStopPoint(&S);
962*67e74705SXin Li // If there is an increment, emit it next.
963*67e74705SXin Li EmitBlock(Continue.getBlock());
964*67e74705SXin Li EmitStmt(S.getInc());
965*67e74705SXin Li
966*67e74705SXin Li BreakContinueStack.pop_back();
967*67e74705SXin Li
968*67e74705SXin Li EmitBranch(CondBlock);
969*67e74705SXin Li
970*67e74705SXin Li ForScope.ForceCleanup();
971*67e74705SXin Li
972*67e74705SXin Li LoopStack.pop();
973*67e74705SXin Li
974*67e74705SXin Li // Emit the fall-through block.
975*67e74705SXin Li EmitBlock(LoopExit.getBlock(), true);
976*67e74705SXin Li }
977*67e74705SXin Li
EmitReturnOfRValue(RValue RV,QualType Ty)978*67e74705SXin Li void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
979*67e74705SXin Li if (RV.isScalar()) {
980*67e74705SXin Li Builder.CreateStore(RV.getScalarVal(), ReturnValue);
981*67e74705SXin Li } else if (RV.isAggregate()) {
982*67e74705SXin Li EmitAggregateCopy(ReturnValue, RV.getAggregateAddress(), Ty);
983*67e74705SXin Li } else {
984*67e74705SXin Li EmitStoreOfComplex(RV.getComplexVal(), MakeAddrLValue(ReturnValue, Ty),
985*67e74705SXin Li /*init*/ true);
986*67e74705SXin Li }
987*67e74705SXin Li EmitBranchThroughCleanup(ReturnBlock);
988*67e74705SXin Li }
989*67e74705SXin Li
990*67e74705SXin Li /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
991*67e74705SXin Li /// if the function returns void, or may be missing one if the function returns
992*67e74705SXin Li /// non-void. Fun stuff :).
EmitReturnStmt(const ReturnStmt & S)993*67e74705SXin Li void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
994*67e74705SXin Li // Returning from an outlined SEH helper is UB, and we already warn on it.
995*67e74705SXin Li if (IsOutlinedSEHHelper) {
996*67e74705SXin Li Builder.CreateUnreachable();
997*67e74705SXin Li Builder.ClearInsertionPoint();
998*67e74705SXin Li }
999*67e74705SXin Li
1000*67e74705SXin Li // Emit the result value, even if unused, to evalute the side effects.
1001*67e74705SXin Li const Expr *RV = S.getRetValue();
1002*67e74705SXin Li
1003*67e74705SXin Li // Treat block literals in a return expression as if they appeared
1004*67e74705SXin Li // in their own scope. This permits a small, easily-implemented
1005*67e74705SXin Li // exception to our over-conservative rules about not jumping to
1006*67e74705SXin Li // statements following block literals with non-trivial cleanups.
1007*67e74705SXin Li RunCleanupsScope cleanupScope(*this);
1008*67e74705SXin Li if (const ExprWithCleanups *cleanups =
1009*67e74705SXin Li dyn_cast_or_null<ExprWithCleanups>(RV)) {
1010*67e74705SXin Li enterFullExpression(cleanups);
1011*67e74705SXin Li RV = cleanups->getSubExpr();
1012*67e74705SXin Li }
1013*67e74705SXin Li
1014*67e74705SXin Li // FIXME: Clean this up by using an LValue for ReturnTemp,
1015*67e74705SXin Li // EmitStoreThroughLValue, and EmitAnyExpr.
1016*67e74705SXin Li if (getLangOpts().ElideConstructors &&
1017*67e74705SXin Li S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) {
1018*67e74705SXin Li // Apply the named return value optimization for this return statement,
1019*67e74705SXin Li // which means doing nothing: the appropriate result has already been
1020*67e74705SXin Li // constructed into the NRVO variable.
1021*67e74705SXin Li
1022*67e74705SXin Li // If there is an NRVO flag for this variable, set it to 1 into indicate
1023*67e74705SXin Li // that the cleanup code should not destroy the variable.
1024*67e74705SXin Li if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
1025*67e74705SXin Li Builder.CreateFlagStore(Builder.getTrue(), NRVOFlag);
1026*67e74705SXin Li } else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) {
1027*67e74705SXin Li // Make sure not to return anything, but evaluate the expression
1028*67e74705SXin Li // for side effects.
1029*67e74705SXin Li if (RV)
1030*67e74705SXin Li EmitAnyExpr(RV);
1031*67e74705SXin Li } else if (!RV) {
1032*67e74705SXin Li // Do nothing (return value is left uninitialized)
1033*67e74705SXin Li } else if (FnRetTy->isReferenceType()) {
1034*67e74705SXin Li // If this function returns a reference, take the address of the expression
1035*67e74705SXin Li // rather than the value.
1036*67e74705SXin Li RValue Result = EmitReferenceBindingToExpr(RV);
1037*67e74705SXin Li Builder.CreateStore(Result.getScalarVal(), ReturnValue);
1038*67e74705SXin Li } else {
1039*67e74705SXin Li switch (getEvaluationKind(RV->getType())) {
1040*67e74705SXin Li case TEK_Scalar:
1041*67e74705SXin Li Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
1042*67e74705SXin Li break;
1043*67e74705SXin Li case TEK_Complex:
1044*67e74705SXin Li EmitComplexExprIntoLValue(RV, MakeAddrLValue(ReturnValue, RV->getType()),
1045*67e74705SXin Li /*isInit*/ true);
1046*67e74705SXin Li break;
1047*67e74705SXin Li case TEK_Aggregate:
1048*67e74705SXin Li EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue,
1049*67e74705SXin Li Qualifiers(),
1050*67e74705SXin Li AggValueSlot::IsDestructed,
1051*67e74705SXin Li AggValueSlot::DoesNotNeedGCBarriers,
1052*67e74705SXin Li AggValueSlot::IsNotAliased));
1053*67e74705SXin Li break;
1054*67e74705SXin Li }
1055*67e74705SXin Li }
1056*67e74705SXin Li
1057*67e74705SXin Li ++NumReturnExprs;
1058*67e74705SXin Li if (!RV || RV->isEvaluatable(getContext()))
1059*67e74705SXin Li ++NumSimpleReturnExprs;
1060*67e74705SXin Li
1061*67e74705SXin Li cleanupScope.ForceCleanup();
1062*67e74705SXin Li EmitBranchThroughCleanup(ReturnBlock);
1063*67e74705SXin Li }
1064*67e74705SXin Li
EmitDeclStmt(const DeclStmt & S)1065*67e74705SXin Li void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
1066*67e74705SXin Li // As long as debug info is modeled with instructions, we have to ensure we
1067*67e74705SXin Li // have a place to insert here and write the stop point here.
1068*67e74705SXin Li if (HaveInsertPoint())
1069*67e74705SXin Li EmitStopPoint(&S);
1070*67e74705SXin Li
1071*67e74705SXin Li for (const auto *I : S.decls())
1072*67e74705SXin Li EmitDecl(*I);
1073*67e74705SXin Li }
1074*67e74705SXin Li
EmitBreakStmt(const BreakStmt & S)1075*67e74705SXin Li void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
1076*67e74705SXin Li assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
1077*67e74705SXin Li
1078*67e74705SXin Li // If this code is reachable then emit a stop point (if generating
1079*67e74705SXin Li // debug info). We have to do this ourselves because we are on the
1080*67e74705SXin Li // "simple" statement path.
1081*67e74705SXin Li if (HaveInsertPoint())
1082*67e74705SXin Li EmitStopPoint(&S);
1083*67e74705SXin Li
1084*67e74705SXin Li EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock);
1085*67e74705SXin Li }
1086*67e74705SXin Li
EmitContinueStmt(const ContinueStmt & S)1087*67e74705SXin Li void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
1088*67e74705SXin Li assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1089*67e74705SXin Li
1090*67e74705SXin Li // If this code is reachable then emit a stop point (if generating
1091*67e74705SXin Li // debug info). We have to do this ourselves because we are on the
1092*67e74705SXin Li // "simple" statement path.
1093*67e74705SXin Li if (HaveInsertPoint())
1094*67e74705SXin Li EmitStopPoint(&S);
1095*67e74705SXin Li
1096*67e74705SXin Li EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock);
1097*67e74705SXin Li }
1098*67e74705SXin Li
1099*67e74705SXin Li /// EmitCaseStmtRange - If case statement range is not too big then
1100*67e74705SXin Li /// add multiple cases to switch instruction, one for each value within
1101*67e74705SXin Li /// the range. If range is too big then emit "if" condition check.
EmitCaseStmtRange(const CaseStmt & S)1102*67e74705SXin Li void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
1103*67e74705SXin Li assert(S.getRHS() && "Expected RHS value in CaseStmt");
1104*67e74705SXin Li
1105*67e74705SXin Li llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
1106*67e74705SXin Li llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
1107*67e74705SXin Li
1108*67e74705SXin Li // Emit the code for this case. We do this first to make sure it is
1109*67e74705SXin Li // properly chained from our predecessor before generating the
1110*67e74705SXin Li // switch machinery to enter this block.
1111*67e74705SXin Li llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1112*67e74705SXin Li EmitBlockWithFallThrough(CaseDest, &S);
1113*67e74705SXin Li EmitStmt(S.getSubStmt());
1114*67e74705SXin Li
1115*67e74705SXin Li // If range is empty, do nothing.
1116*67e74705SXin Li if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
1117*67e74705SXin Li return;
1118*67e74705SXin Li
1119*67e74705SXin Li llvm::APInt Range = RHS - LHS;
1120*67e74705SXin Li // FIXME: parameters such as this should not be hardcoded.
1121*67e74705SXin Li if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
1122*67e74705SXin Li // Range is small enough to add multiple switch instruction cases.
1123*67e74705SXin Li uint64_t Total = getProfileCount(&S);
1124*67e74705SXin Li unsigned NCases = Range.getZExtValue() + 1;
1125*67e74705SXin Li // We only have one region counter for the entire set of cases here, so we
1126*67e74705SXin Li // need to divide the weights evenly between the generated cases, ensuring
1127*67e74705SXin Li // that the total weight is preserved. E.g., a weight of 5 over three cases
1128*67e74705SXin Li // will be distributed as weights of 2, 2, and 1.
1129*67e74705SXin Li uint64_t Weight = Total / NCases, Rem = Total % NCases;
1130*67e74705SXin Li for (unsigned I = 0; I != NCases; ++I) {
1131*67e74705SXin Li if (SwitchWeights)
1132*67e74705SXin Li SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
1133*67e74705SXin Li if (Rem)
1134*67e74705SXin Li Rem--;
1135*67e74705SXin Li SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
1136*67e74705SXin Li LHS++;
1137*67e74705SXin Li }
1138*67e74705SXin Li return;
1139*67e74705SXin Li }
1140*67e74705SXin Li
1141*67e74705SXin Li // The range is too big. Emit "if" condition into a new block,
1142*67e74705SXin Li // making sure to save and restore the current insertion point.
1143*67e74705SXin Li llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
1144*67e74705SXin Li
1145*67e74705SXin Li // Push this test onto the chain of range checks (which terminates
1146*67e74705SXin Li // in the default basic block). The switch's default will be changed
1147*67e74705SXin Li // to the top of this chain after switch emission is complete.
1148*67e74705SXin Li llvm::BasicBlock *FalseDest = CaseRangeBlock;
1149*67e74705SXin Li CaseRangeBlock = createBasicBlock("sw.caserange");
1150*67e74705SXin Li
1151*67e74705SXin Li CurFn->getBasicBlockList().push_back(CaseRangeBlock);
1152*67e74705SXin Li Builder.SetInsertPoint(CaseRangeBlock);
1153*67e74705SXin Li
1154*67e74705SXin Li // Emit range check.
1155*67e74705SXin Li llvm::Value *Diff =
1156*67e74705SXin Li Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
1157*67e74705SXin Li llvm::Value *Cond =
1158*67e74705SXin Li Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
1159*67e74705SXin Li
1160*67e74705SXin Li llvm::MDNode *Weights = nullptr;
1161*67e74705SXin Li if (SwitchWeights) {
1162*67e74705SXin Li uint64_t ThisCount = getProfileCount(&S);
1163*67e74705SXin Li uint64_t DefaultCount = (*SwitchWeights)[0];
1164*67e74705SXin Li Weights = createProfileWeights(ThisCount, DefaultCount);
1165*67e74705SXin Li
1166*67e74705SXin Li // Since we're chaining the switch default through each large case range, we
1167*67e74705SXin Li // need to update the weight for the default, ie, the first case, to include
1168*67e74705SXin Li // this case.
1169*67e74705SXin Li (*SwitchWeights)[0] += ThisCount;
1170*67e74705SXin Li }
1171*67e74705SXin Li Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
1172*67e74705SXin Li
1173*67e74705SXin Li // Restore the appropriate insertion point.
1174*67e74705SXin Li if (RestoreBB)
1175*67e74705SXin Li Builder.SetInsertPoint(RestoreBB);
1176*67e74705SXin Li else
1177*67e74705SXin Li Builder.ClearInsertionPoint();
1178*67e74705SXin Li }
1179*67e74705SXin Li
EmitCaseStmt(const CaseStmt & S)1180*67e74705SXin Li void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
1181*67e74705SXin Li // If there is no enclosing switch instance that we're aware of, then this
1182*67e74705SXin Li // case statement and its block can be elided. This situation only happens
1183*67e74705SXin Li // when we've constant-folded the switch, are emitting the constant case,
1184*67e74705SXin Li // and part of the constant case includes another case statement. For
1185*67e74705SXin Li // instance: switch (4) { case 4: do { case 5: } while (1); }
1186*67e74705SXin Li if (!SwitchInsn) {
1187*67e74705SXin Li EmitStmt(S.getSubStmt());
1188*67e74705SXin Li return;
1189*67e74705SXin Li }
1190*67e74705SXin Li
1191*67e74705SXin Li // Handle case ranges.
1192*67e74705SXin Li if (S.getRHS()) {
1193*67e74705SXin Li EmitCaseStmtRange(S);
1194*67e74705SXin Li return;
1195*67e74705SXin Li }
1196*67e74705SXin Li
1197*67e74705SXin Li llvm::ConstantInt *CaseVal =
1198*67e74705SXin Li Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
1199*67e74705SXin Li
1200*67e74705SXin Li // If the body of the case is just a 'break', try to not emit an empty block.
1201*67e74705SXin Li // If we're profiling or we're not optimizing, leave the block in for better
1202*67e74705SXin Li // debug and coverage analysis.
1203*67e74705SXin Li if (!CGM.getCodeGenOpts().hasProfileClangInstr() &&
1204*67e74705SXin Li CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1205*67e74705SXin Li isa<BreakStmt>(S.getSubStmt())) {
1206*67e74705SXin Li JumpDest Block = BreakContinueStack.back().BreakBlock;
1207*67e74705SXin Li
1208*67e74705SXin Li // Only do this optimization if there are no cleanups that need emitting.
1209*67e74705SXin Li if (isObviouslyBranchWithoutCleanups(Block)) {
1210*67e74705SXin Li if (SwitchWeights)
1211*67e74705SXin Li SwitchWeights->push_back(getProfileCount(&S));
1212*67e74705SXin Li SwitchInsn->addCase(CaseVal, Block.getBlock());
1213*67e74705SXin Li
1214*67e74705SXin Li // If there was a fallthrough into this case, make sure to redirect it to
1215*67e74705SXin Li // the end of the switch as well.
1216*67e74705SXin Li if (Builder.GetInsertBlock()) {
1217*67e74705SXin Li Builder.CreateBr(Block.getBlock());
1218*67e74705SXin Li Builder.ClearInsertionPoint();
1219*67e74705SXin Li }
1220*67e74705SXin Li return;
1221*67e74705SXin Li }
1222*67e74705SXin Li }
1223*67e74705SXin Li
1224*67e74705SXin Li llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1225*67e74705SXin Li EmitBlockWithFallThrough(CaseDest, &S);
1226*67e74705SXin Li if (SwitchWeights)
1227*67e74705SXin Li SwitchWeights->push_back(getProfileCount(&S));
1228*67e74705SXin Li SwitchInsn->addCase(CaseVal, CaseDest);
1229*67e74705SXin Li
1230*67e74705SXin Li // Recursively emitting the statement is acceptable, but is not wonderful for
1231*67e74705SXin Li // code where we have many case statements nested together, i.e.:
1232*67e74705SXin Li // case 1:
1233*67e74705SXin Li // case 2:
1234*67e74705SXin Li // case 3: etc.
1235*67e74705SXin Li // Handling this recursively will create a new block for each case statement
1236*67e74705SXin Li // that falls through to the next case which is IR intensive. It also causes
1237*67e74705SXin Li // deep recursion which can run into stack depth limitations. Handle
1238*67e74705SXin Li // sequential non-range case statements specially.
1239*67e74705SXin Li const CaseStmt *CurCase = &S;
1240*67e74705SXin Li const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1241*67e74705SXin Li
1242*67e74705SXin Li // Otherwise, iteratively add consecutive cases to this switch stmt.
1243*67e74705SXin Li while (NextCase && NextCase->getRHS() == nullptr) {
1244*67e74705SXin Li CurCase = NextCase;
1245*67e74705SXin Li llvm::ConstantInt *CaseVal =
1246*67e74705SXin Li Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
1247*67e74705SXin Li
1248*67e74705SXin Li if (SwitchWeights)
1249*67e74705SXin Li SwitchWeights->push_back(getProfileCount(NextCase));
1250*67e74705SXin Li if (CGM.getCodeGenOpts().hasProfileClangInstr()) {
1251*67e74705SXin Li CaseDest = createBasicBlock("sw.bb");
1252*67e74705SXin Li EmitBlockWithFallThrough(CaseDest, &S);
1253*67e74705SXin Li }
1254*67e74705SXin Li
1255*67e74705SXin Li SwitchInsn->addCase(CaseVal, CaseDest);
1256*67e74705SXin Li NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1257*67e74705SXin Li }
1258*67e74705SXin Li
1259*67e74705SXin Li // Normal default recursion for non-cases.
1260*67e74705SXin Li EmitStmt(CurCase->getSubStmt());
1261*67e74705SXin Li }
1262*67e74705SXin Li
EmitDefaultStmt(const DefaultStmt & S)1263*67e74705SXin Li void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
1264*67e74705SXin Li llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1265*67e74705SXin Li assert(DefaultBlock->empty() &&
1266*67e74705SXin Li "EmitDefaultStmt: Default block already defined?");
1267*67e74705SXin Li
1268*67e74705SXin Li EmitBlockWithFallThrough(DefaultBlock, &S);
1269*67e74705SXin Li
1270*67e74705SXin Li EmitStmt(S.getSubStmt());
1271*67e74705SXin Li }
1272*67e74705SXin Li
1273*67e74705SXin Li /// CollectStatementsForCase - Given the body of a 'switch' statement and a
1274*67e74705SXin Li /// constant value that is being switched on, see if we can dead code eliminate
1275*67e74705SXin Li /// the body of the switch to a simple series of statements to emit. Basically,
1276*67e74705SXin Li /// on a switch (5) we want to find these statements:
1277*67e74705SXin Li /// case 5:
1278*67e74705SXin Li /// printf(...); <--
1279*67e74705SXin Li /// ++i; <--
1280*67e74705SXin Li /// break;
1281*67e74705SXin Li ///
1282*67e74705SXin Li /// and add them to the ResultStmts vector. If it is unsafe to do this
1283*67e74705SXin Li /// transformation (for example, one of the elided statements contains a label
1284*67e74705SXin Li /// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
1285*67e74705SXin Li /// should include statements after it (e.g. the printf() line is a substmt of
1286*67e74705SXin Li /// the case) then return CSFC_FallThrough. If we handled it and found a break
1287*67e74705SXin Li /// statement, then return CSFC_Success.
1288*67e74705SXin Li ///
1289*67e74705SXin Li /// If Case is non-null, then we are looking for the specified case, checking
1290*67e74705SXin Li /// that nothing we jump over contains labels. If Case is null, then we found
1291*67e74705SXin Li /// the case and are looking for the break.
1292*67e74705SXin Li ///
1293*67e74705SXin Li /// If the recursive walk actually finds our Case, then we set FoundCase to
1294*67e74705SXin Li /// true.
1295*67e74705SXin Li ///
1296*67e74705SXin Li enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
CollectStatementsForCase(const Stmt * S,const SwitchCase * Case,bool & FoundCase,SmallVectorImpl<const Stmt * > & ResultStmts)1297*67e74705SXin Li static CSFC_Result CollectStatementsForCase(const Stmt *S,
1298*67e74705SXin Li const SwitchCase *Case,
1299*67e74705SXin Li bool &FoundCase,
1300*67e74705SXin Li SmallVectorImpl<const Stmt*> &ResultStmts) {
1301*67e74705SXin Li // If this is a null statement, just succeed.
1302*67e74705SXin Li if (!S)
1303*67e74705SXin Li return Case ? CSFC_Success : CSFC_FallThrough;
1304*67e74705SXin Li
1305*67e74705SXin Li // If this is the switchcase (case 4: or default) that we're looking for, then
1306*67e74705SXin Li // we're in business. Just add the substatement.
1307*67e74705SXin Li if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
1308*67e74705SXin Li if (S == Case) {
1309*67e74705SXin Li FoundCase = true;
1310*67e74705SXin Li return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
1311*67e74705SXin Li ResultStmts);
1312*67e74705SXin Li }
1313*67e74705SXin Li
1314*67e74705SXin Li // Otherwise, this is some other case or default statement, just ignore it.
1315*67e74705SXin Li return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
1316*67e74705SXin Li ResultStmts);
1317*67e74705SXin Li }
1318*67e74705SXin Li
1319*67e74705SXin Li // If we are in the live part of the code and we found our break statement,
1320*67e74705SXin Li // return a success!
1321*67e74705SXin Li if (!Case && isa<BreakStmt>(S))
1322*67e74705SXin Li return CSFC_Success;
1323*67e74705SXin Li
1324*67e74705SXin Li // If this is a switch statement, then it might contain the SwitchCase, the
1325*67e74705SXin Li // break, or neither.
1326*67e74705SXin Li if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1327*67e74705SXin Li // Handle this as two cases: we might be looking for the SwitchCase (if so
1328*67e74705SXin Li // the skipped statements must be skippable) or we might already have it.
1329*67e74705SXin Li CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
1330*67e74705SXin Li if (Case) {
1331*67e74705SXin Li // Keep track of whether we see a skipped declaration. The code could be
1332*67e74705SXin Li // using the declaration even if it is skipped, so we can't optimize out
1333*67e74705SXin Li // the decl if the kept statements might refer to it.
1334*67e74705SXin Li bool HadSkippedDecl = false;
1335*67e74705SXin Li
1336*67e74705SXin Li // If we're looking for the case, just see if we can skip each of the
1337*67e74705SXin Li // substatements.
1338*67e74705SXin Li for (; Case && I != E; ++I) {
1339*67e74705SXin Li HadSkippedDecl |= isa<DeclStmt>(*I);
1340*67e74705SXin Li
1341*67e74705SXin Li switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1342*67e74705SXin Li case CSFC_Failure: return CSFC_Failure;
1343*67e74705SXin Li case CSFC_Success:
1344*67e74705SXin Li // A successful result means that either 1) that the statement doesn't
1345*67e74705SXin Li // have the case and is skippable, or 2) does contain the case value
1346*67e74705SXin Li // and also contains the break to exit the switch. In the later case,
1347*67e74705SXin Li // we just verify the rest of the statements are elidable.
1348*67e74705SXin Li if (FoundCase) {
1349*67e74705SXin Li // If we found the case and skipped declarations, we can't do the
1350*67e74705SXin Li // optimization.
1351*67e74705SXin Li if (HadSkippedDecl)
1352*67e74705SXin Li return CSFC_Failure;
1353*67e74705SXin Li
1354*67e74705SXin Li for (++I; I != E; ++I)
1355*67e74705SXin Li if (CodeGenFunction::ContainsLabel(*I, true))
1356*67e74705SXin Li return CSFC_Failure;
1357*67e74705SXin Li return CSFC_Success;
1358*67e74705SXin Li }
1359*67e74705SXin Li break;
1360*67e74705SXin Li case CSFC_FallThrough:
1361*67e74705SXin Li // If we have a fallthrough condition, then we must have found the
1362*67e74705SXin Li // case started to include statements. Consider the rest of the
1363*67e74705SXin Li // statements in the compound statement as candidates for inclusion.
1364*67e74705SXin Li assert(FoundCase && "Didn't find case but returned fallthrough?");
1365*67e74705SXin Li // We recursively found Case, so we're not looking for it anymore.
1366*67e74705SXin Li Case = nullptr;
1367*67e74705SXin Li
1368*67e74705SXin Li // If we found the case and skipped declarations, we can't do the
1369*67e74705SXin Li // optimization.
1370*67e74705SXin Li if (HadSkippedDecl)
1371*67e74705SXin Li return CSFC_Failure;
1372*67e74705SXin Li break;
1373*67e74705SXin Li }
1374*67e74705SXin Li }
1375*67e74705SXin Li }
1376*67e74705SXin Li
1377*67e74705SXin Li // If we have statements in our range, then we know that the statements are
1378*67e74705SXin Li // live and need to be added to the set of statements we're tracking.
1379*67e74705SXin Li for (; I != E; ++I) {
1380*67e74705SXin Li switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
1381*67e74705SXin Li case CSFC_Failure: return CSFC_Failure;
1382*67e74705SXin Li case CSFC_FallThrough:
1383*67e74705SXin Li // A fallthrough result means that the statement was simple and just
1384*67e74705SXin Li // included in ResultStmt, keep adding them afterwards.
1385*67e74705SXin Li break;
1386*67e74705SXin Li case CSFC_Success:
1387*67e74705SXin Li // A successful result means that we found the break statement and
1388*67e74705SXin Li // stopped statement inclusion. We just ensure that any leftover stmts
1389*67e74705SXin Li // are skippable and return success ourselves.
1390*67e74705SXin Li for (++I; I != E; ++I)
1391*67e74705SXin Li if (CodeGenFunction::ContainsLabel(*I, true))
1392*67e74705SXin Li return CSFC_Failure;
1393*67e74705SXin Li return CSFC_Success;
1394*67e74705SXin Li }
1395*67e74705SXin Li }
1396*67e74705SXin Li
1397*67e74705SXin Li return Case ? CSFC_Success : CSFC_FallThrough;
1398*67e74705SXin Li }
1399*67e74705SXin Li
1400*67e74705SXin Li // Okay, this is some other statement that we don't handle explicitly, like a
1401*67e74705SXin Li // for statement or increment etc. If we are skipping over this statement,
1402*67e74705SXin Li // just verify it doesn't have labels, which would make it invalid to elide.
1403*67e74705SXin Li if (Case) {
1404*67e74705SXin Li if (CodeGenFunction::ContainsLabel(S, true))
1405*67e74705SXin Li return CSFC_Failure;
1406*67e74705SXin Li return CSFC_Success;
1407*67e74705SXin Li }
1408*67e74705SXin Li
1409*67e74705SXin Li // Otherwise, we want to include this statement. Everything is cool with that
1410*67e74705SXin Li // so long as it doesn't contain a break out of the switch we're in.
1411*67e74705SXin Li if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1412*67e74705SXin Li
1413*67e74705SXin Li // Otherwise, everything is great. Include the statement and tell the caller
1414*67e74705SXin Li // that we fall through and include the next statement as well.
1415*67e74705SXin Li ResultStmts.push_back(S);
1416*67e74705SXin Li return CSFC_FallThrough;
1417*67e74705SXin Li }
1418*67e74705SXin Li
1419*67e74705SXin Li /// FindCaseStatementsForValue - Find the case statement being jumped to and
1420*67e74705SXin Li /// then invoke CollectStatementsForCase to find the list of statements to emit
1421*67e74705SXin Li /// for a switch on constant. See the comment above CollectStatementsForCase
1422*67e74705SXin Li /// for more details.
FindCaseStatementsForValue(const SwitchStmt & S,const llvm::APSInt & ConstantCondValue,SmallVectorImpl<const Stmt * > & ResultStmts,ASTContext & C,const SwitchCase * & ResultCase)1423*67e74705SXin Li static bool FindCaseStatementsForValue(const SwitchStmt &S,
1424*67e74705SXin Li const llvm::APSInt &ConstantCondValue,
1425*67e74705SXin Li SmallVectorImpl<const Stmt*> &ResultStmts,
1426*67e74705SXin Li ASTContext &C,
1427*67e74705SXin Li const SwitchCase *&ResultCase) {
1428*67e74705SXin Li // First step, find the switch case that is being branched to. We can do this
1429*67e74705SXin Li // efficiently by scanning the SwitchCase list.
1430*67e74705SXin Li const SwitchCase *Case = S.getSwitchCaseList();
1431*67e74705SXin Li const DefaultStmt *DefaultCase = nullptr;
1432*67e74705SXin Li
1433*67e74705SXin Li for (; Case; Case = Case->getNextSwitchCase()) {
1434*67e74705SXin Li // It's either a default or case. Just remember the default statement in
1435*67e74705SXin Li // case we're not jumping to any numbered cases.
1436*67e74705SXin Li if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1437*67e74705SXin Li DefaultCase = DS;
1438*67e74705SXin Li continue;
1439*67e74705SXin Li }
1440*67e74705SXin Li
1441*67e74705SXin Li // Check to see if this case is the one we're looking for.
1442*67e74705SXin Li const CaseStmt *CS = cast<CaseStmt>(Case);
1443*67e74705SXin Li // Don't handle case ranges yet.
1444*67e74705SXin Li if (CS->getRHS()) return false;
1445*67e74705SXin Li
1446*67e74705SXin Li // If we found our case, remember it as 'case'.
1447*67e74705SXin Li if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
1448*67e74705SXin Li break;
1449*67e74705SXin Li }
1450*67e74705SXin Li
1451*67e74705SXin Li // If we didn't find a matching case, we use a default if it exists, or we
1452*67e74705SXin Li // elide the whole switch body!
1453*67e74705SXin Li if (!Case) {
1454*67e74705SXin Li // It is safe to elide the body of the switch if it doesn't contain labels
1455*67e74705SXin Li // etc. If it is safe, return successfully with an empty ResultStmts list.
1456*67e74705SXin Li if (!DefaultCase)
1457*67e74705SXin Li return !CodeGenFunction::ContainsLabel(&S);
1458*67e74705SXin Li Case = DefaultCase;
1459*67e74705SXin Li }
1460*67e74705SXin Li
1461*67e74705SXin Li // Ok, we know which case is being jumped to, try to collect all the
1462*67e74705SXin Li // statements that follow it. This can fail for a variety of reasons. Also,
1463*67e74705SXin Li // check to see that the recursive walk actually found our case statement.
1464*67e74705SXin Li // Insane cases like this can fail to find it in the recursive walk since we
1465*67e74705SXin Li // don't handle every stmt kind:
1466*67e74705SXin Li // switch (4) {
1467*67e74705SXin Li // while (1) {
1468*67e74705SXin Li // case 4: ...
1469*67e74705SXin Li bool FoundCase = false;
1470*67e74705SXin Li ResultCase = Case;
1471*67e74705SXin Li return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1472*67e74705SXin Li ResultStmts) != CSFC_Failure &&
1473*67e74705SXin Li FoundCase;
1474*67e74705SXin Li }
1475*67e74705SXin Li
EmitSwitchStmt(const SwitchStmt & S)1476*67e74705SXin Li void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1477*67e74705SXin Li // Handle nested switch statements.
1478*67e74705SXin Li llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1479*67e74705SXin Li SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
1480*67e74705SXin Li llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1481*67e74705SXin Li
1482*67e74705SXin Li // See if we can constant fold the condition of the switch and therefore only
1483*67e74705SXin Li // emit the live case statement (if any) of the switch.
1484*67e74705SXin Li llvm::APSInt ConstantCondValue;
1485*67e74705SXin Li if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1486*67e74705SXin Li SmallVector<const Stmt*, 4> CaseStmts;
1487*67e74705SXin Li const SwitchCase *Case = nullptr;
1488*67e74705SXin Li if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1489*67e74705SXin Li getContext(), Case)) {
1490*67e74705SXin Li if (Case)
1491*67e74705SXin Li incrementProfileCounter(Case);
1492*67e74705SXin Li RunCleanupsScope ExecutedScope(*this);
1493*67e74705SXin Li
1494*67e74705SXin Li if (S.getInit())
1495*67e74705SXin Li EmitStmt(S.getInit());
1496*67e74705SXin Li
1497*67e74705SXin Li // Emit the condition variable if needed inside the entire cleanup scope
1498*67e74705SXin Li // used by this special case for constant folded switches.
1499*67e74705SXin Li if (S.getConditionVariable())
1500*67e74705SXin Li EmitAutoVarDecl(*S.getConditionVariable());
1501*67e74705SXin Li
1502*67e74705SXin Li // At this point, we are no longer "within" a switch instance, so
1503*67e74705SXin Li // we can temporarily enforce this to ensure that any embedded case
1504*67e74705SXin Li // statements are not emitted.
1505*67e74705SXin Li SwitchInsn = nullptr;
1506*67e74705SXin Li
1507*67e74705SXin Li // Okay, we can dead code eliminate everything except this case. Emit the
1508*67e74705SXin Li // specified series of statements and we're good.
1509*67e74705SXin Li for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1510*67e74705SXin Li EmitStmt(CaseStmts[i]);
1511*67e74705SXin Li incrementProfileCounter(&S);
1512*67e74705SXin Li
1513*67e74705SXin Li // Now we want to restore the saved switch instance so that nested
1514*67e74705SXin Li // switches continue to function properly
1515*67e74705SXin Li SwitchInsn = SavedSwitchInsn;
1516*67e74705SXin Li
1517*67e74705SXin Li return;
1518*67e74705SXin Li }
1519*67e74705SXin Li }
1520*67e74705SXin Li
1521*67e74705SXin Li JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1522*67e74705SXin Li
1523*67e74705SXin Li RunCleanupsScope ConditionScope(*this);
1524*67e74705SXin Li
1525*67e74705SXin Li if (S.getInit())
1526*67e74705SXin Li EmitStmt(S.getInit());
1527*67e74705SXin Li
1528*67e74705SXin Li if (S.getConditionVariable())
1529*67e74705SXin Li EmitAutoVarDecl(*S.getConditionVariable());
1530*67e74705SXin Li llvm::Value *CondV = EmitScalarExpr(S.getCond());
1531*67e74705SXin Li
1532*67e74705SXin Li // Create basic block to hold stuff that comes after switch
1533*67e74705SXin Li // statement. We also need to create a default block now so that
1534*67e74705SXin Li // explicit case ranges tests can have a place to jump to on
1535*67e74705SXin Li // failure.
1536*67e74705SXin Li llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1537*67e74705SXin Li SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1538*67e74705SXin Li if (PGO.haveRegionCounts()) {
1539*67e74705SXin Li // Walk the SwitchCase list to find how many there are.
1540*67e74705SXin Li uint64_t DefaultCount = 0;
1541*67e74705SXin Li unsigned NumCases = 0;
1542*67e74705SXin Li for (const SwitchCase *Case = S.getSwitchCaseList();
1543*67e74705SXin Li Case;
1544*67e74705SXin Li Case = Case->getNextSwitchCase()) {
1545*67e74705SXin Li if (isa<DefaultStmt>(Case))
1546*67e74705SXin Li DefaultCount = getProfileCount(Case);
1547*67e74705SXin Li NumCases += 1;
1548*67e74705SXin Li }
1549*67e74705SXin Li SwitchWeights = new SmallVector<uint64_t, 16>();
1550*67e74705SXin Li SwitchWeights->reserve(NumCases);
1551*67e74705SXin Li // The default needs to be first. We store the edge count, so we already
1552*67e74705SXin Li // know the right weight.
1553*67e74705SXin Li SwitchWeights->push_back(DefaultCount);
1554*67e74705SXin Li }
1555*67e74705SXin Li CaseRangeBlock = DefaultBlock;
1556*67e74705SXin Li
1557*67e74705SXin Li // Clear the insertion point to indicate we are in unreachable code.
1558*67e74705SXin Li Builder.ClearInsertionPoint();
1559*67e74705SXin Li
1560*67e74705SXin Li // All break statements jump to NextBlock. If BreakContinueStack is non-empty
1561*67e74705SXin Li // then reuse last ContinueBlock.
1562*67e74705SXin Li JumpDest OuterContinue;
1563*67e74705SXin Li if (!BreakContinueStack.empty())
1564*67e74705SXin Li OuterContinue = BreakContinueStack.back().ContinueBlock;
1565*67e74705SXin Li
1566*67e74705SXin Li BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1567*67e74705SXin Li
1568*67e74705SXin Li // Emit switch body.
1569*67e74705SXin Li EmitStmt(S.getBody());
1570*67e74705SXin Li
1571*67e74705SXin Li BreakContinueStack.pop_back();
1572*67e74705SXin Li
1573*67e74705SXin Li // Update the default block in case explicit case range tests have
1574*67e74705SXin Li // been chained on top.
1575*67e74705SXin Li SwitchInsn->setDefaultDest(CaseRangeBlock);
1576*67e74705SXin Li
1577*67e74705SXin Li // If a default was never emitted:
1578*67e74705SXin Li if (!DefaultBlock->getParent()) {
1579*67e74705SXin Li // If we have cleanups, emit the default block so that there's a
1580*67e74705SXin Li // place to jump through the cleanups from.
1581*67e74705SXin Li if (ConditionScope.requiresCleanups()) {
1582*67e74705SXin Li EmitBlock(DefaultBlock);
1583*67e74705SXin Li
1584*67e74705SXin Li // Otherwise, just forward the default block to the switch end.
1585*67e74705SXin Li } else {
1586*67e74705SXin Li DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1587*67e74705SXin Li delete DefaultBlock;
1588*67e74705SXin Li }
1589*67e74705SXin Li }
1590*67e74705SXin Li
1591*67e74705SXin Li ConditionScope.ForceCleanup();
1592*67e74705SXin Li
1593*67e74705SXin Li // Emit continuation.
1594*67e74705SXin Li EmitBlock(SwitchExit.getBlock(), true);
1595*67e74705SXin Li incrementProfileCounter(&S);
1596*67e74705SXin Li
1597*67e74705SXin Li // If the switch has a condition wrapped by __builtin_unpredictable,
1598*67e74705SXin Li // create metadata that specifies that the switch is unpredictable.
1599*67e74705SXin Li // Don't bother if not optimizing because that metadata would not be used.
1600*67e74705SXin Li auto *Call = dyn_cast<CallExpr>(S.getCond());
1601*67e74705SXin Li if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1602*67e74705SXin Li auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1603*67e74705SXin Li if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1604*67e74705SXin Li llvm::MDBuilder MDHelper(getLLVMContext());
1605*67e74705SXin Li SwitchInsn->setMetadata(llvm::LLVMContext::MD_unpredictable,
1606*67e74705SXin Li MDHelper.createUnpredictable());
1607*67e74705SXin Li }
1608*67e74705SXin Li }
1609*67e74705SXin Li
1610*67e74705SXin Li if (SwitchWeights) {
1611*67e74705SXin Li assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
1612*67e74705SXin Li "switch weights do not match switch cases");
1613*67e74705SXin Li // If there's only one jump destination there's no sense weighting it.
1614*67e74705SXin Li if (SwitchWeights->size() > 1)
1615*67e74705SXin Li SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
1616*67e74705SXin Li createProfileWeights(*SwitchWeights));
1617*67e74705SXin Li delete SwitchWeights;
1618*67e74705SXin Li }
1619*67e74705SXin Li SwitchInsn = SavedSwitchInsn;
1620*67e74705SXin Li SwitchWeights = SavedSwitchWeights;
1621*67e74705SXin Li CaseRangeBlock = SavedCRBlock;
1622*67e74705SXin Li }
1623*67e74705SXin Li
1624*67e74705SXin Li static std::string
SimplifyConstraint(const char * Constraint,const TargetInfo & Target,SmallVectorImpl<TargetInfo::ConstraintInfo> * OutCons=nullptr)1625*67e74705SXin Li SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1626*67e74705SXin Li SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) {
1627*67e74705SXin Li std::string Result;
1628*67e74705SXin Li
1629*67e74705SXin Li while (*Constraint) {
1630*67e74705SXin Li switch (*Constraint) {
1631*67e74705SXin Li default:
1632*67e74705SXin Li Result += Target.convertConstraint(Constraint);
1633*67e74705SXin Li break;
1634*67e74705SXin Li // Ignore these
1635*67e74705SXin Li case '*':
1636*67e74705SXin Li case '?':
1637*67e74705SXin Li case '!':
1638*67e74705SXin Li case '=': // Will see this and the following in mult-alt constraints.
1639*67e74705SXin Li case '+':
1640*67e74705SXin Li break;
1641*67e74705SXin Li case '#': // Ignore the rest of the constraint alternative.
1642*67e74705SXin Li while (Constraint[1] && Constraint[1] != ',')
1643*67e74705SXin Li Constraint++;
1644*67e74705SXin Li break;
1645*67e74705SXin Li case '&':
1646*67e74705SXin Li case '%':
1647*67e74705SXin Li Result += *Constraint;
1648*67e74705SXin Li while (Constraint[1] && Constraint[1] == *Constraint)
1649*67e74705SXin Li Constraint++;
1650*67e74705SXin Li break;
1651*67e74705SXin Li case ',':
1652*67e74705SXin Li Result += "|";
1653*67e74705SXin Li break;
1654*67e74705SXin Li case 'g':
1655*67e74705SXin Li Result += "imr";
1656*67e74705SXin Li break;
1657*67e74705SXin Li case '[': {
1658*67e74705SXin Li assert(OutCons &&
1659*67e74705SXin Li "Must pass output names to constraints with a symbolic name");
1660*67e74705SXin Li unsigned Index;
1661*67e74705SXin Li bool result = Target.resolveSymbolicName(Constraint, *OutCons, Index);
1662*67e74705SXin Li assert(result && "Could not resolve symbolic name"); (void)result;
1663*67e74705SXin Li Result += llvm::utostr(Index);
1664*67e74705SXin Li break;
1665*67e74705SXin Li }
1666*67e74705SXin Li }
1667*67e74705SXin Li
1668*67e74705SXin Li Constraint++;
1669*67e74705SXin Li }
1670*67e74705SXin Li
1671*67e74705SXin Li return Result;
1672*67e74705SXin Li }
1673*67e74705SXin Li
1674*67e74705SXin Li /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1675*67e74705SXin Li /// as using a particular register add that as a constraint that will be used
1676*67e74705SXin Li /// in this asm stmt.
1677*67e74705SXin Li static std::string
AddVariableConstraints(const std::string & Constraint,const Expr & AsmExpr,const TargetInfo & Target,CodeGenModule & CGM,const AsmStmt & Stmt,const bool EarlyClobber)1678*67e74705SXin Li AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1679*67e74705SXin Li const TargetInfo &Target, CodeGenModule &CGM,
1680*67e74705SXin Li const AsmStmt &Stmt, const bool EarlyClobber) {
1681*67e74705SXin Li const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1682*67e74705SXin Li if (!AsmDeclRef)
1683*67e74705SXin Li return Constraint;
1684*67e74705SXin Li const ValueDecl &Value = *AsmDeclRef->getDecl();
1685*67e74705SXin Li const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1686*67e74705SXin Li if (!Variable)
1687*67e74705SXin Li return Constraint;
1688*67e74705SXin Li if (Variable->getStorageClass() != SC_Register)
1689*67e74705SXin Li return Constraint;
1690*67e74705SXin Li AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1691*67e74705SXin Li if (!Attr)
1692*67e74705SXin Li return Constraint;
1693*67e74705SXin Li StringRef Register = Attr->getLabel();
1694*67e74705SXin Li assert(Target.isValidGCCRegisterName(Register));
1695*67e74705SXin Li // We're using validateOutputConstraint here because we only care if
1696*67e74705SXin Li // this is a register constraint.
1697*67e74705SXin Li TargetInfo::ConstraintInfo Info(Constraint, "");
1698*67e74705SXin Li if (Target.validateOutputConstraint(Info) &&
1699*67e74705SXin Li !Info.allowsRegister()) {
1700*67e74705SXin Li CGM.ErrorUnsupported(&Stmt, "__asm__");
1701*67e74705SXin Li return Constraint;
1702*67e74705SXin Li }
1703*67e74705SXin Li // Canonicalize the register here before returning it.
1704*67e74705SXin Li Register = Target.getNormalizedGCCRegisterName(Register);
1705*67e74705SXin Li return (EarlyClobber ? "&{" : "{") + Register.str() + "}";
1706*67e74705SXin Li }
1707*67e74705SXin Li
1708*67e74705SXin Li llvm::Value*
EmitAsmInputLValue(const TargetInfo::ConstraintInfo & Info,LValue InputValue,QualType InputType,std::string & ConstraintStr,SourceLocation Loc)1709*67e74705SXin Li CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
1710*67e74705SXin Li LValue InputValue, QualType InputType,
1711*67e74705SXin Li std::string &ConstraintStr,
1712*67e74705SXin Li SourceLocation Loc) {
1713*67e74705SXin Li llvm::Value *Arg;
1714*67e74705SXin Li if (Info.allowsRegister() || !Info.allowsMemory()) {
1715*67e74705SXin Li if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
1716*67e74705SXin Li Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal();
1717*67e74705SXin Li } else {
1718*67e74705SXin Li llvm::Type *Ty = ConvertType(InputType);
1719*67e74705SXin Li uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
1720*67e74705SXin Li if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
1721*67e74705SXin Li Ty = llvm::IntegerType::get(getLLVMContext(), Size);
1722*67e74705SXin Li Ty = llvm::PointerType::getUnqual(Ty);
1723*67e74705SXin Li
1724*67e74705SXin Li Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1725*67e74705SXin Li Ty));
1726*67e74705SXin Li } else {
1727*67e74705SXin Li Arg = InputValue.getPointer();
1728*67e74705SXin Li ConstraintStr += '*';
1729*67e74705SXin Li }
1730*67e74705SXin Li }
1731*67e74705SXin Li } else {
1732*67e74705SXin Li Arg = InputValue.getPointer();
1733*67e74705SXin Li ConstraintStr += '*';
1734*67e74705SXin Li }
1735*67e74705SXin Li
1736*67e74705SXin Li return Arg;
1737*67e74705SXin Li }
1738*67e74705SXin Li
EmitAsmInput(const TargetInfo::ConstraintInfo & Info,const Expr * InputExpr,std::string & ConstraintStr)1739*67e74705SXin Li llvm::Value* CodeGenFunction::EmitAsmInput(
1740*67e74705SXin Li const TargetInfo::ConstraintInfo &Info,
1741*67e74705SXin Li const Expr *InputExpr,
1742*67e74705SXin Li std::string &ConstraintStr) {
1743*67e74705SXin Li // If this can't be a register or memory, i.e., has to be a constant
1744*67e74705SXin Li // (immediate or symbolic), try to emit it as such.
1745*67e74705SXin Li if (!Info.allowsRegister() && !Info.allowsMemory()) {
1746*67e74705SXin Li llvm::APSInt Result;
1747*67e74705SXin Li if (InputExpr->EvaluateAsInt(Result, getContext()))
1748*67e74705SXin Li return llvm::ConstantInt::get(getLLVMContext(), Result);
1749*67e74705SXin Li assert(!Info.requiresImmediateConstant() &&
1750*67e74705SXin Li "Required-immediate inlineasm arg isn't constant?");
1751*67e74705SXin Li }
1752*67e74705SXin Li
1753*67e74705SXin Li if (Info.allowsRegister() || !Info.allowsMemory())
1754*67e74705SXin Li if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
1755*67e74705SXin Li return EmitScalarExpr(InputExpr);
1756*67e74705SXin Li if (InputExpr->getStmtClass() == Expr::CXXThisExprClass)
1757*67e74705SXin Li return EmitScalarExpr(InputExpr);
1758*67e74705SXin Li InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1759*67e74705SXin Li LValue Dest = EmitLValue(InputExpr);
1760*67e74705SXin Li return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
1761*67e74705SXin Li InputExpr->getExprLoc());
1762*67e74705SXin Li }
1763*67e74705SXin Li
1764*67e74705SXin Li /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
1765*67e74705SXin Li /// asm call instruction. The !srcloc MDNode contains a list of constant
1766*67e74705SXin Li /// integers which are the source locations of the start of each line in the
1767*67e74705SXin Li /// asm.
getAsmSrcLocInfo(const StringLiteral * Str,CodeGenFunction & CGF)1768*67e74705SXin Li static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1769*67e74705SXin Li CodeGenFunction &CGF) {
1770*67e74705SXin Li SmallVector<llvm::Metadata *, 8> Locs;
1771*67e74705SXin Li // Add the location of the first line to the MDNode.
1772*67e74705SXin Li Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1773*67e74705SXin Li CGF.Int32Ty, Str->getLocStart().getRawEncoding())));
1774*67e74705SXin Li StringRef StrVal = Str->getString();
1775*67e74705SXin Li if (!StrVal.empty()) {
1776*67e74705SXin Li const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1777*67e74705SXin Li const LangOptions &LangOpts = CGF.CGM.getLangOpts();
1778*67e74705SXin Li unsigned StartToken = 0;
1779*67e74705SXin Li unsigned ByteOffset = 0;
1780*67e74705SXin Li
1781*67e74705SXin Li // Add the location of the start of each subsequent line of the asm to the
1782*67e74705SXin Li // MDNode.
1783*67e74705SXin Li for (unsigned i = 0, e = StrVal.size() - 1; i != e; ++i) {
1784*67e74705SXin Li if (StrVal[i] != '\n') continue;
1785*67e74705SXin Li SourceLocation LineLoc = Str->getLocationOfByte(
1786*67e74705SXin Li i + 1, SM, LangOpts, CGF.getTarget(), &StartToken, &ByteOffset);
1787*67e74705SXin Li Locs.push_back(llvm::ConstantAsMetadata::get(
1788*67e74705SXin Li llvm::ConstantInt::get(CGF.Int32Ty, LineLoc.getRawEncoding())));
1789*67e74705SXin Li }
1790*67e74705SXin Li }
1791*67e74705SXin Li
1792*67e74705SXin Li return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
1793*67e74705SXin Li }
1794*67e74705SXin Li
EmitAsmStmt(const AsmStmt & S)1795*67e74705SXin Li void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
1796*67e74705SXin Li // Assemble the final asm string.
1797*67e74705SXin Li std::string AsmString = S.generateAsmString(getContext());
1798*67e74705SXin Li
1799*67e74705SXin Li // Get all the output and input constraints together.
1800*67e74705SXin Li SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1801*67e74705SXin Li SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1802*67e74705SXin Li
1803*67e74705SXin Li for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1804*67e74705SXin Li StringRef Name;
1805*67e74705SXin Li if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1806*67e74705SXin Li Name = GAS->getOutputName(i);
1807*67e74705SXin Li TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
1808*67e74705SXin Li bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
1809*67e74705SXin Li assert(IsValid && "Failed to parse output constraint");
1810*67e74705SXin Li OutputConstraintInfos.push_back(Info);
1811*67e74705SXin Li }
1812*67e74705SXin Li
1813*67e74705SXin Li for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1814*67e74705SXin Li StringRef Name;
1815*67e74705SXin Li if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1816*67e74705SXin Li Name = GAS->getInputName(i);
1817*67e74705SXin Li TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
1818*67e74705SXin Li bool IsValid =
1819*67e74705SXin Li getTarget().validateInputConstraint(OutputConstraintInfos, Info);
1820*67e74705SXin Li assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1821*67e74705SXin Li InputConstraintInfos.push_back(Info);
1822*67e74705SXin Li }
1823*67e74705SXin Li
1824*67e74705SXin Li std::string Constraints;
1825*67e74705SXin Li
1826*67e74705SXin Li std::vector<LValue> ResultRegDests;
1827*67e74705SXin Li std::vector<QualType> ResultRegQualTys;
1828*67e74705SXin Li std::vector<llvm::Type *> ResultRegTypes;
1829*67e74705SXin Li std::vector<llvm::Type *> ResultTruncRegTypes;
1830*67e74705SXin Li std::vector<llvm::Type *> ArgTypes;
1831*67e74705SXin Li std::vector<llvm::Value*> Args;
1832*67e74705SXin Li
1833*67e74705SXin Li // Keep track of inout constraints.
1834*67e74705SXin Li std::string InOutConstraints;
1835*67e74705SXin Li std::vector<llvm::Value*> InOutArgs;
1836*67e74705SXin Li std::vector<llvm::Type*> InOutArgTypes;
1837*67e74705SXin Li
1838*67e74705SXin Li // An inline asm can be marked readonly if it meets the following conditions:
1839*67e74705SXin Li // - it doesn't have any sideeffects
1840*67e74705SXin Li // - it doesn't clobber memory
1841*67e74705SXin Li // - it doesn't return a value by-reference
1842*67e74705SXin Li // It can be marked readnone if it doesn't have any input memory constraints
1843*67e74705SXin Li // in addition to meeting the conditions listed above.
1844*67e74705SXin Li bool ReadOnly = true, ReadNone = true;
1845*67e74705SXin Li
1846*67e74705SXin Li for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1847*67e74705SXin Li TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1848*67e74705SXin Li
1849*67e74705SXin Li // Simplify the output constraint.
1850*67e74705SXin Li std::string OutputConstraint(S.getOutputConstraint(i));
1851*67e74705SXin Li OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
1852*67e74705SXin Li getTarget());
1853*67e74705SXin Li
1854*67e74705SXin Li const Expr *OutExpr = S.getOutputExpr(i);
1855*67e74705SXin Li OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1856*67e74705SXin Li
1857*67e74705SXin Li OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
1858*67e74705SXin Li getTarget(), CGM, S,
1859*67e74705SXin Li Info.earlyClobber());
1860*67e74705SXin Li
1861*67e74705SXin Li LValue Dest = EmitLValue(OutExpr);
1862*67e74705SXin Li if (!Constraints.empty())
1863*67e74705SXin Li Constraints += ',';
1864*67e74705SXin Li
1865*67e74705SXin Li // If this is a register output, then make the inline asm return it
1866*67e74705SXin Li // by-value. If this is a memory result, return the value by-reference.
1867*67e74705SXin Li if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
1868*67e74705SXin Li Constraints += "=" + OutputConstraint;
1869*67e74705SXin Li ResultRegQualTys.push_back(OutExpr->getType());
1870*67e74705SXin Li ResultRegDests.push_back(Dest);
1871*67e74705SXin Li ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1872*67e74705SXin Li ResultTruncRegTypes.push_back(ResultRegTypes.back());
1873*67e74705SXin Li
1874*67e74705SXin Li // If this output is tied to an input, and if the input is larger, then
1875*67e74705SXin Li // we need to set the actual result type of the inline asm node to be the
1876*67e74705SXin Li // same as the input type.
1877*67e74705SXin Li if (Info.hasMatchingInput()) {
1878*67e74705SXin Li unsigned InputNo;
1879*67e74705SXin Li for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1880*67e74705SXin Li TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1881*67e74705SXin Li if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1882*67e74705SXin Li break;
1883*67e74705SXin Li }
1884*67e74705SXin Li assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1885*67e74705SXin Li
1886*67e74705SXin Li QualType InputTy = S.getInputExpr(InputNo)->getType();
1887*67e74705SXin Li QualType OutputType = OutExpr->getType();
1888*67e74705SXin Li
1889*67e74705SXin Li uint64_t InputSize = getContext().getTypeSize(InputTy);
1890*67e74705SXin Li if (getContext().getTypeSize(OutputType) < InputSize) {
1891*67e74705SXin Li // Form the asm to return the value as a larger integer or fp type.
1892*67e74705SXin Li ResultRegTypes.back() = ConvertType(InputTy);
1893*67e74705SXin Li }
1894*67e74705SXin Li }
1895*67e74705SXin Li if (llvm::Type* AdjTy =
1896*67e74705SXin Li getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1897*67e74705SXin Li ResultRegTypes.back()))
1898*67e74705SXin Li ResultRegTypes.back() = AdjTy;
1899*67e74705SXin Li else {
1900*67e74705SXin Li CGM.getDiags().Report(S.getAsmLoc(),
1901*67e74705SXin Li diag::err_asm_invalid_type_in_input)
1902*67e74705SXin Li << OutExpr->getType() << OutputConstraint;
1903*67e74705SXin Li }
1904*67e74705SXin Li } else {
1905*67e74705SXin Li ArgTypes.push_back(Dest.getAddress().getType());
1906*67e74705SXin Li Args.push_back(Dest.getPointer());
1907*67e74705SXin Li Constraints += "=*";
1908*67e74705SXin Li Constraints += OutputConstraint;
1909*67e74705SXin Li ReadOnly = ReadNone = false;
1910*67e74705SXin Li }
1911*67e74705SXin Li
1912*67e74705SXin Li if (Info.isReadWrite()) {
1913*67e74705SXin Li InOutConstraints += ',';
1914*67e74705SXin Li
1915*67e74705SXin Li const Expr *InputExpr = S.getOutputExpr(i);
1916*67e74705SXin Li llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
1917*67e74705SXin Li InOutConstraints,
1918*67e74705SXin Li InputExpr->getExprLoc());
1919*67e74705SXin Li
1920*67e74705SXin Li if (llvm::Type* AdjTy =
1921*67e74705SXin Li getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1922*67e74705SXin Li Arg->getType()))
1923*67e74705SXin Li Arg = Builder.CreateBitCast(Arg, AdjTy);
1924*67e74705SXin Li
1925*67e74705SXin Li if (Info.allowsRegister())
1926*67e74705SXin Li InOutConstraints += llvm::utostr(i);
1927*67e74705SXin Li else
1928*67e74705SXin Li InOutConstraints += OutputConstraint;
1929*67e74705SXin Li
1930*67e74705SXin Li InOutArgTypes.push_back(Arg->getType());
1931*67e74705SXin Li InOutArgs.push_back(Arg);
1932*67e74705SXin Li }
1933*67e74705SXin Li }
1934*67e74705SXin Li
1935*67e74705SXin Li // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
1936*67e74705SXin Li // to the return value slot. Only do this when returning in registers.
1937*67e74705SXin Li if (isa<MSAsmStmt>(&S)) {
1938*67e74705SXin Li const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
1939*67e74705SXin Li if (RetAI.isDirect() || RetAI.isExtend()) {
1940*67e74705SXin Li // Make a fake lvalue for the return value slot.
1941*67e74705SXin Li LValue ReturnSlot = MakeAddrLValue(ReturnValue, FnRetTy);
1942*67e74705SXin Li CGM.getTargetCodeGenInfo().addReturnRegisterOutputs(
1943*67e74705SXin Li *this, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
1944*67e74705SXin Li ResultRegDests, AsmString, S.getNumOutputs());
1945*67e74705SXin Li SawAsmBlock = true;
1946*67e74705SXin Li }
1947*67e74705SXin Li }
1948*67e74705SXin Li
1949*67e74705SXin Li for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1950*67e74705SXin Li const Expr *InputExpr = S.getInputExpr(i);
1951*67e74705SXin Li
1952*67e74705SXin Li TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1953*67e74705SXin Li
1954*67e74705SXin Li if (Info.allowsMemory())
1955*67e74705SXin Li ReadNone = false;
1956*67e74705SXin Li
1957*67e74705SXin Li if (!Constraints.empty())
1958*67e74705SXin Li Constraints += ',';
1959*67e74705SXin Li
1960*67e74705SXin Li // Simplify the input constraint.
1961*67e74705SXin Li std::string InputConstraint(S.getInputConstraint(i));
1962*67e74705SXin Li InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
1963*67e74705SXin Li &OutputConstraintInfos);
1964*67e74705SXin Li
1965*67e74705SXin Li InputConstraint = AddVariableConstraints(
1966*67e74705SXin Li InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
1967*67e74705SXin Li getTarget(), CGM, S, false /* No EarlyClobber */);
1968*67e74705SXin Li
1969*67e74705SXin Li llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
1970*67e74705SXin Li
1971*67e74705SXin Li // If this input argument is tied to a larger output result, extend the
1972*67e74705SXin Li // input to be the same size as the output. The LLVM backend wants to see
1973*67e74705SXin Li // the input and output of a matching constraint be the same size. Note
1974*67e74705SXin Li // that GCC does not define what the top bits are here. We use zext because
1975*67e74705SXin Li // that is usually cheaper, but LLVM IR should really get an anyext someday.
1976*67e74705SXin Li if (Info.hasTiedOperand()) {
1977*67e74705SXin Li unsigned Output = Info.getTiedOperand();
1978*67e74705SXin Li QualType OutputType = S.getOutputExpr(Output)->getType();
1979*67e74705SXin Li QualType InputTy = InputExpr->getType();
1980*67e74705SXin Li
1981*67e74705SXin Li if (getContext().getTypeSize(OutputType) >
1982*67e74705SXin Li getContext().getTypeSize(InputTy)) {
1983*67e74705SXin Li // Use ptrtoint as appropriate so that we can do our extension.
1984*67e74705SXin Li if (isa<llvm::PointerType>(Arg->getType()))
1985*67e74705SXin Li Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
1986*67e74705SXin Li llvm::Type *OutputTy = ConvertType(OutputType);
1987*67e74705SXin Li if (isa<llvm::IntegerType>(OutputTy))
1988*67e74705SXin Li Arg = Builder.CreateZExt(Arg, OutputTy);
1989*67e74705SXin Li else if (isa<llvm::PointerType>(OutputTy))
1990*67e74705SXin Li Arg = Builder.CreateZExt(Arg, IntPtrTy);
1991*67e74705SXin Li else {
1992*67e74705SXin Li assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
1993*67e74705SXin Li Arg = Builder.CreateFPExt(Arg, OutputTy);
1994*67e74705SXin Li }
1995*67e74705SXin Li }
1996*67e74705SXin Li }
1997*67e74705SXin Li if (llvm::Type* AdjTy =
1998*67e74705SXin Li getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
1999*67e74705SXin Li Arg->getType()))
2000*67e74705SXin Li Arg = Builder.CreateBitCast(Arg, AdjTy);
2001*67e74705SXin Li else
2002*67e74705SXin Li CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
2003*67e74705SXin Li << InputExpr->getType() << InputConstraint;
2004*67e74705SXin Li
2005*67e74705SXin Li ArgTypes.push_back(Arg->getType());
2006*67e74705SXin Li Args.push_back(Arg);
2007*67e74705SXin Li Constraints += InputConstraint;
2008*67e74705SXin Li }
2009*67e74705SXin Li
2010*67e74705SXin Li // Append the "input" part of inout constraints last.
2011*67e74705SXin Li for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
2012*67e74705SXin Li ArgTypes.push_back(InOutArgTypes[i]);
2013*67e74705SXin Li Args.push_back(InOutArgs[i]);
2014*67e74705SXin Li }
2015*67e74705SXin Li Constraints += InOutConstraints;
2016*67e74705SXin Li
2017*67e74705SXin Li // Clobbers
2018*67e74705SXin Li for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
2019*67e74705SXin Li StringRef Clobber = S.getClobber(i);
2020*67e74705SXin Li
2021*67e74705SXin Li if (Clobber == "memory")
2022*67e74705SXin Li ReadOnly = ReadNone = false;
2023*67e74705SXin Li else if (Clobber != "cc")
2024*67e74705SXin Li Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
2025*67e74705SXin Li
2026*67e74705SXin Li if (!Constraints.empty())
2027*67e74705SXin Li Constraints += ',';
2028*67e74705SXin Li
2029*67e74705SXin Li Constraints += "~{";
2030*67e74705SXin Li Constraints += Clobber;
2031*67e74705SXin Li Constraints += '}';
2032*67e74705SXin Li }
2033*67e74705SXin Li
2034*67e74705SXin Li // Add machine specific clobbers
2035*67e74705SXin Li std::string MachineClobbers = getTarget().getClobbers();
2036*67e74705SXin Li if (!MachineClobbers.empty()) {
2037*67e74705SXin Li if (!Constraints.empty())
2038*67e74705SXin Li Constraints += ',';
2039*67e74705SXin Li Constraints += MachineClobbers;
2040*67e74705SXin Li }
2041*67e74705SXin Li
2042*67e74705SXin Li llvm::Type *ResultType;
2043*67e74705SXin Li if (ResultRegTypes.empty())
2044*67e74705SXin Li ResultType = VoidTy;
2045*67e74705SXin Li else if (ResultRegTypes.size() == 1)
2046*67e74705SXin Li ResultType = ResultRegTypes[0];
2047*67e74705SXin Li else
2048*67e74705SXin Li ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
2049*67e74705SXin Li
2050*67e74705SXin Li llvm::FunctionType *FTy =
2051*67e74705SXin Li llvm::FunctionType::get(ResultType, ArgTypes, false);
2052*67e74705SXin Li
2053*67e74705SXin Li bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
2054*67e74705SXin Li llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
2055*67e74705SXin Li llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
2056*67e74705SXin Li llvm::InlineAsm *IA =
2057*67e74705SXin Li llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
2058*67e74705SXin Li /* IsAlignStack */ false, AsmDialect);
2059*67e74705SXin Li llvm::CallInst *Result = Builder.CreateCall(IA, Args);
2060*67e74705SXin Li Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2061*67e74705SXin Li llvm::Attribute::NoUnwind);
2062*67e74705SXin Li
2063*67e74705SXin Li if (isa<MSAsmStmt>(&S)) {
2064*67e74705SXin Li // If the assembly contains any labels, mark the call noduplicate to prevent
2065*67e74705SXin Li // defining the same ASM label twice (PR23715). This is pretty hacky, but it
2066*67e74705SXin Li // works.
2067*67e74705SXin Li if (AsmString.find("__MSASMLABEL_") != std::string::npos)
2068*67e74705SXin Li Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2069*67e74705SXin Li llvm::Attribute::NoDuplicate);
2070*67e74705SXin Li }
2071*67e74705SXin Li
2072*67e74705SXin Li // Attach readnone and readonly attributes.
2073*67e74705SXin Li if (!HasSideEffect) {
2074*67e74705SXin Li if (ReadNone)
2075*67e74705SXin Li Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2076*67e74705SXin Li llvm::Attribute::ReadNone);
2077*67e74705SXin Li else if (ReadOnly)
2078*67e74705SXin Li Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2079*67e74705SXin Li llvm::Attribute::ReadOnly);
2080*67e74705SXin Li }
2081*67e74705SXin Li
2082*67e74705SXin Li // Slap the source location of the inline asm into a !srcloc metadata on the
2083*67e74705SXin Li // call.
2084*67e74705SXin Li if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S)) {
2085*67e74705SXin Li Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(),
2086*67e74705SXin Li *this));
2087*67e74705SXin Li } else {
2088*67e74705SXin Li // At least put the line number on MS inline asm blobs.
2089*67e74705SXin Li auto Loc = llvm::ConstantInt::get(Int32Ty, S.getAsmLoc().getRawEncoding());
2090*67e74705SXin Li Result->setMetadata("srcloc",
2091*67e74705SXin Li llvm::MDNode::get(getLLVMContext(),
2092*67e74705SXin Li llvm::ConstantAsMetadata::get(Loc)));
2093*67e74705SXin Li }
2094*67e74705SXin Li
2095*67e74705SXin Li if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
2096*67e74705SXin Li // Conservatively, mark all inline asm blocks in CUDA as convergent
2097*67e74705SXin Li // (meaning, they may call an intrinsically convergent op, such as bar.sync,
2098*67e74705SXin Li // and so can't have certain optimizations applied around them).
2099*67e74705SXin Li Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2100*67e74705SXin Li llvm::Attribute::Convergent);
2101*67e74705SXin Li }
2102*67e74705SXin Li
2103*67e74705SXin Li // Extract all of the register value results from the asm.
2104*67e74705SXin Li std::vector<llvm::Value*> RegResults;
2105*67e74705SXin Li if (ResultRegTypes.size() == 1) {
2106*67e74705SXin Li RegResults.push_back(Result);
2107*67e74705SXin Li } else {
2108*67e74705SXin Li for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
2109*67e74705SXin Li llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
2110*67e74705SXin Li RegResults.push_back(Tmp);
2111*67e74705SXin Li }
2112*67e74705SXin Li }
2113*67e74705SXin Li
2114*67e74705SXin Li assert(RegResults.size() == ResultRegTypes.size());
2115*67e74705SXin Li assert(RegResults.size() == ResultTruncRegTypes.size());
2116*67e74705SXin Li assert(RegResults.size() == ResultRegDests.size());
2117*67e74705SXin Li for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
2118*67e74705SXin Li llvm::Value *Tmp = RegResults[i];
2119*67e74705SXin Li
2120*67e74705SXin Li // If the result type of the LLVM IR asm doesn't match the result type of
2121*67e74705SXin Li // the expression, do the conversion.
2122*67e74705SXin Li if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
2123*67e74705SXin Li llvm::Type *TruncTy = ResultTruncRegTypes[i];
2124*67e74705SXin Li
2125*67e74705SXin Li // Truncate the integer result to the right size, note that TruncTy can be
2126*67e74705SXin Li // a pointer.
2127*67e74705SXin Li if (TruncTy->isFloatingPointTy())
2128*67e74705SXin Li Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
2129*67e74705SXin Li else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
2130*67e74705SXin Li uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
2131*67e74705SXin Li Tmp = Builder.CreateTrunc(Tmp,
2132*67e74705SXin Li llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
2133*67e74705SXin Li Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
2134*67e74705SXin Li } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
2135*67e74705SXin Li uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
2136*67e74705SXin Li Tmp = Builder.CreatePtrToInt(Tmp,
2137*67e74705SXin Li llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
2138*67e74705SXin Li Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2139*67e74705SXin Li } else if (TruncTy->isIntegerTy()) {
2140*67e74705SXin Li Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2141*67e74705SXin Li } else if (TruncTy->isVectorTy()) {
2142*67e74705SXin Li Tmp = Builder.CreateBitCast(Tmp, TruncTy);
2143*67e74705SXin Li }
2144*67e74705SXin Li }
2145*67e74705SXin Li
2146*67e74705SXin Li EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
2147*67e74705SXin Li }
2148*67e74705SXin Li }
2149*67e74705SXin Li
InitCapturedStruct(const CapturedStmt & S)2150*67e74705SXin Li LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) {
2151*67e74705SXin Li const RecordDecl *RD = S.getCapturedRecordDecl();
2152*67e74705SXin Li QualType RecordTy = getContext().getRecordType(RD);
2153*67e74705SXin Li
2154*67e74705SXin Li // Initialize the captured struct.
2155*67e74705SXin Li LValue SlotLV =
2156*67e74705SXin Li MakeAddrLValue(CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
2157*67e74705SXin Li
2158*67e74705SXin Li RecordDecl::field_iterator CurField = RD->field_begin();
2159*67e74705SXin Li for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
2160*67e74705SXin Li E = S.capture_init_end();
2161*67e74705SXin Li I != E; ++I, ++CurField) {
2162*67e74705SXin Li LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
2163*67e74705SXin Li if (CurField->hasCapturedVLAType()) {
2164*67e74705SXin Li auto VAT = CurField->getCapturedVLAType();
2165*67e74705SXin Li EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2166*67e74705SXin Li } else {
2167*67e74705SXin Li EmitInitializerForField(*CurField, LV, *I, None);
2168*67e74705SXin Li }
2169*67e74705SXin Li }
2170*67e74705SXin Li
2171*67e74705SXin Li return SlotLV;
2172*67e74705SXin Li }
2173*67e74705SXin Li
2174*67e74705SXin Li /// Generate an outlined function for the body of a CapturedStmt, store any
2175*67e74705SXin Li /// captured variables into the captured struct, and call the outlined function.
2176*67e74705SXin Li llvm::Function *
EmitCapturedStmt(const CapturedStmt & S,CapturedRegionKind K)2177*67e74705SXin Li CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
2178*67e74705SXin Li LValue CapStruct = InitCapturedStruct(S);
2179*67e74705SXin Li
2180*67e74705SXin Li // Emit the CapturedDecl
2181*67e74705SXin Li CodeGenFunction CGF(CGM, true);
2182*67e74705SXin Li CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K));
2183*67e74705SXin Li llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
2184*67e74705SXin Li delete CGF.CapturedStmtInfo;
2185*67e74705SXin Li
2186*67e74705SXin Li // Emit call to the helper function.
2187*67e74705SXin Li EmitCallOrInvoke(F, CapStruct.getPointer());
2188*67e74705SXin Li
2189*67e74705SXin Li return F;
2190*67e74705SXin Li }
2191*67e74705SXin Li
GenerateCapturedStmtArgument(const CapturedStmt & S)2192*67e74705SXin Li Address CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) {
2193*67e74705SXin Li LValue CapStruct = InitCapturedStruct(S);
2194*67e74705SXin Li return CapStruct.getAddress();
2195*67e74705SXin Li }
2196*67e74705SXin Li
2197*67e74705SXin Li /// Creates the outlined function for a CapturedStmt.
2198*67e74705SXin Li llvm::Function *
GenerateCapturedStmtFunction(const CapturedStmt & S)2199*67e74705SXin Li CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) {
2200*67e74705SXin Li assert(CapturedStmtInfo &&
2201*67e74705SXin Li "CapturedStmtInfo should be set when generating the captured function");
2202*67e74705SXin Li const CapturedDecl *CD = S.getCapturedDecl();
2203*67e74705SXin Li const RecordDecl *RD = S.getCapturedRecordDecl();
2204*67e74705SXin Li SourceLocation Loc = S.getLocStart();
2205*67e74705SXin Li assert(CD->hasBody() && "missing CapturedDecl body");
2206*67e74705SXin Li
2207*67e74705SXin Li // Build the argument list.
2208*67e74705SXin Li ASTContext &Ctx = CGM.getContext();
2209*67e74705SXin Li FunctionArgList Args;
2210*67e74705SXin Li Args.append(CD->param_begin(), CD->param_end());
2211*67e74705SXin Li
2212*67e74705SXin Li // Create the function declaration.
2213*67e74705SXin Li FunctionType::ExtInfo ExtInfo;
2214*67e74705SXin Li const CGFunctionInfo &FuncInfo =
2215*67e74705SXin Li CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
2216*67e74705SXin Li llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
2217*67e74705SXin Li
2218*67e74705SXin Li llvm::Function *F =
2219*67e74705SXin Li llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
2220*67e74705SXin Li CapturedStmtInfo->getHelperName(), &CGM.getModule());
2221*67e74705SXin Li CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
2222*67e74705SXin Li if (CD->isNothrow())
2223*67e74705SXin Li F->addFnAttr(llvm::Attribute::NoUnwind);
2224*67e74705SXin Li
2225*67e74705SXin Li // Generate the function.
2226*67e74705SXin Li StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args,
2227*67e74705SXin Li CD->getLocation(),
2228*67e74705SXin Li CD->getBody()->getLocStart());
2229*67e74705SXin Li // Set the context parameter in CapturedStmtInfo.
2230*67e74705SXin Li Address DeclPtr = GetAddrOfLocalVar(CD->getContextParam());
2231*67e74705SXin Li CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
2232*67e74705SXin Li
2233*67e74705SXin Li // Initialize variable-length arrays.
2234*67e74705SXin Li LValue Base = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(),
2235*67e74705SXin Li Ctx.getTagDeclType(RD));
2236*67e74705SXin Li for (auto *FD : RD->fields()) {
2237*67e74705SXin Li if (FD->hasCapturedVLAType()) {
2238*67e74705SXin Li auto *ExprArg = EmitLoadOfLValue(EmitLValueForField(Base, FD),
2239*67e74705SXin Li S.getLocStart()).getScalarVal();
2240*67e74705SXin Li auto VAT = FD->getCapturedVLAType();
2241*67e74705SXin Li VLASizeMap[VAT->getSizeExpr()] = ExprArg;
2242*67e74705SXin Li }
2243*67e74705SXin Li }
2244*67e74705SXin Li
2245*67e74705SXin Li // If 'this' is captured, load it into CXXThisValue.
2246*67e74705SXin Li if (CapturedStmtInfo->isCXXThisExprCaptured()) {
2247*67e74705SXin Li FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
2248*67e74705SXin Li LValue ThisLValue = EmitLValueForField(Base, FD);
2249*67e74705SXin Li CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
2250*67e74705SXin Li }
2251*67e74705SXin Li
2252*67e74705SXin Li PGO.assignRegionCounters(GlobalDecl(CD), F);
2253*67e74705SXin Li CapturedStmtInfo->EmitBody(*this, CD->getBody());
2254*67e74705SXin Li FinishFunction(CD->getBodyRBrace());
2255*67e74705SXin Li
2256*67e74705SXin Li return F;
2257*67e74705SXin Li }
2258