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