blob: c128abcca9ccaa44db46ff7512be9b532be1245a [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 Lattnerb6ef18a2007-08-21 05:54:00 +000034 if (E->getType()->isComplexType()) {
35 EmitComplexExpr(E);
36 } else if (hasAggregateLLVMType(E->getType()))
Chris Lattner883f6a72007-08-11 00:04:45 +000037 EmitAggExpr(E, 0, false); // Emit an aggregate, ignoring the result.
38 else
39 EmitExpr(E);
Reid Spencer5f016e22007-07-11 17:01:13 +000040 } else {
41 printf("Unimplemented stmt!\n");
42 S->dump();
43 }
44 break;
45 case Stmt::NullStmtClass: break;
46 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
47 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
48 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
49
50 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
51 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
52 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
53 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
54
55 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
56 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Chris Lattnerda138702007-07-16 21:28:45 +000057
58 case Stmt::BreakStmtClass: EmitBreakStmt(); break;
59 case Stmt::ContinueStmtClass: EmitContinueStmt(); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000060 }
61}
62
63void CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S) {
64 // FIXME: handle vla's etc.
65
66 for (CompoundStmt::const_body_iterator I = S.body_begin(), E = S.body_end();
67 I != E; ++I)
68 EmitStmt(*I);
69}
70
71void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
72 // Emit a branch from this block to the next one if this was a real block. If
73 // this was just a fall-through block after a terminator, don't emit it.
74 llvm::BasicBlock *LastBB = Builder.GetInsertBlock();
75
76 if (LastBB->getTerminator()) {
77 // If the previous block is already terminated, don't touch it.
78 } else if (LastBB->empty() && LastBB->getValueName() == 0) {
79 // If the last block was an empty placeholder, remove it now.
80 // TODO: cache and reuse these.
81 Builder.GetInsertBlock()->eraseFromParent();
82 } else {
83 // Otherwise, create a fall-through branch.
84 Builder.CreateBr(BB);
85 }
86 CurFn->getBasicBlockList().push_back(BB);
87 Builder.SetInsertPoint(BB);
88}
89
90void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
91 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
92
93 EmitBlock(NextBB);
94 EmitStmt(S.getSubStmt());
95}
96
97void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
98 Builder.CreateBr(getBasicBlockForLabel(S.getLabel()));
99
100 // Emit a block after the branch so that dead code after a goto has some place
101 // to go.
102 Builder.SetInsertPoint(new llvm::BasicBlock("", CurFn));
103}
104
105void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
106 // C99 6.8.4.1: The first substatement is executed if the expression compares
107 // unequal to 0. The condition must be a scalar type.
108 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
109
110 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("ifend");
111 llvm::BasicBlock *ThenBlock = new llvm::BasicBlock("ifthen");
112 llvm::BasicBlock *ElseBlock = ContBlock;
113
114 if (S.getElse())
115 ElseBlock = new llvm::BasicBlock("ifelse");
116
117 // Insert the conditional branch.
118 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
119
120 // Emit the 'then' code.
121 EmitBlock(ThenBlock);
122 EmitStmt(S.getThen());
123 Builder.CreateBr(ContBlock);
124
125 // Emit the 'else' code if present.
126 if (const Stmt *Else = S.getElse()) {
127 EmitBlock(ElseBlock);
128 EmitStmt(Else);
129 Builder.CreateBr(ContBlock);
130 }
131
132 // Emit the continuation block for code after the if.
133 EmitBlock(ContBlock);
134}
135
136void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000137 // Emit the header for the loop, insert it, which will create an uncond br to
138 // it.
139 llvm::BasicBlock *LoopHeader = new llvm::BasicBlock("whilecond");
140 EmitBlock(LoopHeader);
141
142 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
143 // of the controlling expression takes place before each execution of the loop
144 // body.
145 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
146
147 // TODO: while(1) is common, avoid extra exit blocks, etc. Be sure
148 // to correctly handle break/continue though.
149
150 // Create an exit block for when the condition fails, create a block for the
151 // body of the loop.
152 llvm::BasicBlock *ExitBlock = new llvm::BasicBlock("whileexit");
153 llvm::BasicBlock *LoopBody = new llvm::BasicBlock("whilebody");
154
155 // As long as the condition is true, go to the loop body.
156 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000157
158 // Store the blocks to use for break and continue.
159 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000160
161 // Emit the loop body.
162 EmitBlock(LoopBody);
163 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000164
165 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000166
167 // Cycle to the condition.
168 Builder.CreateBr(LoopHeader);
169
170 // Emit the exit block.
171 EmitBlock(ExitBlock);
172}
173
174void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000175 // TODO: "do {} while (0)" is common in macros, avoid extra blocks. Be sure
176 // to correctly handle break/continue though.
177
178 // Emit the body for the loop, insert it, which will create an uncond br to
179 // it.
180 llvm::BasicBlock *LoopBody = new llvm::BasicBlock("dobody");
181 llvm::BasicBlock *AfterDo = new llvm::BasicBlock("afterdo");
182 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000183
184 llvm::BasicBlock *DoCond = new llvm::BasicBlock("docond");
185
186 // Store the blocks to use for break and continue.
187 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000188
189 // Emit the body of the loop into the block.
190 EmitStmt(S.getBody());
191
Chris Lattnerda138702007-07-16 21:28:45 +0000192 BreakContinueStack.pop_back();
193
194 EmitBlock(DoCond);
195
Reid Spencer5f016e22007-07-11 17:01:13 +0000196 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
197 // after each execution of the loop body."
198
199 // Evaluate the conditional in the while header.
200 // C99 6.8.5p2/p4: The first substatement is executed if the expression
201 // compares unequal to 0. The condition must be a scalar type.
202 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
203
204 // As long as the condition is true, iterate the loop.
205 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
206
207 // Emit the exit block.
208 EmitBlock(AfterDo);
209}
210
211void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000212 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
213 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000214 // TODO: We could keep track of whether the loop body contains any
215 // break/continue statements and not create unnecessary blocks (like
216 // "afterfor" for a condless loop) if it doesn't.
217
Reid Spencer5f016e22007-07-11 17:01:13 +0000218 // Evaluate the first part before the loop.
219 if (S.getInit())
220 EmitStmt(S.getInit());
221
222 // Start the loop with a block that tests the condition.
223 llvm::BasicBlock *CondBlock = new llvm::BasicBlock("forcond");
Chris Lattnerda138702007-07-16 21:28:45 +0000224 llvm::BasicBlock *AfterFor = new llvm::BasicBlock("afterfor");
225
Reid Spencer5f016e22007-07-11 17:01:13 +0000226 EmitBlock(CondBlock);
227
228 // Evaluate the condition if present. If not, treat it as a non-zero-constant
229 // according to 6.8.5.3p2, aka, true.
230 if (S.getCond()) {
231 // C99 6.8.5p2/p4: The first substatement is executed if the expression
232 // compares unequal to 0. The condition must be a scalar type.
233 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
234
235 // As long as the condition is true, iterate the loop.
236 llvm::BasicBlock *ForBody = new llvm::BasicBlock("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
238 EmitBlock(ForBody);
239 } else {
240 // Treat it as a non-zero constant. Don't even create a new block for the
241 // body, just fall into it.
242 }
243
Chris Lattnerda138702007-07-16 21:28:45 +0000244 // If the for loop doesn't have an increment we can just use the
245 // condition as the continue block.
246 llvm::BasicBlock *ContinueBlock;
247 if (S.getInc())
248 ContinueBlock = new llvm::BasicBlock("forinc");
249 else
250 ContinueBlock = CondBlock;
251
252 // Store the blocks to use for break and continue.
253 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
254
Reid Spencer5f016e22007-07-11 17:01:13 +0000255 // If the condition is true, execute the body of the for stmt.
256 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000257
258 BreakContinueStack.pop_back();
259
260 if (S.getInc())
261 EmitBlock(ContinueBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000262
263 // If there is an increment, emit it next.
264 if (S.getInc())
Chris Lattner883f6a72007-08-11 00:04:45 +0000265 EmitStmt(S.getInc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000266
267 // Finally, branch back up to the condition for the next iteration.
268 Builder.CreateBr(CondBlock);
269
Chris Lattnerda138702007-07-16 21:28:45 +0000270 // Emit the fall-through block.
271 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000272}
273
274/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
275/// if the function returns void, or may be missing one if the function returns
276/// non-void. Fun stuff :).
277void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
278 RValue RetVal;
279
280 // Emit the result value, even if unused, to evalute the side effects.
281 const Expr *RV = S.getRetValue();
Chris Lattner883f6a72007-08-11 00:04:45 +0000282 // FIXME: Handle return of an aggregate!
Reid Spencer5f016e22007-07-11 17:01:13 +0000283 if (RV)
284 RetVal = EmitExpr(RV);
Chris Lattnera80b0ba2007-07-13 20:07:11 +0000285 else // Silence a bogus GCC warning.
286 RetVal = RValue::get(0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000287
288 QualType FnRetTy = CurFuncDecl->getType().getCanonicalType();
289 FnRetTy = cast<FunctionType>(FnRetTy)->getResultType();
290
291 if (FnRetTy->isVoidType()) {
292 // If the function returns void, emit ret void, and ignore the retval.
293 Builder.CreateRetVoid();
294 } else if (RV == 0) {
295 // "return;" in a function that returns a value.
296 const llvm::Type *RetTy = CurFn->getFunctionType()->getReturnType();
297 if (RetTy == llvm::Type::VoidTy)
298 Builder.CreateRetVoid(); // struct return etc.
299 else
300 Builder.CreateRet(llvm::UndefValue::get(RetTy));
301 } else {
302 // Do implicit conversions to the returned type.
303 RetVal = EmitConversion(RetVal, RV->getType(), FnRetTy);
304
305 if (RetVal.isScalar()) {
306 Builder.CreateRet(RetVal.getVal());
307 } else {
308 llvm::Value *SRetPtr = CurFn->arg_begin();
309 EmitStoreThroughLValue(RetVal, LValue::MakeAddr(SRetPtr), FnRetTy);
310 }
311 }
312
313 // Emit a block after the branch so that dead code after a return has some
314 // place to go.
315 EmitBlock(new llvm::BasicBlock());
316}
317
318void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
319 for (const Decl *Decl = S.getDecl(); Decl; Decl = Decl->getNextDeclarator())
320 EmitDecl(*Decl);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000321}
Chris Lattnerda138702007-07-16 21:28:45 +0000322
323void CodeGenFunction::EmitBreakStmt() {
324 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
325
326 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
327 Builder.CreateBr(Block);
328 EmitBlock(new llvm::BasicBlock());
329}
330
331void CodeGenFunction::EmitContinueStmt() {
332 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
333
334 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
335 Builder.CreateBr(Block);
336 EmitBlock(new llvm::BasicBlock());
337}