blob: 067d6ebd098604a358136e31010eaf305aed0742 [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//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Stmt nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
15#include "CodeGenModule.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "CodeGenFunction.h"
17#include "clang/AST/AST.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000018#include "clang/Basic/TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000022#include "llvm/InlineAsm.h"
23#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25using namespace CodeGen;
26
27//===----------------------------------------------------------------------===//
28// Statement Emission
29//===----------------------------------------------------------------------===//
30
31void CodeGenFunction::EmitStmt(const Stmt *S) {
32 assert(S && "Null statement?");
33
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000034 // Generate stoppoints if we are emitting debug info.
35 // Beginning of a Compound Statement (e.g. an opening '{') does not produce
36 // executable code. So do not generate a stoppoint for that.
37 CGDebugInfo *DI = CGM.getDebugInfo();
38 if (DI && S->getStmtClass() != Stmt::CompoundStmtClass) {
39 if (S->getLocStart().isValid()) {
40 DI->setLocation(S->getLocStart());
41 }
42
43 DI->EmitStopPoint(CurFn, Builder);
44 }
45
Reid Spencer5f016e22007-07-11 17:01:13 +000046 switch (S->getStmtClass()) {
47 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000048 // Must be an expression in a stmt context. Emit the value (to get
49 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000050 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000051 if (!hasAggregateLLVMType(E->getType()))
52 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000053 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000054 EmitComplexExpr(E);
55 else
56 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000057 } else {
Chris Lattnerdc4d2802007-12-02 01:49:16 +000058 WarnUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000059 }
60 break;
61 case Stmt::NullStmtClass: break;
62 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
63 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
64 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
65
66 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
67 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
68 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
69 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
70
71 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
72 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Chris Lattnerda138702007-07-16 21:28:45 +000073
74 case Stmt::BreakStmtClass: EmitBreakStmt(); break;
75 case Stmt::ContinueStmtClass: EmitContinueStmt(); break;
Devang Patel51b09f22007-10-04 23:45:31 +000076 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
77 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
78 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000079 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000080 }
81}
82
Chris Lattner33793202007-08-31 22:09:40 +000083/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
84/// this captures the expression result of the last sub-statement and returns it
85/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +000086RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
87 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +000088 // FIXME: handle vla's etc.
Chris Lattner33793202007-08-31 22:09:40 +000089 if (S.body_empty() || !isa<Expr>(S.body_back())) GetLast = false;
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000090
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +000091 CGDebugInfo *DI = CGM.getDebugInfo();
92 if (DI) {
93 if (S.getLBracLoc().isValid()) {
94 DI->setLocation(S.getLBracLoc());
95 }
96 DI->EmitRegionStart(CurFn, Builder);
97 }
98
Chris Lattner33793202007-08-31 22:09:40 +000099 for (CompoundStmt::const_body_iterator I = S.body_begin(),
100 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000101 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000102
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000103 if (DI) {
104 if (S.getRBracLoc().isValid()) {
105 DI->setLocation(S.getRBracLoc());
106 }
107 DI->EmitRegionEnd(CurFn, Builder);
108 }
109
Chris Lattner33793202007-08-31 22:09:40 +0000110 if (!GetLast)
111 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +0000112
113 return EmitAnyExpr(cast<Expr>(S.body_back()), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000114}
115
116void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
117 // Emit a branch from this block to the next one if this was a real block. If
118 // this was just a fall-through block after a terminator, don't emit it.
119 llvm::BasicBlock *LastBB = Builder.GetInsertBlock();
120
121 if (LastBB->getTerminator()) {
122 // If the previous block is already terminated, don't touch it.
123 } else if (LastBB->empty() && LastBB->getValueName() == 0) {
124 // If the last block was an empty placeholder, remove it now.
125 // TODO: cache and reuse these.
126 Builder.GetInsertBlock()->eraseFromParent();
127 } else {
128 // Otherwise, create a fall-through branch.
129 Builder.CreateBr(BB);
130 }
131 CurFn->getBasicBlockList().push_back(BB);
132 Builder.SetInsertPoint(BB);
133}
134
135void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
136 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
137
138 EmitBlock(NextBB);
139 EmitStmt(S.getSubStmt());
140}
141
142void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
143 Builder.CreateBr(getBasicBlockForLabel(S.getLabel()));
144
145 // Emit a block after the branch so that dead code after a goto has some place
146 // to go.
Gabor Greif984d0b42008-04-06 20:42:52 +0000147 Builder.SetInsertPoint(llvm::BasicBlock::Create("", CurFn));
Reid Spencer5f016e22007-07-11 17:01:13 +0000148}
149
150void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
151 // C99 6.8.4.1: The first substatement is executed if the expression compares
152 // unequal to 0. The condition must be a scalar type.
153 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
154
Gabor Greif984d0b42008-04-06 20:42:52 +0000155 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("ifend");
156 llvm::BasicBlock *ThenBlock = llvm::BasicBlock::Create("ifthen");
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 llvm::BasicBlock *ElseBlock = ContBlock;
158
159 if (S.getElse())
Gabor Greif984d0b42008-04-06 20:42:52 +0000160 ElseBlock = llvm::BasicBlock::Create("ifelse");
Reid Spencer5f016e22007-07-11 17:01:13 +0000161
162 // Insert the conditional branch.
163 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
164
165 // Emit the 'then' code.
166 EmitBlock(ThenBlock);
167 EmitStmt(S.getThen());
Devang Pateld9363c32007-09-28 21:49:18 +0000168 llvm::BasicBlock *BB = Builder.GetInsertBlock();
169 if (isDummyBlock(BB)) {
170 BB->eraseFromParent();
171 Builder.SetInsertPoint(ThenBlock);
172 }
173 else
174 Builder.CreateBr(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000175
176 // Emit the 'else' code if present.
177 if (const Stmt *Else = S.getElse()) {
178 EmitBlock(ElseBlock);
179 EmitStmt(Else);
Devang Pateld9363c32007-09-28 21:49:18 +0000180 llvm::BasicBlock *BB = Builder.GetInsertBlock();
181 if (isDummyBlock(BB)) {
182 BB->eraseFromParent();
183 Builder.SetInsertPoint(ElseBlock);
184 }
185 else
186 Builder.CreateBr(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 }
188
189 // Emit the continuation block for code after the if.
190 EmitBlock(ContBlock);
191}
192
193void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000194 // Emit the header for the loop, insert it, which will create an uncond br to
195 // it.
Gabor Greif984d0b42008-04-06 20:42:52 +0000196 llvm::BasicBlock *LoopHeader = llvm::BasicBlock::Create("whilecond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000197 EmitBlock(LoopHeader);
198
199 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
200 // of the controlling expression takes place before each execution of the loop
201 // body.
202 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000203
204 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000205 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000206 bool EmitBoolCondBranch = true;
207 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
208 if (C->isOne())
209 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000210
211 // Create an exit block for when the condition fails, create a block for the
212 // body of the loop.
Gabor Greif984d0b42008-04-06 20:42:52 +0000213 llvm::BasicBlock *ExitBlock = llvm::BasicBlock::Create("whileexit");
214 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("whilebody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000215
216 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000217 if (EmitBoolCondBranch)
218 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000219
220 // Store the blocks to use for break and continue.
221 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000222
223 // Emit the loop body.
224 EmitBlock(LoopBody);
225 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000226
227 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000228
229 // Cycle to the condition.
230 Builder.CreateBr(LoopHeader);
231
232 // Emit the exit block.
233 EmitBlock(ExitBlock);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000234
235 // If LoopHeader is a simple forwarding block then eliminate it.
236 if (!EmitBoolCondBranch
237 && &LoopHeader->front() == LoopHeader->getTerminator()) {
238 LoopHeader->replaceAllUsesWith(LoopBody);
239 LoopHeader->getTerminator()->eraseFromParent();
240 LoopHeader->eraseFromParent();
241 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000242}
243
244void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000245 // Emit the body for the loop, insert it, which will create an uncond br to
246 // it.
Gabor Greif984d0b42008-04-06 20:42:52 +0000247 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("dobody");
248 llvm::BasicBlock *AfterDo = llvm::BasicBlock::Create("afterdo");
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000250
Gabor Greif984d0b42008-04-06 20:42:52 +0000251 llvm::BasicBlock *DoCond = llvm::BasicBlock::Create("docond");
Chris Lattnerda138702007-07-16 21:28:45 +0000252
253 // Store the blocks to use for break and continue.
254 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000255
256 // Emit the body of the loop into the block.
257 EmitStmt(S.getBody());
258
Chris Lattnerda138702007-07-16 21:28:45 +0000259 BreakContinueStack.pop_back();
260
261 EmitBlock(DoCond);
262
Reid Spencer5f016e22007-07-11 17:01:13 +0000263 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
264 // after each execution of the loop body."
265
266 // Evaluate the conditional in the while header.
267 // C99 6.8.5p2/p4: The first substatement is executed if the expression
268 // compares unequal to 0. The condition must be a scalar type.
269 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000270
271 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
272 // to correctly handle break/continue though.
273 bool EmitBoolCondBranch = true;
274 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
275 if (C->isZero())
276 EmitBoolCondBranch = false;
277
Reid Spencer5f016e22007-07-11 17:01:13 +0000278 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000279 if (EmitBoolCondBranch)
280 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000281
282 // Emit the exit block.
283 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000284
285 // If DoCond is a simple forwarding block then eliminate it.
286 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
287 DoCond->replaceAllUsesWith(AfterDo);
288 DoCond->getTerminator()->eraseFromParent();
289 DoCond->eraseFromParent();
290 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000291}
292
293void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000294 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
295 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000296 // TODO: We could keep track of whether the loop body contains any
297 // break/continue statements and not create unnecessary blocks (like
298 // "afterfor" for a condless loop) if it doesn't.
299
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 // Evaluate the first part before the loop.
301 if (S.getInit())
302 EmitStmt(S.getInit());
303
304 // Start the loop with a block that tests the condition.
Gabor Greif984d0b42008-04-06 20:42:52 +0000305 llvm::BasicBlock *CondBlock = llvm::BasicBlock::Create("forcond");
306 llvm::BasicBlock *AfterFor = llvm::BasicBlock::Create("afterfor");
Chris Lattnerda138702007-07-16 21:28:45 +0000307
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 EmitBlock(CondBlock);
309
310 // Evaluate the condition if present. If not, treat it as a non-zero-constant
311 // according to 6.8.5.3p2, aka, true.
312 if (S.getCond()) {
313 // C99 6.8.5p2/p4: The first substatement is executed if the expression
314 // compares unequal to 0. The condition must be a scalar type.
315 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
316
317 // As long as the condition is true, iterate the loop.
Gabor Greif984d0b42008-04-06 20:42:52 +0000318 llvm::BasicBlock *ForBody = llvm::BasicBlock::Create("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
320 EmitBlock(ForBody);
321 } else {
322 // Treat it as a non-zero constant. Don't even create a new block for the
323 // body, just fall into it.
324 }
325
Chris Lattnerda138702007-07-16 21:28:45 +0000326 // If the for loop doesn't have an increment we can just use the
327 // condition as the continue block.
328 llvm::BasicBlock *ContinueBlock;
329 if (S.getInc())
Gabor Greif984d0b42008-04-06 20:42:52 +0000330 ContinueBlock = llvm::BasicBlock::Create("forinc");
Chris Lattnerda138702007-07-16 21:28:45 +0000331 else
332 ContinueBlock = CondBlock;
333
334 // Store the blocks to use for break and continue.
335 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
336
Reid Spencer5f016e22007-07-11 17:01:13 +0000337 // If the condition is true, execute the body of the for stmt.
338 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000339
340 BreakContinueStack.pop_back();
341
342 if (S.getInc())
343 EmitBlock(ContinueBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000344
345 // If there is an increment, emit it next.
346 if (S.getInc())
Chris Lattner883f6a72007-08-11 00:04:45 +0000347 EmitStmt(S.getInc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000348
349 // Finally, branch back up to the condition for the next iteration.
350 Builder.CreateBr(CondBlock);
351
Chris Lattnerda138702007-07-16 21:28:45 +0000352 // Emit the fall-through block.
353 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000354}
355
356/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
357/// if the function returns void, or may be missing one if the function returns
358/// non-void. Fun stuff :).
359void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000360 // Emit the result value, even if unused, to evalute the side effects.
361 const Expr *RV = S.getRetValue();
Chris Lattner4b0029d2007-08-26 07:14:44 +0000362
Eli Friedman144ac612008-05-22 01:22:33 +0000363 llvm::Value* RetValue = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000364 if (FnRetTy->isVoidType()) {
Eli Friedman144ac612008-05-22 01:22:33 +0000365 // Make sure not to return anything
366 if (RV) {
367 // Evaluate the expression for side effects
368 EmitAnyExpr(RV);
369 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 } else if (RV == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 const llvm::Type *RetTy = CurFn->getFunctionType()->getReturnType();
Eli Friedman144ac612008-05-22 01:22:33 +0000372 if (RetTy != llvm::Type::VoidTy) {
373 // Handle "return;" in a function that returns a value.
374 RetValue = llvm::UndefValue::get(RetTy);
375 }
Chris Lattner4b0029d2007-08-26 07:14:44 +0000376 } else if (!hasAggregateLLVMType(RV->getType())) {
Eli Friedman144ac612008-05-22 01:22:33 +0000377 RetValue = EmitScalarExpr(RV);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000378 } else if (RV->getType()->isAnyComplexType()) {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000379 llvm::Value *SRetPtr = CurFn->arg_begin();
Chris Lattner190dbe22007-08-26 16:22:13 +0000380 EmitComplexExprIntoAddr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 } else {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000382 llvm::Value *SRetPtr = CurFn->arg_begin();
383 EmitAggExpr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000384 }
Eli Friedman144ac612008-05-22 01:22:33 +0000385
386 if (RetValue) {
387 Builder.CreateRet(RetValue);
388 } else {
389 Builder.CreateRetVoid();
390 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000391
392 // Emit a block after the branch so that dead code after a return has some
393 // place to go.
Gabor Greif984d0b42008-04-06 20:42:52 +0000394 EmitBlock(llvm::BasicBlock::Create());
Reid Spencer5f016e22007-07-11 17:01:13 +0000395}
396
397void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Steve Naroff94745042007-09-13 23:52:58 +0000398 for (const ScopedDecl *Decl = S.getDecl(); Decl;
399 Decl = Decl->getNextDeclarator())
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 EmitDecl(*Decl);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000401}
Chris Lattnerda138702007-07-16 21:28:45 +0000402
403void CodeGenFunction::EmitBreakStmt() {
404 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
405
406 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
407 Builder.CreateBr(Block);
Gabor Greif984d0b42008-04-06 20:42:52 +0000408 EmitBlock(llvm::BasicBlock::Create());
Chris Lattnerda138702007-07-16 21:28:45 +0000409}
410
411void CodeGenFunction::EmitContinueStmt() {
412 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
413
414 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
415 Builder.CreateBr(Block);
Gabor Greif984d0b42008-04-06 20:42:52 +0000416 EmitBlock(llvm::BasicBlock::Create());
Chris Lattnerda138702007-07-16 21:28:45 +0000417}
Devang Patel51b09f22007-10-04 23:45:31 +0000418
Devang Patelc049e4f2007-10-08 20:57:48 +0000419/// EmitCaseStmtRange - If case statement range is not too big then
420/// add multiple cases to switch instruction, one for each value within
421/// the range. If range is too big then emit "if" condition check.
422void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
423 assert (S.getRHS() && "Unexpected RHS value in CaseStmt");
424
425 const Expr *L = S.getLHS();
426 const Expr *R = S.getRHS();
427 llvm::ConstantInt *LV = cast<llvm::ConstantInt>(EmitScalarExpr(L));
428 llvm::ConstantInt *RV = cast<llvm::ConstantInt>(EmitScalarExpr(R));
429 llvm::APInt LHS = LV->getValue();
Devang Patel00ee4e42007-10-09 17:10:59 +0000430 const llvm::APInt &RHS = RV->getValue();
Devang Patelc049e4f2007-10-08 20:57:48 +0000431
432 llvm::APInt Range = RHS - LHS;
433 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
434 // Range is small enough to add multiple switch instruction cases.
435 StartBlock("sw.bb");
436 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
437 SwitchInsn->addCase(LV, CaseDest);
Devang Patel2d79d0f2007-10-05 20:54:07 +0000438 LHS++;
439 while (LHS != RHS) {
440 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
441 LHS++;
442 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000443 SwitchInsn->addCase(RV, CaseDest);
444 EmitStmt(S.getSubStmt());
445 return;
446 }
447
448 // The range is too big. Emit "if" condition.
449 llvm::BasicBlock *FalseDest = NULL;
Gabor Greif984d0b42008-04-06 20:42:52 +0000450 llvm::BasicBlock *CaseDest = llvm::BasicBlock::Create("sw.bb");
Devang Patel2d79d0f2007-10-05 20:54:07 +0000451
Devang Patelc049e4f2007-10-08 20:57:48 +0000452 // If we have already seen one case statement range for this switch
453 // instruction then piggy-back otherwise use default block as false
454 // destination.
455 if (CaseRangeBlock)
456 FalseDest = CaseRangeBlock;
457 else
458 FalseDest = SwitchInsn->getDefaultDest();
459
460 // Start new block to hold case statement range check instructions.
461 StartBlock("case.range");
462 CaseRangeBlock = Builder.GetInsertBlock();
463
464 // Emit range check.
465 llvm::Value *Diff =
466 Builder.CreateSub(SwitchInsn->getCondition(), LV, "tmp");
467 llvm::Value *Cond =
468 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
469 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
470
471 // Now emit case statement body.
472 EmitBlock(CaseDest);
473 EmitStmt(S.getSubStmt());
474}
475
476void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
477 if (S.getRHS()) {
478 EmitCaseStmtRange(S);
479 return;
480 }
481
482 StartBlock("sw.bb");
483 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Chris Lattnerc69a5812007-11-30 17:44:57 +0000484 llvm::APSInt CaseVal(32);
485 S.getLHS()->isIntegerConstantExpr(CaseVal, getContext());
486 llvm::ConstantInt *LV = llvm::ConstantInt::get(CaseVal);
Devang Patelc049e4f2007-10-08 20:57:48 +0000487 SwitchInsn->addCase(LV, CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000488 EmitStmt(S.getSubStmt());
489}
490
491void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
492 StartBlock("sw.default");
493 // Current insert block is the default destination.
494 SwitchInsn->setSuccessor(0, Builder.GetInsertBlock());
495 EmitStmt(S.getSubStmt());
496}
497
498void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
499 llvm::Value *CondV = EmitScalarExpr(S.getCond());
500
501 // Handle nested switch statements.
502 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000503 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
504 CaseRangeBlock = NULL;
Devang Patel51b09f22007-10-04 23:45:31 +0000505
506 // Create basic block to hold stuff that comes after switch statement.
507 // Initially use it to hold DefaultStmt.
Gabor Greif984d0b42008-04-06 20:42:52 +0000508 llvm::BasicBlock *NextBlock = llvm::BasicBlock::Create("after.sw");
Devang Patel51b09f22007-10-04 23:45:31 +0000509 SwitchInsn = Builder.CreateSwitch(CondV, NextBlock);
510
Eli Friedmand28a80d2008-05-12 16:08:04 +0000511 // Create basic block for body of switch
512 StartBlock("body.sw");
513
Devang Patele9b8c0a2007-10-30 20:59:40 +0000514 // All break statements jump to NextBlock. If BreakContinueStack is non empty
515 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000516 llvm::BasicBlock *ContinueBlock = NULL;
517 if (!BreakContinueStack.empty())
518 ContinueBlock = BreakContinueStack.back().ContinueBlock;
519 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
520
521 // Emit switch body.
522 EmitStmt(S.getBody());
523 BreakContinueStack.pop_back();
524
Devang Patelc049e4f2007-10-08 20:57:48 +0000525 // If one or more case statement range is seen then use CaseRangeBlock
526 // as the default block. False edge of CaseRangeBlock will lead to
527 // original default block.
528 if (CaseRangeBlock)
529 SwitchInsn->setSuccessor(0, CaseRangeBlock);
530
Devang Patel51b09f22007-10-04 23:45:31 +0000531 // Prune insert block if it is dummy.
532 llvm::BasicBlock *BB = Builder.GetInsertBlock();
533 if (isDummyBlock(BB))
534 BB->eraseFromParent();
Chris Lattner1438b492007-12-01 05:27:33 +0000535 else // Otherwise, branch to continuation.
536 Builder.CreateBr(NextBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000537
538 // Place NextBlock as the new insert point.
Chris Lattner1438b492007-12-01 05:27:33 +0000539 CurFn->getBasicBlockList().push_back(NextBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000540 Builder.SetInsertPoint(NextBlock);
541 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000542 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000543}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000544
545static inline std::string ConvertAsmString(const char *Start,
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000546 unsigned NumOperands,
547 bool IsSimple)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000548{
549 static unsigned AsmCounter = 0;
550
551 AsmCounter++;
552
553 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000554 if (IsSimple) {
555 while (*Start) {
556 switch (*Start) {
557 default:
558 Result += *Start;
559 break;
560 case '$':
561 Result += "$$";
562 break;
563 }
564
565 Start++;
566 }
567
568 return Result;
569 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000570
571 while (*Start) {
572 switch (*Start) {
573 default:
574 Result += *Start;
575 break;
576 case '$':
577 Result += "$$";
578 break;
579 case '%':
580 // Escaped character
581 Start++;
582 if (!*Start) {
583 // FIXME: This should be caught during Sema.
584 assert(0 && "Trailing '%' in asm string.");
585 }
586
587 char EscapedChar = *Start;
588 if (EscapedChar == '%') {
589 // Escaped percentage sign.
590 Result += '%';
591 }
592 else if (EscapedChar == '=') {
593 // Generate an unique ID.
594 Result += llvm::utostr(AsmCounter);
595 } else if (isdigit(EscapedChar)) {
596 // %n - Assembler operand n
597 char *End;
598
599 unsigned long n = strtoul(Start, &End, 10);
600 if (Start == End) {
601 // FIXME: This should be caught during Sema.
602 assert(0 && "Missing operand!");
603 } else if (n >= NumOperands) {
604 // FIXME: This should be caught during Sema.
605 assert(0 && "Operand number out of range!");
606 }
607
608 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000609 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000610 } else if (isalpha(EscapedChar)) {
611 char *End;
612
613 unsigned long n = strtoul(Start + 1, &End, 10);
614 if (Start == End) {
615 // FIXME: This should be caught during Sema.
616 assert(0 && "Missing operand!");
617 } else if (n >= NumOperands) {
618 // FIXME: This should be caught during Sema.
619 assert(0 && "Operand number out of range!");
620 }
621
622 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000623 Start = End - 1;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000624 } else {
625 assert(0 && "Unhandled asm escaped character!");
626 }
627 }
628 Start++;
629 }
630
631 return Result;
632}
633
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000634static std::string SimplifyConstraint(const char* Constraint,
635 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000636 std::string Result;
637
638 while (*Constraint) {
639 switch (*Constraint) {
640 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000641 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000642 break;
643 // Ignore these
644 case '*':
645 case '?':
646 case '!':
647 break;
648 case 'g':
649 Result += "imr";
650 break;
651 }
652
653 Constraint++;
654 }
655
656 return Result;
657}
658
659void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
660 std::string AsmString =
661 ConvertAsmString(std::string(S.getAsmString()->getStrData(),
662 S.getAsmString()->getByteLength()).c_str(),
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000663 S.getNumOutputs() + S.getNumInputs(), S.isSimple());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000664
665 std::string Constraints;
666
667 llvm::Value *ResultAddr = 0;
668 const llvm::Type *ResultType = llvm::Type::VoidTy;
669
670 std::vector<const llvm::Type*> ArgTypes;
671 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000672
673 // Keep track of inout constraints.
674 std::string InOutConstraints;
675 std::vector<llvm::Value*> InOutArgs;
676 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000677
678 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
679 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
680 S.getOutputConstraint(i)->getByteLength());
681
682 TargetInfo::ConstraintInfo Info;
683 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
684 Info);
685 assert(result && "Failed to parse output constraint");
686
687 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000688 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000689
690 LValue Dest = EmitLValue(S.getOutputExpr(i));
691 const llvm::Type *DestValueType =
692 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
693
694 // If the first output operand is not a memory dest, we'll
695 // make it the return value.
696 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000697 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000698 ResultAddr = Dest.getAddress();
699 ResultType = DestValueType;
700 Constraints += "=" + OutputConstraint;
701 } else {
702 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000703 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000704 if (i != 0)
705 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000706 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000707 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000708 }
709
710 if (Info & TargetInfo::CI_ReadWrite) {
711 // FIXME: This code should be shared with the code that handles inputs.
712 InOutConstraints += ',';
713
714 const Expr *InputExpr = S.getOutputExpr(i);
715 llvm::Value *Arg;
716 if ((Info & TargetInfo::CI_AllowsRegister) ||
717 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000718 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000719 Arg = EmitScalarExpr(InputExpr);
720 } else {
Dan Gohmand79a7262008-05-22 22:12:56 +0000721 assert(0 && "FIXME: Implement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000722 }
723 } else {
724 LValue Dest = EmitLValue(InputExpr);
725 Arg = Dest.getAddress();
726 InOutConstraints += '*';
727 }
728
729 InOutArgTypes.push_back(Arg->getType());
730 InOutArgs.push_back(Arg);
731 InOutConstraints += OutputConstraint;
732 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000733 }
734
735 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
736
737 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
738 const Expr *InputExpr = S.getInputExpr(i);
739
740 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
741 S.getInputConstraint(i)->getByteLength());
742
743 TargetInfo::ConstraintInfo Info;
744 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
745 NumConstraints,
746 Info);
747 assert(result && "Failed to parse input constraint");
748
749 if (i != 0 || S.getNumOutputs() > 0)
750 Constraints += ',';
751
752 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000753 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000754
755 llvm::Value *Arg;
756
757 if ((Info & TargetInfo::CI_AllowsRegister) ||
758 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000759 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000760 Arg = EmitScalarExpr(InputExpr);
761 } else {
Dan Gohmand79a7262008-05-22 22:12:56 +0000762 assert(0 && "FIXME: Implement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000763 }
764 } else {
765 LValue Dest = EmitLValue(InputExpr);
766 Arg = Dest.getAddress();
767 Constraints += '*';
768 }
769
770 ArgTypes.push_back(Arg->getType());
771 Args.push_back(Arg);
772 Constraints += InputConstraint;
773 }
774
Anders Carlssonf39a4212008-02-05 20:01:53 +0000775 // Append the "input" part of inout constraints last.
776 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
777 ArgTypes.push_back(InOutArgTypes[i]);
778 Args.push_back(InOutArgs[i]);
779 }
780 Constraints += InOutConstraints;
781
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000782 // Clobbers
783 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
784 std::string Clobber(S.getClobber(i)->getStrData(),
785 S.getClobber(i)->getByteLength());
786
787 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
788
Anders Carlssonea041752008-02-06 00:11:32 +0000789 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000790 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000791
792 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000793 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000794 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000795 }
796
797 // Add machine specific clobbers
798 if (const char *C = Target.getClobbers()) {
799 if (!Constraints.empty())
800 Constraints += ',';
801 Constraints += C;
802 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000803
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000804 const llvm::FunctionType *FTy =
805 llvm::FunctionType::get(ResultType, ArgTypes, false);
806
807 llvm::InlineAsm *IA =
808 llvm::InlineAsm::get(FTy, AsmString, Constraints,
809 S.isVolatile() || S.getNumOutputs() == 0);
810 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
811 if (ResultAddr)
812 Builder.CreateStore(Result, ResultAddr);
813}