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