blob: b7f1f29f878365c3dca764327cd67f137bd4919a [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:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000031 // Must be an expression in a stmt context. Emit the value (to get
32 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000033 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000034 if (!hasAggregateLLVMType(E->getType()))
35 EmitScalarExpr(E);
36 else if (E->getType()->isComplexType())
37 EmitComplexExpr(E);
38 else
39 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000040 } else {
41 printf("Unimplemented stmt!\n");
Chris Lattner419ea7e2007-09-13 01:17:29 +000042 S->dump(getContext().SourceMgr);
Reid Spencer5f016e22007-07-11 17:01:13 +000043 }
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
Chris Lattner33793202007-08-31 22:09:40 +000063/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
64/// this captures the expression result of the last sub-statement and returns it
65/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +000066RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
67 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +000068 // FIXME: handle vla's etc.
Chris Lattner33793202007-08-31 22:09:40 +000069 if (S.body_empty() || !isa<Expr>(S.body_back())) GetLast = false;
Reid Spencer5f016e22007-07-11 17:01:13 +000070
Chris Lattner33793202007-08-31 22:09:40 +000071 for (CompoundStmt::const_body_iterator I = S.body_begin(),
72 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +000073 EmitStmt(*I);
Chris Lattner33793202007-08-31 22:09:40 +000074
75
76 if (!GetLast)
77 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +000078
79 return EmitAnyExpr(cast<Expr>(S.body_back()), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +000080}
81
82void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
83 // Emit a branch from this block to the next one if this was a real block. If
84 // this was just a fall-through block after a terminator, don't emit it.
85 llvm::BasicBlock *LastBB = Builder.GetInsertBlock();
86
87 if (LastBB->getTerminator()) {
88 // If the previous block is already terminated, don't touch it.
89 } else if (LastBB->empty() && LastBB->getValueName() == 0) {
90 // If the last block was an empty placeholder, remove it now.
91 // TODO: cache and reuse these.
92 Builder.GetInsertBlock()->eraseFromParent();
93 } else {
94 // Otherwise, create a fall-through branch.
95 Builder.CreateBr(BB);
96 }
97 CurFn->getBasicBlockList().push_back(BB);
98 Builder.SetInsertPoint(BB);
99}
100
101void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
102 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
103
104 EmitBlock(NextBB);
105 EmitStmt(S.getSubStmt());
106}
107
108void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
109 Builder.CreateBr(getBasicBlockForLabel(S.getLabel()));
110
111 // Emit a block after the branch so that dead code after a goto has some place
112 // to go.
113 Builder.SetInsertPoint(new llvm::BasicBlock("", CurFn));
114}
115
116void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
117 // C99 6.8.4.1: The first substatement is executed if the expression compares
118 // unequal to 0. The condition must be a scalar type.
119 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
120
121 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("ifend");
122 llvm::BasicBlock *ThenBlock = new llvm::BasicBlock("ifthen");
123 llvm::BasicBlock *ElseBlock = ContBlock;
124
125 if (S.getElse())
126 ElseBlock = new llvm::BasicBlock("ifelse");
127
128 // Insert the conditional branch.
129 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
130
131 // Emit the 'then' code.
132 EmitBlock(ThenBlock);
133 EmitStmt(S.getThen());
134 Builder.CreateBr(ContBlock);
135
136 // Emit the 'else' code if present.
137 if (const Stmt *Else = S.getElse()) {
138 EmitBlock(ElseBlock);
139 EmitStmt(Else);
140 Builder.CreateBr(ContBlock);
141 }
142
143 // Emit the continuation block for code after the if.
144 EmitBlock(ContBlock);
145}
146
147void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000148 // Emit the header for the loop, insert it, which will create an uncond br to
149 // it.
150 llvm::BasicBlock *LoopHeader = new llvm::BasicBlock("whilecond");
151 EmitBlock(LoopHeader);
152
153 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
154 // of the controlling expression takes place before each execution of the loop
155 // body.
156 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
157
158 // TODO: while(1) is common, avoid extra exit blocks, etc. Be sure
159 // to correctly handle break/continue though.
160
161 // Create an exit block for when the condition fails, create a block for the
162 // body of the loop.
163 llvm::BasicBlock *ExitBlock = new llvm::BasicBlock("whileexit");
164 llvm::BasicBlock *LoopBody = new llvm::BasicBlock("whilebody");
165
166 // As long as the condition is true, go to the loop body.
167 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000168
169 // Store the blocks to use for break and continue.
170 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000171
172 // Emit the loop body.
173 EmitBlock(LoopBody);
174 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000175
176 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000177
178 // Cycle to the condition.
179 Builder.CreateBr(LoopHeader);
180
181 // Emit the exit block.
182 EmitBlock(ExitBlock);
183}
184
185void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 // TODO: "do {} while (0)" is common in macros, avoid extra blocks. Be sure
187 // to correctly handle break/continue though.
188
189 // Emit the body for the loop, insert it, which will create an uncond br to
190 // it.
191 llvm::BasicBlock *LoopBody = new llvm::BasicBlock("dobody");
192 llvm::BasicBlock *AfterDo = new llvm::BasicBlock("afterdo");
193 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000194
195 llvm::BasicBlock *DoCond = new llvm::BasicBlock("docond");
196
197 // Store the blocks to use for break and continue.
198 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000199
200 // Emit the body of the loop into the block.
201 EmitStmt(S.getBody());
202
Chris Lattnerda138702007-07-16 21:28:45 +0000203 BreakContinueStack.pop_back();
204
205 EmitBlock(DoCond);
206
Reid Spencer5f016e22007-07-11 17:01:13 +0000207 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
208 // after each execution of the loop body."
209
210 // Evaluate the conditional in the while header.
211 // C99 6.8.5p2/p4: The first substatement is executed if the expression
212 // compares unequal to 0. The condition must be a scalar type.
213 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
214
215 // As long as the condition is true, iterate the loop.
216 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
217
218 // Emit the exit block.
219 EmitBlock(AfterDo);
220}
221
222void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000223 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
224 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000225 // TODO: We could keep track of whether the loop body contains any
226 // break/continue statements and not create unnecessary blocks (like
227 // "afterfor" for a condless loop) if it doesn't.
228
Reid Spencer5f016e22007-07-11 17:01:13 +0000229 // Evaluate the first part before the loop.
230 if (S.getInit())
231 EmitStmt(S.getInit());
232
233 // Start the loop with a block that tests the condition.
234 llvm::BasicBlock *CondBlock = new llvm::BasicBlock("forcond");
Chris Lattnerda138702007-07-16 21:28:45 +0000235 llvm::BasicBlock *AfterFor = new llvm::BasicBlock("afterfor");
236
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 EmitBlock(CondBlock);
238
239 // Evaluate the condition if present. If not, treat it as a non-zero-constant
240 // according to 6.8.5.3p2, aka, true.
241 if (S.getCond()) {
242 // C99 6.8.5p2/p4: The first substatement is executed if the expression
243 // compares unequal to 0. The condition must be a scalar type.
244 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
245
246 // As long as the condition is true, iterate the loop.
247 llvm::BasicBlock *ForBody = new llvm::BasicBlock("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
249 EmitBlock(ForBody);
250 } else {
251 // Treat it as a non-zero constant. Don't even create a new block for the
252 // body, just fall into it.
253 }
254
Chris Lattnerda138702007-07-16 21:28:45 +0000255 // If the for loop doesn't have an increment we can just use the
256 // condition as the continue block.
257 llvm::BasicBlock *ContinueBlock;
258 if (S.getInc())
259 ContinueBlock = new llvm::BasicBlock("forinc");
260 else
261 ContinueBlock = CondBlock;
262
263 // Store the blocks to use for break and continue.
264 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
265
Reid Spencer5f016e22007-07-11 17:01:13 +0000266 // If the condition is true, execute the body of the for stmt.
267 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000268
269 BreakContinueStack.pop_back();
270
271 if (S.getInc())
272 EmitBlock(ContinueBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000273
274 // If there is an increment, emit it next.
275 if (S.getInc())
Chris Lattner883f6a72007-08-11 00:04:45 +0000276 EmitStmt(S.getInc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000277
278 // Finally, branch back up to the condition for the next iteration.
279 Builder.CreateBr(CondBlock);
280
Chris Lattnerda138702007-07-16 21:28:45 +0000281 // Emit the fall-through block.
282 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000283}
284
285/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
286/// if the function returns void, or may be missing one if the function returns
287/// non-void. Fun stuff :).
288void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000289 // Emit the result value, even if unused, to evalute the side effects.
290 const Expr *RV = S.getRetValue();
Chris Lattner4b0029d2007-08-26 07:14:44 +0000291
Reid Spencer5f016e22007-07-11 17:01:13 +0000292 QualType FnRetTy = CurFuncDecl->getType().getCanonicalType();
293 FnRetTy = cast<FunctionType>(FnRetTy)->getResultType();
294
295 if (FnRetTy->isVoidType()) {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000296 // If the function returns void, emit ret void.
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 Builder.CreateRetVoid();
298 } else if (RV == 0) {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000299 // Handle "return;" in a function that returns a value.
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 const llvm::Type *RetTy = CurFn->getFunctionType()->getReturnType();
301 if (RetTy == llvm::Type::VoidTy)
302 Builder.CreateRetVoid(); // struct return etc.
303 else
304 Builder.CreateRet(llvm::UndefValue::get(RetTy));
Chris Lattner4b0029d2007-08-26 07:14:44 +0000305 } else if (!hasAggregateLLVMType(RV->getType())) {
306 Builder.CreateRet(EmitScalarExpr(RV));
307 } else if (RV->getType()->isComplexType()) {
308 llvm::Value *SRetPtr = CurFn->arg_begin();
Chris Lattner190dbe22007-08-26 16:22:13 +0000309 EmitComplexExprIntoAddr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000310 } else {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000311 llvm::Value *SRetPtr = CurFn->arg_begin();
312 EmitAggExpr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 }
314
315 // Emit a block after the branch so that dead code after a return has some
316 // place to go.
317 EmitBlock(new llvm::BasicBlock());
318}
319
320void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Steve Naroff94745042007-09-13 23:52:58 +0000321 for (const ScopedDecl *Decl = S.getDecl(); Decl;
322 Decl = Decl->getNextDeclarator())
Reid Spencer5f016e22007-07-11 17:01:13 +0000323 EmitDecl(*Decl);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000324}
Chris Lattnerda138702007-07-16 21:28:45 +0000325
326void CodeGenFunction::EmitBreakStmt() {
327 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
328
329 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
330 Builder.CreateBr(Block);
331 EmitBlock(new llvm::BasicBlock());
332}
333
334void CodeGenFunction::EmitContinueStmt() {
335 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
336
337 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
338 Builder.CreateBr(Block);
339 EmitBlock(new llvm::BasicBlock());
340}