blob: 4a41a4962f1191a333f4557431e63a0f42569bee [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
14#include "CodeGenFunction.h"
15#include "clang/AST/AST.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000016#include "clang/Basic/TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Function.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000020#include "llvm/InlineAsm.h"
21#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23using namespace CodeGen;
24
25//===----------------------------------------------------------------------===//
26// Statement Emission
27//===----------------------------------------------------------------------===//
28
29void CodeGenFunction::EmitStmt(const Stmt *S) {
30 assert(S && "Null statement?");
31
32 switch (S->getStmtClass()) {
33 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000034 // Must be an expression in a stmt context. Emit the value (to get
35 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000036 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000037 if (!hasAggregateLLVMType(E->getType()))
38 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000039 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000040 EmitComplexExpr(E);
41 else
42 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000043 } else {
Chris Lattnerdc4d2802007-12-02 01:49:16 +000044 WarnUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000045 }
46 break;
47 case Stmt::NullStmtClass: break;
48 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
49 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
50 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
51
52 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
53 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
54 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
55 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
56
57 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
58 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Chris Lattnerda138702007-07-16 21:28:45 +000059
60 case Stmt::BreakStmtClass: EmitBreakStmt(); break;
61 case Stmt::ContinueStmtClass: EmitContinueStmt(); break;
Devang Patel51b09f22007-10-04 23:45:31 +000062 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
63 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
64 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000065 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000066 }
67}
68
Chris Lattner33793202007-08-31 22:09:40 +000069/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
70/// this captures the expression result of the last sub-statement and returns it
71/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +000072RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
73 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +000074 // FIXME: handle vla's etc.
Chris Lattner33793202007-08-31 22:09:40 +000075 if (S.body_empty() || !isa<Expr>(S.body_back())) GetLast = false;
Reid Spencer5f016e22007-07-11 17:01:13 +000076
Chris Lattner33793202007-08-31 22:09:40 +000077 for (CompoundStmt::const_body_iterator I = S.body_begin(),
78 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +000079 EmitStmt(*I);
Chris Lattner33793202007-08-31 22:09:40 +000080
81
82 if (!GetLast)
83 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +000084
85 return EmitAnyExpr(cast<Expr>(S.body_back()), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +000086}
87
88void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
89 // Emit a branch from this block to the next one if this was a real block. If
90 // this was just a fall-through block after a terminator, don't emit it.
91 llvm::BasicBlock *LastBB = Builder.GetInsertBlock();
92
93 if (LastBB->getTerminator()) {
94 // If the previous block is already terminated, don't touch it.
95 } else if (LastBB->empty() && LastBB->getValueName() == 0) {
96 // If the last block was an empty placeholder, remove it now.
97 // TODO: cache and reuse these.
98 Builder.GetInsertBlock()->eraseFromParent();
99 } else {
100 // Otherwise, create a fall-through branch.
101 Builder.CreateBr(BB);
102 }
103 CurFn->getBasicBlockList().push_back(BB);
104 Builder.SetInsertPoint(BB);
105}
106
107void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
108 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
109
110 EmitBlock(NextBB);
111 EmitStmt(S.getSubStmt());
112}
113
114void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
115 Builder.CreateBr(getBasicBlockForLabel(S.getLabel()));
116
117 // Emit a block after the branch so that dead code after a goto has some place
118 // to go.
119 Builder.SetInsertPoint(new llvm::BasicBlock("", CurFn));
120}
121
122void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
123 // C99 6.8.4.1: The first substatement is executed if the expression compares
124 // unequal to 0. The condition must be a scalar type.
125 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
126
127 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("ifend");
128 llvm::BasicBlock *ThenBlock = new llvm::BasicBlock("ifthen");
129 llvm::BasicBlock *ElseBlock = ContBlock;
130
131 if (S.getElse())
132 ElseBlock = new llvm::BasicBlock("ifelse");
133
134 // Insert the conditional branch.
135 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
136
137 // Emit the 'then' code.
138 EmitBlock(ThenBlock);
139 EmitStmt(S.getThen());
Devang Pateld9363c32007-09-28 21:49:18 +0000140 llvm::BasicBlock *BB = Builder.GetInsertBlock();
141 if (isDummyBlock(BB)) {
142 BB->eraseFromParent();
143 Builder.SetInsertPoint(ThenBlock);
144 }
145 else
146 Builder.CreateBr(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000147
148 // Emit the 'else' code if present.
149 if (const Stmt *Else = S.getElse()) {
150 EmitBlock(ElseBlock);
151 EmitStmt(Else);
Devang Pateld9363c32007-09-28 21:49:18 +0000152 llvm::BasicBlock *BB = Builder.GetInsertBlock();
153 if (isDummyBlock(BB)) {
154 BB->eraseFromParent();
155 Builder.SetInsertPoint(ElseBlock);
156 }
157 else
158 Builder.CreateBr(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 }
160
161 // Emit the continuation block for code after the if.
162 EmitBlock(ContBlock);
163}
164
165void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000166 // Emit the header for the loop, insert it, which will create an uncond br to
167 // it.
168 llvm::BasicBlock *LoopHeader = new llvm::BasicBlock("whilecond");
169 EmitBlock(LoopHeader);
170
171 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
172 // of the controlling expression takes place before each execution of the loop
173 // body.
174 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000175
176 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000177 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000178 bool EmitBoolCondBranch = true;
179 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
180 if (C->isOne())
181 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000182
183 // Create an exit block for when the condition fails, create a block for the
184 // body of the loop.
185 llvm::BasicBlock *ExitBlock = new llvm::BasicBlock("whileexit");
186 llvm::BasicBlock *LoopBody = new llvm::BasicBlock("whilebody");
187
188 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000189 if (EmitBoolCondBranch)
190 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000191
192 // Store the blocks to use for break and continue.
193 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000194
195 // Emit the loop body.
196 EmitBlock(LoopBody);
197 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000198
199 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000200
201 // Cycle to the condition.
202 Builder.CreateBr(LoopHeader);
203
204 // Emit the exit block.
205 EmitBlock(ExitBlock);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000206
207 // If LoopHeader is a simple forwarding block then eliminate it.
208 if (!EmitBoolCondBranch
209 && &LoopHeader->front() == LoopHeader->getTerminator()) {
210 LoopHeader->replaceAllUsesWith(LoopBody);
211 LoopHeader->getTerminator()->eraseFromParent();
212 LoopHeader->eraseFromParent();
213 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000214}
215
216void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000217 // Emit the body for the loop, insert it, which will create an uncond br to
218 // it.
219 llvm::BasicBlock *LoopBody = new llvm::BasicBlock("dobody");
220 llvm::BasicBlock *AfterDo = new llvm::BasicBlock("afterdo");
221 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000222
223 llvm::BasicBlock *DoCond = new llvm::BasicBlock("docond");
224
225 // Store the blocks to use for break and continue.
226 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000227
228 // Emit the body of the loop into the block.
229 EmitStmt(S.getBody());
230
Chris Lattnerda138702007-07-16 21:28:45 +0000231 BreakContinueStack.pop_back();
232
233 EmitBlock(DoCond);
234
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
236 // after each execution of the loop body."
237
238 // Evaluate the conditional in the while header.
239 // C99 6.8.5p2/p4: The first substatement is executed if the expression
240 // compares unequal to 0. The condition must be a scalar type.
241 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000242
243 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
244 // to correctly handle break/continue though.
245 bool EmitBoolCondBranch = true;
246 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
247 if (C->isZero())
248 EmitBoolCondBranch = false;
249
Reid Spencer5f016e22007-07-11 17:01:13 +0000250 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000251 if (EmitBoolCondBranch)
252 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000253
254 // Emit the exit block.
255 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000256
257 // If DoCond is a simple forwarding block then eliminate it.
258 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
259 DoCond->replaceAllUsesWith(AfterDo);
260 DoCond->getTerminator()->eraseFromParent();
261 DoCond->eraseFromParent();
262 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000263}
264
265void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000266 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
267 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000268 // TODO: We could keep track of whether the loop body contains any
269 // break/continue statements and not create unnecessary blocks (like
270 // "afterfor" for a condless loop) if it doesn't.
271
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 // Evaluate the first part before the loop.
273 if (S.getInit())
274 EmitStmt(S.getInit());
275
276 // Start the loop with a block that tests the condition.
277 llvm::BasicBlock *CondBlock = new llvm::BasicBlock("forcond");
Chris Lattnerda138702007-07-16 21:28:45 +0000278 llvm::BasicBlock *AfterFor = new llvm::BasicBlock("afterfor");
279
Reid Spencer5f016e22007-07-11 17:01:13 +0000280 EmitBlock(CondBlock);
281
282 // Evaluate the condition if present. If not, treat it as a non-zero-constant
283 // according to 6.8.5.3p2, aka, true.
284 if (S.getCond()) {
285 // C99 6.8.5p2/p4: The first substatement is executed if the expression
286 // compares unequal to 0. The condition must be a scalar type.
287 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
288
289 // As long as the condition is true, iterate the loop.
290 llvm::BasicBlock *ForBody = new llvm::BasicBlock("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000291 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
292 EmitBlock(ForBody);
293 } else {
294 // Treat it as a non-zero constant. Don't even create a new block for the
295 // body, just fall into it.
296 }
297
Chris Lattnerda138702007-07-16 21:28:45 +0000298 // If the for loop doesn't have an increment we can just use the
299 // condition as the continue block.
300 llvm::BasicBlock *ContinueBlock;
301 if (S.getInc())
302 ContinueBlock = new llvm::BasicBlock("forinc");
303 else
304 ContinueBlock = CondBlock;
305
306 // Store the blocks to use for break and continue.
307 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
308
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 // If the condition is true, execute the body of the for stmt.
310 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000311
312 BreakContinueStack.pop_back();
313
314 if (S.getInc())
315 EmitBlock(ContinueBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000316
317 // If there is an increment, emit it next.
318 if (S.getInc())
Chris Lattner883f6a72007-08-11 00:04:45 +0000319 EmitStmt(S.getInc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000320
321 // Finally, branch back up to the condition for the next iteration.
322 Builder.CreateBr(CondBlock);
323
Chris Lattnerda138702007-07-16 21:28:45 +0000324 // Emit the fall-through block.
325 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000326}
327
328/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
329/// if the function returns void, or may be missing one if the function returns
330/// non-void. Fun stuff :).
331void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000332 // Emit the result value, even if unused, to evalute the side effects.
333 const Expr *RV = S.getRetValue();
Chris Lattner4b0029d2007-08-26 07:14:44 +0000334
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 if (FnRetTy->isVoidType()) {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000336 // If the function returns void, emit ret void.
Reid Spencer5f016e22007-07-11 17:01:13 +0000337 Builder.CreateRetVoid();
338 } else if (RV == 0) {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000339 // Handle "return;" in a function that returns a value.
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 const llvm::Type *RetTy = CurFn->getFunctionType()->getReturnType();
341 if (RetTy == llvm::Type::VoidTy)
342 Builder.CreateRetVoid(); // struct return etc.
343 else
344 Builder.CreateRet(llvm::UndefValue::get(RetTy));
Chris Lattner4b0029d2007-08-26 07:14:44 +0000345 } else if (!hasAggregateLLVMType(RV->getType())) {
346 Builder.CreateRet(EmitScalarExpr(RV));
Chris Lattner9b2dc282008-04-04 16:54:41 +0000347 } else if (RV->getType()->isAnyComplexType()) {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000348 llvm::Value *SRetPtr = CurFn->arg_begin();
Chris Lattner190dbe22007-08-26 16:22:13 +0000349 EmitComplexExprIntoAddr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 } else {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000351 llvm::Value *SRetPtr = CurFn->arg_begin();
352 EmitAggExpr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 }
354
355 // Emit a block after the branch so that dead code after a return has some
356 // place to go.
357 EmitBlock(new llvm::BasicBlock());
358}
359
360void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Steve Naroff94745042007-09-13 23:52:58 +0000361 for (const ScopedDecl *Decl = S.getDecl(); Decl;
362 Decl = Decl->getNextDeclarator())
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 EmitDecl(*Decl);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000364}
Chris Lattnerda138702007-07-16 21:28:45 +0000365
366void CodeGenFunction::EmitBreakStmt() {
367 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
368
369 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
370 Builder.CreateBr(Block);
371 EmitBlock(new llvm::BasicBlock());
372}
373
374void CodeGenFunction::EmitContinueStmt() {
375 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
376
377 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
378 Builder.CreateBr(Block);
379 EmitBlock(new llvm::BasicBlock());
380}
Devang Patel51b09f22007-10-04 23:45:31 +0000381
Devang Patelc049e4f2007-10-08 20:57:48 +0000382/// EmitCaseStmtRange - If case statement range is not too big then
383/// add multiple cases to switch instruction, one for each value within
384/// the range. If range is too big then emit "if" condition check.
385void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
386 assert (S.getRHS() && "Unexpected RHS value in CaseStmt");
387
388 const Expr *L = S.getLHS();
389 const Expr *R = S.getRHS();
390 llvm::ConstantInt *LV = cast<llvm::ConstantInt>(EmitScalarExpr(L));
391 llvm::ConstantInt *RV = cast<llvm::ConstantInt>(EmitScalarExpr(R));
392 llvm::APInt LHS = LV->getValue();
Devang Patel00ee4e42007-10-09 17:10:59 +0000393 const llvm::APInt &RHS = RV->getValue();
Devang Patelc049e4f2007-10-08 20:57:48 +0000394
395 llvm::APInt Range = RHS - LHS;
396 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
397 // Range is small enough to add multiple switch instruction cases.
398 StartBlock("sw.bb");
399 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
400 SwitchInsn->addCase(LV, CaseDest);
Devang Patel2d79d0f2007-10-05 20:54:07 +0000401 LHS++;
402 while (LHS != RHS) {
403 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
404 LHS++;
405 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000406 SwitchInsn->addCase(RV, CaseDest);
407 EmitStmt(S.getSubStmt());
408 return;
409 }
410
411 // The range is too big. Emit "if" condition.
412 llvm::BasicBlock *FalseDest = NULL;
413 llvm::BasicBlock *CaseDest = new llvm::BasicBlock("sw.bb");
Devang Patel2d79d0f2007-10-05 20:54:07 +0000414
Devang Patelc049e4f2007-10-08 20:57:48 +0000415 // If we have already seen one case statement range for this switch
416 // instruction then piggy-back otherwise use default block as false
417 // destination.
418 if (CaseRangeBlock)
419 FalseDest = CaseRangeBlock;
420 else
421 FalseDest = SwitchInsn->getDefaultDest();
422
423 // Start new block to hold case statement range check instructions.
424 StartBlock("case.range");
425 CaseRangeBlock = Builder.GetInsertBlock();
426
427 // Emit range check.
428 llvm::Value *Diff =
429 Builder.CreateSub(SwitchInsn->getCondition(), LV, "tmp");
430 llvm::Value *Cond =
431 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
432 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
433
434 // Now emit case statement body.
435 EmitBlock(CaseDest);
436 EmitStmt(S.getSubStmt());
437}
438
439void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
440 if (S.getRHS()) {
441 EmitCaseStmtRange(S);
442 return;
443 }
444
445 StartBlock("sw.bb");
446 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Chris Lattnerc69a5812007-11-30 17:44:57 +0000447 llvm::APSInt CaseVal(32);
448 S.getLHS()->isIntegerConstantExpr(CaseVal, getContext());
449 llvm::ConstantInt *LV = llvm::ConstantInt::get(CaseVal);
Devang Patelc049e4f2007-10-08 20:57:48 +0000450 SwitchInsn->addCase(LV, CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000451 EmitStmt(S.getSubStmt());
452}
453
454void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
455 StartBlock("sw.default");
456 // Current insert block is the default destination.
457 SwitchInsn->setSuccessor(0, Builder.GetInsertBlock());
458 EmitStmt(S.getSubStmt());
459}
460
461void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
462 llvm::Value *CondV = EmitScalarExpr(S.getCond());
463
464 // Handle nested switch statements.
465 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000466 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
467 CaseRangeBlock = NULL;
Devang Patel51b09f22007-10-04 23:45:31 +0000468
469 // Create basic block to hold stuff that comes after switch statement.
470 // Initially use it to hold DefaultStmt.
Chris Lattner1438b492007-12-01 05:27:33 +0000471 llvm::BasicBlock *NextBlock = new llvm::BasicBlock("after.sw");
Devang Patel51b09f22007-10-04 23:45:31 +0000472 SwitchInsn = Builder.CreateSwitch(CondV, NextBlock);
473
Devang Patele9b8c0a2007-10-30 20:59:40 +0000474 // All break statements jump to NextBlock. If BreakContinueStack is non empty
475 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000476 llvm::BasicBlock *ContinueBlock = NULL;
477 if (!BreakContinueStack.empty())
478 ContinueBlock = BreakContinueStack.back().ContinueBlock;
479 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
480
481 // Emit switch body.
482 EmitStmt(S.getBody());
483 BreakContinueStack.pop_back();
484
Devang Patelc049e4f2007-10-08 20:57:48 +0000485 // If one or more case statement range is seen then use CaseRangeBlock
486 // as the default block. False edge of CaseRangeBlock will lead to
487 // original default block.
488 if (CaseRangeBlock)
489 SwitchInsn->setSuccessor(0, CaseRangeBlock);
490
Devang Patel51b09f22007-10-04 23:45:31 +0000491 // Prune insert block if it is dummy.
492 llvm::BasicBlock *BB = Builder.GetInsertBlock();
493 if (isDummyBlock(BB))
494 BB->eraseFromParent();
Chris Lattner1438b492007-12-01 05:27:33 +0000495 else // Otherwise, branch to continuation.
496 Builder.CreateBr(NextBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000497
498 // Place NextBlock as the new insert point.
Chris Lattner1438b492007-12-01 05:27:33 +0000499 CurFn->getBasicBlockList().push_back(NextBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000500 Builder.SetInsertPoint(NextBlock);
501 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000502 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000503}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000504
505static inline std::string ConvertAsmString(const char *Start,
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000506 unsigned NumOperands,
507 bool IsSimple)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000508{
509 static unsigned AsmCounter = 0;
510
511 AsmCounter++;
512
513 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000514 if (IsSimple) {
515 while (*Start) {
516 switch (*Start) {
517 default:
518 Result += *Start;
519 break;
520 case '$':
521 Result += "$$";
522 break;
523 }
524
525 Start++;
526 }
527
528 return Result;
529 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000530
531 while (*Start) {
532 switch (*Start) {
533 default:
534 Result += *Start;
535 break;
536 case '$':
537 Result += "$$";
538 break;
539 case '%':
540 // Escaped character
541 Start++;
542 if (!*Start) {
543 // FIXME: This should be caught during Sema.
544 assert(0 && "Trailing '%' in asm string.");
545 }
546
547 char EscapedChar = *Start;
548 if (EscapedChar == '%') {
549 // Escaped percentage sign.
550 Result += '%';
551 }
552 else if (EscapedChar == '=') {
553 // Generate an unique ID.
554 Result += llvm::utostr(AsmCounter);
555 } else if (isdigit(EscapedChar)) {
556 // %n - Assembler operand n
557 char *End;
558
559 unsigned long n = strtoul(Start, &End, 10);
560 if (Start == End) {
561 // FIXME: This should be caught during Sema.
562 assert(0 && "Missing operand!");
563 } else if (n >= NumOperands) {
564 // FIXME: This should be caught during Sema.
565 assert(0 && "Operand number out of range!");
566 }
567
568 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000569 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000570 } else if (isalpha(EscapedChar)) {
571 char *End;
572
573 unsigned long n = strtoul(Start + 1, &End, 10);
574 if (Start == End) {
575 // FIXME: This should be caught during Sema.
576 assert(0 && "Missing operand!");
577 } else if (n >= NumOperands) {
578 // FIXME: This should be caught during Sema.
579 assert(0 && "Operand number out of range!");
580 }
581
582 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000583 Start = End - 1;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000584 } else {
585 assert(0 && "Unhandled asm escaped character!");
586 }
587 }
588 Start++;
589 }
590
591 return Result;
592}
593
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000594static std::string SimplifyConstraint(const char* Constraint,
595 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000596 std::string Result;
597
598 while (*Constraint) {
599 switch (*Constraint) {
600 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000601 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000602 break;
603 // Ignore these
604 case '*':
605 case '?':
606 case '!':
607 break;
608 case 'g':
609 Result += "imr";
610 break;
611 }
612
613 Constraint++;
614 }
615
616 return Result;
617}
618
619void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
620 std::string AsmString =
621 ConvertAsmString(std::string(S.getAsmString()->getStrData(),
622 S.getAsmString()->getByteLength()).c_str(),
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000623 S.getNumOutputs() + S.getNumInputs(), S.isSimple());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000624
625 std::string Constraints;
626
627 llvm::Value *ResultAddr = 0;
628 const llvm::Type *ResultType = llvm::Type::VoidTy;
629
630 std::vector<const llvm::Type*> ArgTypes;
631 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000632
633 // Keep track of inout constraints.
634 std::string InOutConstraints;
635 std::vector<llvm::Value*> InOutArgs;
636 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000637
638 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
639 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
640 S.getOutputConstraint(i)->getByteLength());
641
642 TargetInfo::ConstraintInfo Info;
643 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
644 Info);
645 assert(result && "Failed to parse output constraint");
646
647 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000648 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000649
650 LValue Dest = EmitLValue(S.getOutputExpr(i));
651 const llvm::Type *DestValueType =
652 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
653
654 // If the first output operand is not a memory dest, we'll
655 // make it the return value.
656 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
657 DestValueType->isFirstClassType()) {
658 ResultAddr = Dest.getAddress();
659 ResultType = DestValueType;
660 Constraints += "=" + OutputConstraint;
661 } else {
662 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000663 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000664 if (i != 0)
665 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000666 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000667 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000668 }
669
670 if (Info & TargetInfo::CI_ReadWrite) {
671 // FIXME: This code should be shared with the code that handles inputs.
672 InOutConstraints += ',';
673
674 const Expr *InputExpr = S.getOutputExpr(i);
675 llvm::Value *Arg;
676 if ((Info & TargetInfo::CI_AllowsRegister) ||
677 !(Info & TargetInfo::CI_AllowsMemory)) {
678 if (ConvertType(InputExpr->getType())->isFirstClassType()) {
679 Arg = EmitScalarExpr(InputExpr);
680 } else {
681 assert(0 && "FIXME: Implement passing non first class types as inputs");
682 }
683 } else {
684 LValue Dest = EmitLValue(InputExpr);
685 Arg = Dest.getAddress();
686 InOutConstraints += '*';
687 }
688
689 InOutArgTypes.push_back(Arg->getType());
690 InOutArgs.push_back(Arg);
691 InOutConstraints += OutputConstraint;
692 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000693 }
694
695 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
696
697 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
698 const Expr *InputExpr = S.getInputExpr(i);
699
700 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
701 S.getInputConstraint(i)->getByteLength());
702
703 TargetInfo::ConstraintInfo Info;
704 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
705 NumConstraints,
706 Info);
707 assert(result && "Failed to parse input constraint");
708
709 if (i != 0 || S.getNumOutputs() > 0)
710 Constraints += ',';
711
712 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000713 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000714
715 llvm::Value *Arg;
716
717 if ((Info & TargetInfo::CI_AllowsRegister) ||
718 !(Info & TargetInfo::CI_AllowsMemory)) {
719 if (ConvertType(InputExpr->getType())->isFirstClassType()) {
720 Arg = EmitScalarExpr(InputExpr);
721 } else {
722 assert(0 && "FIXME: Implement passing non first class types as inputs");
723 }
724 } else {
725 LValue Dest = EmitLValue(InputExpr);
726 Arg = Dest.getAddress();
727 Constraints += '*';
728 }
729
730 ArgTypes.push_back(Arg->getType());
731 Args.push_back(Arg);
732 Constraints += InputConstraint;
733 }
734
Anders Carlssonf39a4212008-02-05 20:01:53 +0000735 // Append the "input" part of inout constraints last.
736 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
737 ArgTypes.push_back(InOutArgTypes[i]);
738 Args.push_back(InOutArgs[i]);
739 }
740 Constraints += InOutConstraints;
741
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000742 // Clobbers
743 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
744 std::string Clobber(S.getClobber(i)->getStrData(),
745 S.getClobber(i)->getByteLength());
746
747 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
748
Anders Carlssonea041752008-02-06 00:11:32 +0000749 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000750 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000751
752 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000753 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000754 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000755 }
756
757 // Add machine specific clobbers
758 if (const char *C = Target.getClobbers()) {
759 if (!Constraints.empty())
760 Constraints += ',';
761 Constraints += C;
762 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000763
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000764 const llvm::FunctionType *FTy =
765 llvm::FunctionType::get(ResultType, ArgTypes, false);
766
767 llvm::InlineAsm *IA =
768 llvm::InlineAsm::get(FTy, AsmString, Constraints,
769 S.isVolatile() || S.getNumOutputs() == 0);
770 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
771 if (ResultAddr)
772 Builder.CreateStore(Result, ResultAddr);
773}