blob: c38ad04001da803e827b8fda76c8e62ac42ba7db [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
Chris Lattner33793202007-08-31 22:09:40 +000091 for (CompoundStmt::const_body_iterator I = S.body_begin(),
92 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +000093 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000094
Chris Lattner33793202007-08-31 22:09:40 +000095 if (!GetLast)
96 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +000097
98 return EmitAnyExpr(cast<Expr>(S.body_back()), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +000099}
100
101void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
102 // Emit a branch from this block to the next one if this was a real block. If
103 // this was just a fall-through block after a terminator, don't emit it.
104 llvm::BasicBlock *LastBB = Builder.GetInsertBlock();
105
106 if (LastBB->getTerminator()) {
107 // If the previous block is already terminated, don't touch it.
108 } else if (LastBB->empty() && LastBB->getValueName() == 0) {
109 // If the last block was an empty placeholder, remove it now.
110 // TODO: cache and reuse these.
111 Builder.GetInsertBlock()->eraseFromParent();
112 } else {
113 // Otherwise, create a fall-through branch.
114 Builder.CreateBr(BB);
115 }
116 CurFn->getBasicBlockList().push_back(BB);
117 Builder.SetInsertPoint(BB);
118}
119
120void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
121 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
122
123 EmitBlock(NextBB);
124 EmitStmt(S.getSubStmt());
125}
126
127void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
128 Builder.CreateBr(getBasicBlockForLabel(S.getLabel()));
129
130 // Emit a block after the branch so that dead code after a goto has some place
131 // to go.
Gabor Greif984d0b42008-04-06 20:42:52 +0000132 Builder.SetInsertPoint(llvm::BasicBlock::Create("", CurFn));
Reid Spencer5f016e22007-07-11 17:01:13 +0000133}
134
135void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
136 // C99 6.8.4.1: The first substatement is executed if the expression compares
137 // unequal to 0. The condition must be a scalar type.
138 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
139
Gabor Greif984d0b42008-04-06 20:42:52 +0000140 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("ifend");
141 llvm::BasicBlock *ThenBlock = llvm::BasicBlock::Create("ifthen");
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 llvm::BasicBlock *ElseBlock = ContBlock;
143
144 if (S.getElse())
Gabor Greif984d0b42008-04-06 20:42:52 +0000145 ElseBlock = llvm::BasicBlock::Create("ifelse");
Reid Spencer5f016e22007-07-11 17:01:13 +0000146
147 // Insert the conditional branch.
148 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
149
150 // Emit the 'then' code.
151 EmitBlock(ThenBlock);
152 EmitStmt(S.getThen());
Devang Pateld9363c32007-09-28 21:49:18 +0000153 llvm::BasicBlock *BB = Builder.GetInsertBlock();
154 if (isDummyBlock(BB)) {
155 BB->eraseFromParent();
156 Builder.SetInsertPoint(ThenBlock);
157 }
158 else
159 Builder.CreateBr(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000160
161 // Emit the 'else' code if present.
162 if (const Stmt *Else = S.getElse()) {
163 EmitBlock(ElseBlock);
164 EmitStmt(Else);
Devang Pateld9363c32007-09-28 21:49:18 +0000165 llvm::BasicBlock *BB = Builder.GetInsertBlock();
166 if (isDummyBlock(BB)) {
167 BB->eraseFromParent();
168 Builder.SetInsertPoint(ElseBlock);
169 }
170 else
171 Builder.CreateBr(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000172 }
173
174 // Emit the continuation block for code after the if.
175 EmitBlock(ContBlock);
176}
177
178void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000179 // Emit the header for the loop, insert it, which will create an uncond br to
180 // it.
Gabor Greif984d0b42008-04-06 20:42:52 +0000181 llvm::BasicBlock *LoopHeader = llvm::BasicBlock::Create("whilecond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000182 EmitBlock(LoopHeader);
183
184 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
185 // of the controlling expression takes place before each execution of the loop
186 // body.
187 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000188
189 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000191 bool EmitBoolCondBranch = true;
192 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
193 if (C->isOne())
194 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000195
196 // Create an exit block for when the condition fails, create a block for the
197 // body of the loop.
Gabor Greif984d0b42008-04-06 20:42:52 +0000198 llvm::BasicBlock *ExitBlock = llvm::BasicBlock::Create("whileexit");
199 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("whilebody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000200
201 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000202 if (EmitBoolCondBranch)
203 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000204
205 // Store the blocks to use for break and continue.
206 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000207
208 // Emit the loop body.
209 EmitBlock(LoopBody);
210 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000211
212 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000213
214 // Cycle to the condition.
215 Builder.CreateBr(LoopHeader);
216
217 // Emit the exit block.
218 EmitBlock(ExitBlock);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000219
220 // If LoopHeader is a simple forwarding block then eliminate it.
221 if (!EmitBoolCondBranch
222 && &LoopHeader->front() == LoopHeader->getTerminator()) {
223 LoopHeader->replaceAllUsesWith(LoopBody);
224 LoopHeader->getTerminator()->eraseFromParent();
225 LoopHeader->eraseFromParent();
226 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000227}
228
229void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000230 // Emit the body for the loop, insert it, which will create an uncond br to
231 // it.
Gabor Greif984d0b42008-04-06 20:42:52 +0000232 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("dobody");
233 llvm::BasicBlock *AfterDo = llvm::BasicBlock::Create("afterdo");
Reid Spencer5f016e22007-07-11 17:01:13 +0000234 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000235
Gabor Greif984d0b42008-04-06 20:42:52 +0000236 llvm::BasicBlock *DoCond = llvm::BasicBlock::Create("docond");
Chris Lattnerda138702007-07-16 21:28:45 +0000237
238 // Store the blocks to use for break and continue.
239 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000240
241 // Emit the body of the loop into the block.
242 EmitStmt(S.getBody());
243
Chris Lattnerda138702007-07-16 21:28:45 +0000244 BreakContinueStack.pop_back();
245
246 EmitBlock(DoCond);
247
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
249 // after each execution of the loop body."
250
251 // Evaluate the conditional in the while header.
252 // C99 6.8.5p2/p4: The first substatement is executed if the expression
253 // compares unequal to 0. The condition must be a scalar type.
254 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000255
256 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
257 // to correctly handle break/continue though.
258 bool EmitBoolCondBranch = true;
259 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
260 if (C->isZero())
261 EmitBoolCondBranch = false;
262
Reid Spencer5f016e22007-07-11 17:01:13 +0000263 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000264 if (EmitBoolCondBranch)
265 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000266
267 // Emit the exit block.
268 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000269
270 // If DoCond is a simple forwarding block then eliminate it.
271 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
272 DoCond->replaceAllUsesWith(AfterDo);
273 DoCond->getTerminator()->eraseFromParent();
274 DoCond->eraseFromParent();
275 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000276}
277
278void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
280 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000281 // TODO: We could keep track of whether the loop body contains any
282 // break/continue statements and not create unnecessary blocks (like
283 // "afterfor" for a condless loop) if it doesn't.
284
Reid Spencer5f016e22007-07-11 17:01:13 +0000285 // Evaluate the first part before the loop.
286 if (S.getInit())
287 EmitStmt(S.getInit());
288
289 // Start the loop with a block that tests the condition.
Gabor Greif984d0b42008-04-06 20:42:52 +0000290 llvm::BasicBlock *CondBlock = llvm::BasicBlock::Create("forcond");
291 llvm::BasicBlock *AfterFor = llvm::BasicBlock::Create("afterfor");
Chris Lattnerda138702007-07-16 21:28:45 +0000292
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 EmitBlock(CondBlock);
294
295 // Evaluate the condition if present. If not, treat it as a non-zero-constant
296 // according to 6.8.5.3p2, aka, true.
297 if (S.getCond()) {
298 // C99 6.8.5p2/p4: The first substatement is executed if the expression
299 // compares unequal to 0. The condition must be a scalar type.
300 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
301
302 // As long as the condition is true, iterate the loop.
Gabor Greif984d0b42008-04-06 20:42:52 +0000303 llvm::BasicBlock *ForBody = llvm::BasicBlock::Create("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
305 EmitBlock(ForBody);
306 } else {
307 // Treat it as a non-zero constant. Don't even create a new block for the
308 // body, just fall into it.
309 }
310
Chris Lattnerda138702007-07-16 21:28:45 +0000311 // If the for loop doesn't have an increment we can just use the
312 // condition as the continue block.
313 llvm::BasicBlock *ContinueBlock;
314 if (S.getInc())
Gabor Greif984d0b42008-04-06 20:42:52 +0000315 ContinueBlock = llvm::BasicBlock::Create("forinc");
Chris Lattnerda138702007-07-16 21:28:45 +0000316 else
317 ContinueBlock = CondBlock;
318
319 // Store the blocks to use for break and continue.
320 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
321
Reid Spencer5f016e22007-07-11 17:01:13 +0000322 // If the condition is true, execute the body of the for stmt.
323 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000324
325 BreakContinueStack.pop_back();
326
327 if (S.getInc())
328 EmitBlock(ContinueBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000329
330 // If there is an increment, emit it next.
331 if (S.getInc())
Chris Lattner883f6a72007-08-11 00:04:45 +0000332 EmitStmt(S.getInc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000333
334 // Finally, branch back up to the condition for the next iteration.
335 Builder.CreateBr(CondBlock);
336
Chris Lattnerda138702007-07-16 21:28:45 +0000337 // Emit the fall-through block.
338 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000339}
340
341/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
342/// if the function returns void, or may be missing one if the function returns
343/// non-void. Fun stuff :).
344void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000345 // Emit the result value, even if unused, to evalute the side effects.
346 const Expr *RV = S.getRetValue();
Chris Lattner4b0029d2007-08-26 07:14:44 +0000347
Eli Friedman144ac612008-05-22 01:22:33 +0000348 llvm::Value* RetValue = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000349 if (FnRetTy->isVoidType()) {
Eli Friedman144ac612008-05-22 01:22:33 +0000350 // Make sure not to return anything
351 if (RV) {
352 // Evaluate the expression for side effects
353 EmitAnyExpr(RV);
354 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000355 } else if (RV == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 const llvm::Type *RetTy = CurFn->getFunctionType()->getReturnType();
Eli Friedman144ac612008-05-22 01:22:33 +0000357 if (RetTy != llvm::Type::VoidTy) {
358 // Handle "return;" in a function that returns a value.
359 RetValue = llvm::UndefValue::get(RetTy);
360 }
Chris Lattner4b0029d2007-08-26 07:14:44 +0000361 } else if (!hasAggregateLLVMType(RV->getType())) {
Eli Friedman144ac612008-05-22 01:22:33 +0000362 RetValue = EmitScalarExpr(RV);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000363 } else if (RV->getType()->isAnyComplexType()) {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000364 llvm::Value *SRetPtr = CurFn->arg_begin();
Chris Lattner190dbe22007-08-26 16:22:13 +0000365 EmitComplexExprIntoAddr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000366 } else {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000367 llvm::Value *SRetPtr = CurFn->arg_begin();
368 EmitAggExpr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 }
Eli Friedman144ac612008-05-22 01:22:33 +0000370
Eli Friedman3f2af102008-05-22 01:40:10 +0000371 CGDebugInfo *DI = CGM.getDebugInfo();
372 if (DI) {
373 CompoundStmt* body = cast<CompoundStmt>(CurFuncDecl->getBody());
374 if (body->getRBracLoc().isValid()) {
375 DI->setLocation(body->getRBracLoc());
376 }
377 DI->EmitFunctionEnd(CurFn, Builder);
378 }
379
Eli Friedman144ac612008-05-22 01:22:33 +0000380 if (RetValue) {
381 Builder.CreateRet(RetValue);
382 } else {
383 Builder.CreateRetVoid();
384 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000385
386 // Emit a block after the branch so that dead code after a return has some
387 // place to go.
Gabor Greif984d0b42008-04-06 20:42:52 +0000388 EmitBlock(llvm::BasicBlock::Create());
Reid Spencer5f016e22007-07-11 17:01:13 +0000389}
390
391void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Steve Naroff94745042007-09-13 23:52:58 +0000392 for (const ScopedDecl *Decl = S.getDecl(); Decl;
393 Decl = Decl->getNextDeclarator())
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 EmitDecl(*Decl);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000395}
Chris Lattnerda138702007-07-16 21:28:45 +0000396
397void CodeGenFunction::EmitBreakStmt() {
398 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
399
400 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
401 Builder.CreateBr(Block);
Gabor Greif984d0b42008-04-06 20:42:52 +0000402 EmitBlock(llvm::BasicBlock::Create());
Chris Lattnerda138702007-07-16 21:28:45 +0000403}
404
405void CodeGenFunction::EmitContinueStmt() {
406 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
407
408 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
409 Builder.CreateBr(Block);
Gabor Greif984d0b42008-04-06 20:42:52 +0000410 EmitBlock(llvm::BasicBlock::Create());
Chris Lattnerda138702007-07-16 21:28:45 +0000411}
Devang Patel51b09f22007-10-04 23:45:31 +0000412
Devang Patelc049e4f2007-10-08 20:57:48 +0000413/// EmitCaseStmtRange - If case statement range is not too big then
414/// add multiple cases to switch instruction, one for each value within
415/// the range. If range is too big then emit "if" condition check.
416void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
417 assert (S.getRHS() && "Unexpected RHS value in CaseStmt");
418
419 const Expr *L = S.getLHS();
420 const Expr *R = S.getRHS();
421 llvm::ConstantInt *LV = cast<llvm::ConstantInt>(EmitScalarExpr(L));
422 llvm::ConstantInt *RV = cast<llvm::ConstantInt>(EmitScalarExpr(R));
423 llvm::APInt LHS = LV->getValue();
Devang Patel00ee4e42007-10-09 17:10:59 +0000424 const llvm::APInt &RHS = RV->getValue();
Devang Patelc049e4f2007-10-08 20:57:48 +0000425
426 llvm::APInt Range = RHS - LHS;
427 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
428 // Range is small enough to add multiple switch instruction cases.
429 StartBlock("sw.bb");
430 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
431 SwitchInsn->addCase(LV, CaseDest);
Devang Patel2d79d0f2007-10-05 20:54:07 +0000432 LHS++;
433 while (LHS != RHS) {
434 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
435 LHS++;
436 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000437 SwitchInsn->addCase(RV, CaseDest);
438 EmitStmt(S.getSubStmt());
439 return;
440 }
441
442 // The range is too big. Emit "if" condition.
443 llvm::BasicBlock *FalseDest = NULL;
Gabor Greif984d0b42008-04-06 20:42:52 +0000444 llvm::BasicBlock *CaseDest = llvm::BasicBlock::Create("sw.bb");
Devang Patel2d79d0f2007-10-05 20:54:07 +0000445
Devang Patelc049e4f2007-10-08 20:57:48 +0000446 // If we have already seen one case statement range for this switch
447 // instruction then piggy-back otherwise use default block as false
448 // destination.
449 if (CaseRangeBlock)
450 FalseDest = CaseRangeBlock;
451 else
452 FalseDest = SwitchInsn->getDefaultDest();
453
454 // Start new block to hold case statement range check instructions.
455 StartBlock("case.range");
456 CaseRangeBlock = Builder.GetInsertBlock();
457
458 // Emit range check.
459 llvm::Value *Diff =
460 Builder.CreateSub(SwitchInsn->getCondition(), LV, "tmp");
461 llvm::Value *Cond =
462 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
463 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
464
465 // Now emit case statement body.
466 EmitBlock(CaseDest);
467 EmitStmt(S.getSubStmt());
468}
469
470void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
471 if (S.getRHS()) {
472 EmitCaseStmtRange(S);
473 return;
474 }
475
476 StartBlock("sw.bb");
477 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Chris Lattnerc69a5812007-11-30 17:44:57 +0000478 llvm::APSInt CaseVal(32);
479 S.getLHS()->isIntegerConstantExpr(CaseVal, getContext());
480 llvm::ConstantInt *LV = llvm::ConstantInt::get(CaseVal);
Devang Patelc049e4f2007-10-08 20:57:48 +0000481 SwitchInsn->addCase(LV, CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000482 EmitStmt(S.getSubStmt());
483}
484
485void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
486 StartBlock("sw.default");
487 // Current insert block is the default destination.
488 SwitchInsn->setSuccessor(0, Builder.GetInsertBlock());
489 EmitStmt(S.getSubStmt());
490}
491
492void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
493 llvm::Value *CondV = EmitScalarExpr(S.getCond());
494
495 // Handle nested switch statements.
496 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000497 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
498 CaseRangeBlock = NULL;
Devang Patel51b09f22007-10-04 23:45:31 +0000499
500 // Create basic block to hold stuff that comes after switch statement.
501 // Initially use it to hold DefaultStmt.
Gabor Greif984d0b42008-04-06 20:42:52 +0000502 llvm::BasicBlock *NextBlock = llvm::BasicBlock::Create("after.sw");
Devang Patel51b09f22007-10-04 23:45:31 +0000503 SwitchInsn = Builder.CreateSwitch(CondV, NextBlock);
504
Eli Friedmand28a80d2008-05-12 16:08:04 +0000505 // Create basic block for body of switch
506 StartBlock("body.sw");
507
Devang Patele9b8c0a2007-10-30 20:59:40 +0000508 // All break statements jump to NextBlock. If BreakContinueStack is non empty
509 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000510 llvm::BasicBlock *ContinueBlock = NULL;
511 if (!BreakContinueStack.empty())
512 ContinueBlock = BreakContinueStack.back().ContinueBlock;
513 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
514
515 // Emit switch body.
516 EmitStmt(S.getBody());
517 BreakContinueStack.pop_back();
518
Devang Patelc049e4f2007-10-08 20:57:48 +0000519 // If one or more case statement range is seen then use CaseRangeBlock
520 // as the default block. False edge of CaseRangeBlock will lead to
521 // original default block.
522 if (CaseRangeBlock)
523 SwitchInsn->setSuccessor(0, CaseRangeBlock);
524
Devang Patel51b09f22007-10-04 23:45:31 +0000525 // Prune insert block if it is dummy.
526 llvm::BasicBlock *BB = Builder.GetInsertBlock();
527 if (isDummyBlock(BB))
528 BB->eraseFromParent();
Chris Lattner1438b492007-12-01 05:27:33 +0000529 else // Otherwise, branch to continuation.
530 Builder.CreateBr(NextBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000531
532 // Place NextBlock as the new insert point.
Chris Lattner1438b492007-12-01 05:27:33 +0000533 CurFn->getBasicBlockList().push_back(NextBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000534 Builder.SetInsertPoint(NextBlock);
535 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000536 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000537}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000538
539static inline std::string ConvertAsmString(const char *Start,
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000540 unsigned NumOperands,
541 bool IsSimple)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000542{
543 static unsigned AsmCounter = 0;
544
545 AsmCounter++;
546
547 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000548 if (IsSimple) {
549 while (*Start) {
550 switch (*Start) {
551 default:
552 Result += *Start;
553 break;
554 case '$':
555 Result += "$$";
556 break;
557 }
558
559 Start++;
560 }
561
562 return Result;
563 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000564
565 while (*Start) {
566 switch (*Start) {
567 default:
568 Result += *Start;
569 break;
570 case '$':
571 Result += "$$";
572 break;
573 case '%':
574 // Escaped character
575 Start++;
576 if (!*Start) {
577 // FIXME: This should be caught during Sema.
578 assert(0 && "Trailing '%' in asm string.");
579 }
580
581 char EscapedChar = *Start;
582 if (EscapedChar == '%') {
583 // Escaped percentage sign.
584 Result += '%';
585 }
586 else if (EscapedChar == '=') {
587 // Generate an unique ID.
588 Result += llvm::utostr(AsmCounter);
589 } else if (isdigit(EscapedChar)) {
590 // %n - Assembler operand n
591 char *End;
592
593 unsigned long n = strtoul(Start, &End, 10);
594 if (Start == End) {
595 // FIXME: This should be caught during Sema.
596 assert(0 && "Missing operand!");
597 } else if (n >= NumOperands) {
598 // FIXME: This should be caught during Sema.
599 assert(0 && "Operand number out of range!");
600 }
601
602 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000603 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000604 } else if (isalpha(EscapedChar)) {
605 char *End;
606
607 unsigned long n = strtoul(Start + 1, &End, 10);
608 if (Start == End) {
609 // FIXME: This should be caught during Sema.
610 assert(0 && "Missing operand!");
611 } else if (n >= NumOperands) {
612 // FIXME: This should be caught during Sema.
613 assert(0 && "Operand number out of range!");
614 }
615
616 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000617 Start = End - 1;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000618 } else {
619 assert(0 && "Unhandled asm escaped character!");
620 }
621 }
622 Start++;
623 }
624
625 return Result;
626}
627
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000628static std::string SimplifyConstraint(const char* Constraint,
629 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000630 std::string Result;
631
632 while (*Constraint) {
633 switch (*Constraint) {
634 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000635 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000636 break;
637 // Ignore these
638 case '*':
639 case '?':
640 case '!':
641 break;
642 case 'g':
643 Result += "imr";
644 break;
645 }
646
647 Constraint++;
648 }
649
650 return Result;
651}
652
653void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
654 std::string AsmString =
655 ConvertAsmString(std::string(S.getAsmString()->getStrData(),
656 S.getAsmString()->getByteLength()).c_str(),
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000657 S.getNumOutputs() + S.getNumInputs(), S.isSimple());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000658
659 std::string Constraints;
660
661 llvm::Value *ResultAddr = 0;
662 const llvm::Type *ResultType = llvm::Type::VoidTy;
663
664 std::vector<const llvm::Type*> ArgTypes;
665 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000666
667 // Keep track of inout constraints.
668 std::string InOutConstraints;
669 std::vector<llvm::Value*> InOutArgs;
670 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000671
672 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
673 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
674 S.getOutputConstraint(i)->getByteLength());
675
676 TargetInfo::ConstraintInfo Info;
677 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
678 Info);
679 assert(result && "Failed to parse output constraint");
680
681 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000682 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000683
684 LValue Dest = EmitLValue(S.getOutputExpr(i));
685 const llvm::Type *DestValueType =
686 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
687
688 // If the first output operand is not a memory dest, we'll
689 // make it the return value.
690 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000691 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000692 ResultAddr = Dest.getAddress();
693 ResultType = DestValueType;
694 Constraints += "=" + OutputConstraint;
695 } else {
696 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000697 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000698 if (i != 0)
699 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000700 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000701 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000702 }
703
704 if (Info & TargetInfo::CI_ReadWrite) {
705 // FIXME: This code should be shared with the code that handles inputs.
706 InOutConstraints += ',';
707
708 const Expr *InputExpr = S.getOutputExpr(i);
709 llvm::Value *Arg;
710 if ((Info & TargetInfo::CI_AllowsRegister) ||
711 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000712 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000713 Arg = EmitScalarExpr(InputExpr);
714 } else {
Dan Gohmand79a7262008-05-22 22:12:56 +0000715 assert(0 && "FIXME: Implement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000716 }
717 } else {
718 LValue Dest = EmitLValue(InputExpr);
719 Arg = Dest.getAddress();
720 InOutConstraints += '*';
721 }
722
723 InOutArgTypes.push_back(Arg->getType());
724 InOutArgs.push_back(Arg);
725 InOutConstraints += OutputConstraint;
726 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000727 }
728
729 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
730
731 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
732 const Expr *InputExpr = S.getInputExpr(i);
733
734 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
735 S.getInputConstraint(i)->getByteLength());
736
737 TargetInfo::ConstraintInfo Info;
738 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
739 NumConstraints,
740 Info);
741 assert(result && "Failed to parse input constraint");
742
743 if (i != 0 || S.getNumOutputs() > 0)
744 Constraints += ',';
745
746 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000747 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000748
749 llvm::Value *Arg;
750
751 if ((Info & TargetInfo::CI_AllowsRegister) ||
752 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000753 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000754 Arg = EmitScalarExpr(InputExpr);
755 } else {
Dan Gohmand79a7262008-05-22 22:12:56 +0000756 assert(0 && "FIXME: Implement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000757 }
758 } else {
759 LValue Dest = EmitLValue(InputExpr);
760 Arg = Dest.getAddress();
761 Constraints += '*';
762 }
763
764 ArgTypes.push_back(Arg->getType());
765 Args.push_back(Arg);
766 Constraints += InputConstraint;
767 }
768
Anders Carlssonf39a4212008-02-05 20:01:53 +0000769 // Append the "input" part of inout constraints last.
770 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
771 ArgTypes.push_back(InOutArgTypes[i]);
772 Args.push_back(InOutArgs[i]);
773 }
774 Constraints += InOutConstraints;
775
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000776 // Clobbers
777 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
778 std::string Clobber(S.getClobber(i)->getStrData(),
779 S.getClobber(i)->getByteLength());
780
781 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
782
Anders Carlssonea041752008-02-06 00:11:32 +0000783 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000784 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000785
786 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000787 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000788 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000789 }
790
791 // Add machine specific clobbers
792 if (const char *C = Target.getClobbers()) {
793 if (!Constraints.empty())
794 Constraints += ',';
795 Constraints += C;
796 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000797
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000798 const llvm::FunctionType *FTy =
799 llvm::FunctionType::get(ResultType, ArgTypes, false);
800
801 llvm::InlineAsm *IA =
802 llvm::InlineAsm::get(FTy, AsmString, Constraints,
803 S.isVolatile() || S.getNumOutputs() == 0);
804 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
805 if (ResultAddr)
806 Builder.CreateStore(Result, ResultAddr);
807}