blob: 131e2b553c31e878c3f34f3dea23ceaf648f31ef [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Stmt nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "clang/AST/AST.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Function.h"
19using namespace clang;
20using namespace CodeGen;
21
22//===----------------------------------------------------------------------===//
23// Statement Emission
24//===----------------------------------------------------------------------===//
25
26void CodeGenFunction::EmitStmt(const Stmt *S) {
27 assert(S && "Null statement?");
28
29 switch (S->getStmtClass()) {
30 default:
31 // Must be an expression in a stmt context. Emit the value and ignore the
32 // result.
33 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner883f6a72007-08-11 00:04:45 +000034 if (hasAggregateLLVMType(E->getType()))
35 EmitAggExpr(E, 0, false); // Emit an aggregate, ignoring the result.
36 else
37 EmitExpr(E);
Reid Spencer5f016e22007-07-11 17:01:13 +000038 } else {
39 printf("Unimplemented stmt!\n");
40 S->dump();
41 }
42 break;
43 case Stmt::NullStmtClass: break;
44 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
45 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
46 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
47
48 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
49 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
50 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
51 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
52
53 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
54 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Chris Lattnerda138702007-07-16 21:28:45 +000055
56 case Stmt::BreakStmtClass: EmitBreakStmt(); break;
57 case Stmt::ContinueStmtClass: EmitContinueStmt(); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000058 }
59}
60
61void CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S) {
62 // FIXME: handle vla's etc.
63
64 for (CompoundStmt::const_body_iterator I = S.body_begin(), E = S.body_end();
65 I != E; ++I)
66 EmitStmt(*I);
67}
68
69void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
70 // Emit a branch from this block to the next one if this was a real block. If
71 // this was just a fall-through block after a terminator, don't emit it.
72 llvm::BasicBlock *LastBB = Builder.GetInsertBlock();
73
74 if (LastBB->getTerminator()) {
75 // If the previous block is already terminated, don't touch it.
76 } else if (LastBB->empty() && LastBB->getValueName() == 0) {
77 // If the last block was an empty placeholder, remove it now.
78 // TODO: cache and reuse these.
79 Builder.GetInsertBlock()->eraseFromParent();
80 } else {
81 // Otherwise, create a fall-through branch.
82 Builder.CreateBr(BB);
83 }
84 CurFn->getBasicBlockList().push_back(BB);
85 Builder.SetInsertPoint(BB);
86}
87
88void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
89 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
90
91 EmitBlock(NextBB);
92 EmitStmt(S.getSubStmt());
93}
94
95void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
96 Builder.CreateBr(getBasicBlockForLabel(S.getLabel()));
97
98 // Emit a block after the branch so that dead code after a goto has some place
99 // to go.
100 Builder.SetInsertPoint(new llvm::BasicBlock("", CurFn));
101}
102
103void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
104 // C99 6.8.4.1: The first substatement is executed if the expression compares
105 // unequal to 0. The condition must be a scalar type.
106 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
107
108 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("ifend");
109 llvm::BasicBlock *ThenBlock = new llvm::BasicBlock("ifthen");
110 llvm::BasicBlock *ElseBlock = ContBlock;
111
112 if (S.getElse())
113 ElseBlock = new llvm::BasicBlock("ifelse");
114
115 // Insert the conditional branch.
116 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
117
118 // Emit the 'then' code.
119 EmitBlock(ThenBlock);
120 EmitStmt(S.getThen());
121 Builder.CreateBr(ContBlock);
122
123 // Emit the 'else' code if present.
124 if (const Stmt *Else = S.getElse()) {
125 EmitBlock(ElseBlock);
126 EmitStmt(Else);
127 Builder.CreateBr(ContBlock);
128 }
129
130 // Emit the continuation block for code after the if.
131 EmitBlock(ContBlock);
132}
133
134void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000135 // Emit the header for the loop, insert it, which will create an uncond br to
136 // it.
137 llvm::BasicBlock *LoopHeader = new llvm::BasicBlock("whilecond");
138 EmitBlock(LoopHeader);
139
140 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
141 // of the controlling expression takes place before each execution of the loop
142 // body.
143 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
144
145 // TODO: while(1) is common, avoid extra exit blocks, etc. Be sure
146 // to correctly handle break/continue though.
147
148 // Create an exit block for when the condition fails, create a block for the
149 // body of the loop.
150 llvm::BasicBlock *ExitBlock = new llvm::BasicBlock("whileexit");
151 llvm::BasicBlock *LoopBody = new llvm::BasicBlock("whilebody");
152
153 // As long as the condition is true, go to the loop body.
154 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000155
156 // Store the blocks to use for break and continue.
157 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000158
159 // Emit the loop body.
160 EmitBlock(LoopBody);
161 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000162
163 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000164
165 // Cycle to the condition.
166 Builder.CreateBr(LoopHeader);
167
168 // Emit the exit block.
169 EmitBlock(ExitBlock);
170}
171
172void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000173 // TODO: "do {} while (0)" is common in macros, avoid extra blocks. Be sure
174 // to correctly handle break/continue though.
175
176 // Emit the body for the loop, insert it, which will create an uncond br to
177 // it.
178 llvm::BasicBlock *LoopBody = new llvm::BasicBlock("dobody");
179 llvm::BasicBlock *AfterDo = new llvm::BasicBlock("afterdo");
180 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000181
182 llvm::BasicBlock *DoCond = new llvm::BasicBlock("docond");
183
184 // Store the blocks to use for break and continue.
185 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000186
187 // Emit the body of the loop into the block.
188 EmitStmt(S.getBody());
189
Chris Lattnerda138702007-07-16 21:28:45 +0000190 BreakContinueStack.pop_back();
191
192 EmitBlock(DoCond);
193
Reid Spencer5f016e22007-07-11 17:01:13 +0000194 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
195 // after each execution of the loop body."
196
197 // Evaluate the conditional in the while header.
198 // C99 6.8.5p2/p4: The first substatement is executed if the expression
199 // compares unequal to 0. The condition must be a scalar type.
200 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
201
202 // As long as the condition is true, iterate the loop.
203 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
204
205 // Emit the exit block.
206 EmitBlock(AfterDo);
207}
208
209void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000210 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
211 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000212 // TODO: We could keep track of whether the loop body contains any
213 // break/continue statements and not create unnecessary blocks (like
214 // "afterfor" for a condless loop) if it doesn't.
215
Reid Spencer5f016e22007-07-11 17:01:13 +0000216 // Evaluate the first part before the loop.
217 if (S.getInit())
218 EmitStmt(S.getInit());
219
220 // Start the loop with a block that tests the condition.
221 llvm::BasicBlock *CondBlock = new llvm::BasicBlock("forcond");
Chris Lattnerda138702007-07-16 21:28:45 +0000222 llvm::BasicBlock *AfterFor = new llvm::BasicBlock("afterfor");
223
Reid Spencer5f016e22007-07-11 17:01:13 +0000224 EmitBlock(CondBlock);
225
226 // Evaluate the condition if present. If not, treat it as a non-zero-constant
227 // according to 6.8.5.3p2, aka, true.
228 if (S.getCond()) {
229 // C99 6.8.5p2/p4: The first substatement is executed if the expression
230 // compares unequal to 0. The condition must be a scalar type.
231 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
232
233 // As long as the condition is true, iterate the loop.
234 llvm::BasicBlock *ForBody = new llvm::BasicBlock("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
236 EmitBlock(ForBody);
237 } else {
238 // Treat it as a non-zero constant. Don't even create a new block for the
239 // body, just fall into it.
240 }
241
Chris Lattnerda138702007-07-16 21:28:45 +0000242 // If the for loop doesn't have an increment we can just use the
243 // condition as the continue block.
244 llvm::BasicBlock *ContinueBlock;
245 if (S.getInc())
246 ContinueBlock = new llvm::BasicBlock("forinc");
247 else
248 ContinueBlock = CondBlock;
249
250 // Store the blocks to use for break and continue.
251 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
252
Reid Spencer5f016e22007-07-11 17:01:13 +0000253 // If the condition is true, execute the body of the for stmt.
254 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000255
256 BreakContinueStack.pop_back();
257
258 if (S.getInc())
259 EmitBlock(ContinueBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000260
261 // If there is an increment, emit it next.
262 if (S.getInc())
Chris Lattner883f6a72007-08-11 00:04:45 +0000263 EmitStmt(S.getInc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000264
265 // Finally, branch back up to the condition for the next iteration.
266 Builder.CreateBr(CondBlock);
267
Chris Lattnerda138702007-07-16 21:28:45 +0000268 // Emit the fall-through block.
269 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000270}
271
272/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
273/// if the function returns void, or may be missing one if the function returns
274/// non-void. Fun stuff :).
275void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
276 RValue RetVal;
277
278 // Emit the result value, even if unused, to evalute the side effects.
279 const Expr *RV = S.getRetValue();
Chris Lattner883f6a72007-08-11 00:04:45 +0000280 // FIXME: Handle return of an aggregate!
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 if (RV)
282 RetVal = EmitExpr(RV);
Chris Lattnera80b0ba2007-07-13 20:07:11 +0000283 else // Silence a bogus GCC warning.
284 RetVal = RValue::get(0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000285
286 QualType FnRetTy = CurFuncDecl->getType().getCanonicalType();
287 FnRetTy = cast<FunctionType>(FnRetTy)->getResultType();
288
289 if (FnRetTy->isVoidType()) {
290 // If the function returns void, emit ret void, and ignore the retval.
291 Builder.CreateRetVoid();
292 } else if (RV == 0) {
293 // "return;" in a function that returns a value.
294 const llvm::Type *RetTy = CurFn->getFunctionType()->getReturnType();
295 if (RetTy == llvm::Type::VoidTy)
296 Builder.CreateRetVoid(); // struct return etc.
297 else
298 Builder.CreateRet(llvm::UndefValue::get(RetTy));
299 } else {
300 // Do implicit conversions to the returned type.
301 RetVal = EmitConversion(RetVal, RV->getType(), FnRetTy);
302
303 if (RetVal.isScalar()) {
304 Builder.CreateRet(RetVal.getVal());
305 } else {
306 llvm::Value *SRetPtr = CurFn->arg_begin();
307 EmitStoreThroughLValue(RetVal, LValue::MakeAddr(SRetPtr), FnRetTy);
308 }
309 }
310
311 // Emit a block after the branch so that dead code after a return has some
312 // place to go.
313 EmitBlock(new llvm::BasicBlock());
314}
315
316void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
317 for (const Decl *Decl = S.getDecl(); Decl; Decl = Decl->getNextDeclarator())
318 EmitDecl(*Decl);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000319}
Chris Lattnerda138702007-07-16 21:28:45 +0000320
321void CodeGenFunction::EmitBreakStmt() {
322 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
323
324 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
325 Builder.CreateBr(Block);
326 EmitBlock(new llvm::BasicBlock());
327}
328
329void CodeGenFunction::EmitContinueStmt() {
330 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
331
332 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
333 Builder.CreateBr(Block);
334 EmitBlock(new llvm::BasicBlock());
335}