blob: 5fdc61b46f8894dc105df68470e74a3ca2baefd8 [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);
39 else if (E->getType()->isComplexType())
40 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 QualType FnRetTy = CurFuncDecl->getType().getCanonicalType();
336 FnRetTy = cast<FunctionType>(FnRetTy)->getResultType();
337
338 if (FnRetTy->isVoidType()) {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000339 // If the function returns void, emit ret void.
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 Builder.CreateRetVoid();
341 } else if (RV == 0) {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000342 // Handle "return;" in a function that returns a value.
Reid Spencer5f016e22007-07-11 17:01:13 +0000343 const llvm::Type *RetTy = CurFn->getFunctionType()->getReturnType();
344 if (RetTy == llvm::Type::VoidTy)
345 Builder.CreateRetVoid(); // struct return etc.
346 else
347 Builder.CreateRet(llvm::UndefValue::get(RetTy));
Chris Lattner4b0029d2007-08-26 07:14:44 +0000348 } else if (!hasAggregateLLVMType(RV->getType())) {
349 Builder.CreateRet(EmitScalarExpr(RV));
350 } else if (RV->getType()->isComplexType()) {
351 llvm::Value *SRetPtr = CurFn->arg_begin();
Chris Lattner190dbe22007-08-26 16:22:13 +0000352 EmitComplexExprIntoAddr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 } else {
Chris Lattner4b0029d2007-08-26 07:14:44 +0000354 llvm::Value *SRetPtr = CurFn->arg_begin();
355 EmitAggExpr(RV, SRetPtr, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 }
357
358 // Emit a block after the branch so that dead code after a return has some
359 // place to go.
360 EmitBlock(new llvm::BasicBlock());
361}
362
363void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Steve Naroff94745042007-09-13 23:52:58 +0000364 for (const ScopedDecl *Decl = S.getDecl(); Decl;
365 Decl = Decl->getNextDeclarator())
Reid Spencer5f016e22007-07-11 17:01:13 +0000366 EmitDecl(*Decl);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000367}
Chris Lattnerda138702007-07-16 21:28:45 +0000368
369void CodeGenFunction::EmitBreakStmt() {
370 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
371
372 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
373 Builder.CreateBr(Block);
374 EmitBlock(new llvm::BasicBlock());
375}
376
377void CodeGenFunction::EmitContinueStmt() {
378 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
379
380 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
381 Builder.CreateBr(Block);
382 EmitBlock(new llvm::BasicBlock());
383}
Devang Patel51b09f22007-10-04 23:45:31 +0000384
Devang Patelc049e4f2007-10-08 20:57:48 +0000385/// EmitCaseStmtRange - If case statement range is not too big then
386/// add multiple cases to switch instruction, one for each value within
387/// the range. If range is too big then emit "if" condition check.
388void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
389 assert (S.getRHS() && "Unexpected RHS value in CaseStmt");
390
391 const Expr *L = S.getLHS();
392 const Expr *R = S.getRHS();
393 llvm::ConstantInt *LV = cast<llvm::ConstantInt>(EmitScalarExpr(L));
394 llvm::ConstantInt *RV = cast<llvm::ConstantInt>(EmitScalarExpr(R));
395 llvm::APInt LHS = LV->getValue();
Devang Patel00ee4e42007-10-09 17:10:59 +0000396 const llvm::APInt &RHS = RV->getValue();
Devang Patelc049e4f2007-10-08 20:57:48 +0000397
398 llvm::APInt Range = RHS - LHS;
399 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
400 // Range is small enough to add multiple switch instruction cases.
401 StartBlock("sw.bb");
402 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
403 SwitchInsn->addCase(LV, CaseDest);
Devang Patel2d79d0f2007-10-05 20:54:07 +0000404 LHS++;
405 while (LHS != RHS) {
406 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
407 LHS++;
408 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000409 SwitchInsn->addCase(RV, CaseDest);
410 EmitStmt(S.getSubStmt());
411 return;
412 }
413
414 // The range is too big. Emit "if" condition.
415 llvm::BasicBlock *FalseDest = NULL;
416 llvm::BasicBlock *CaseDest = new llvm::BasicBlock("sw.bb");
Devang Patel2d79d0f2007-10-05 20:54:07 +0000417
Devang Patelc049e4f2007-10-08 20:57:48 +0000418 // If we have already seen one case statement range for this switch
419 // instruction then piggy-back otherwise use default block as false
420 // destination.
421 if (CaseRangeBlock)
422 FalseDest = CaseRangeBlock;
423 else
424 FalseDest = SwitchInsn->getDefaultDest();
425
426 // Start new block to hold case statement range check instructions.
427 StartBlock("case.range");
428 CaseRangeBlock = Builder.GetInsertBlock();
429
430 // Emit range check.
431 llvm::Value *Diff =
432 Builder.CreateSub(SwitchInsn->getCondition(), LV, "tmp");
433 llvm::Value *Cond =
434 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
435 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
436
437 // Now emit case statement body.
438 EmitBlock(CaseDest);
439 EmitStmt(S.getSubStmt());
440}
441
442void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
443 if (S.getRHS()) {
444 EmitCaseStmtRange(S);
445 return;
446 }
447
448 StartBlock("sw.bb");
449 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Chris Lattnerc69a5812007-11-30 17:44:57 +0000450 llvm::APSInt CaseVal(32);
451 S.getLHS()->isIntegerConstantExpr(CaseVal, getContext());
452 llvm::ConstantInt *LV = llvm::ConstantInt::get(CaseVal);
Devang Patelc049e4f2007-10-08 20:57:48 +0000453 SwitchInsn->addCase(LV, CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000454 EmitStmt(S.getSubStmt());
455}
456
457void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
458 StartBlock("sw.default");
459 // Current insert block is the default destination.
460 SwitchInsn->setSuccessor(0, Builder.GetInsertBlock());
461 EmitStmt(S.getSubStmt());
462}
463
464void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
465 llvm::Value *CondV = EmitScalarExpr(S.getCond());
466
467 // Handle nested switch statements.
468 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000469 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
470 CaseRangeBlock = NULL;
Devang Patel51b09f22007-10-04 23:45:31 +0000471
472 // Create basic block to hold stuff that comes after switch statement.
473 // Initially use it to hold DefaultStmt.
Chris Lattner1438b492007-12-01 05:27:33 +0000474 llvm::BasicBlock *NextBlock = new llvm::BasicBlock("after.sw");
Devang Patel51b09f22007-10-04 23:45:31 +0000475 SwitchInsn = Builder.CreateSwitch(CondV, NextBlock);
476
Devang Patele9b8c0a2007-10-30 20:59:40 +0000477 // All break statements jump to NextBlock. If BreakContinueStack is non empty
478 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000479 llvm::BasicBlock *ContinueBlock = NULL;
480 if (!BreakContinueStack.empty())
481 ContinueBlock = BreakContinueStack.back().ContinueBlock;
482 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
483
484 // Emit switch body.
485 EmitStmt(S.getBody());
486 BreakContinueStack.pop_back();
487
Devang Patelc049e4f2007-10-08 20:57:48 +0000488 // If one or more case statement range is seen then use CaseRangeBlock
489 // as the default block. False edge of CaseRangeBlock will lead to
490 // original default block.
491 if (CaseRangeBlock)
492 SwitchInsn->setSuccessor(0, CaseRangeBlock);
493
Devang Patel51b09f22007-10-04 23:45:31 +0000494 // Prune insert block if it is dummy.
495 llvm::BasicBlock *BB = Builder.GetInsertBlock();
496 if (isDummyBlock(BB))
497 BB->eraseFromParent();
Chris Lattner1438b492007-12-01 05:27:33 +0000498 else // Otherwise, branch to continuation.
499 Builder.CreateBr(NextBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000500
501 // Place NextBlock as the new insert point.
Chris Lattner1438b492007-12-01 05:27:33 +0000502 CurFn->getBasicBlockList().push_back(NextBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000503 Builder.SetInsertPoint(NextBlock);
504 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000505 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000506}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000507
508static inline std::string ConvertAsmString(const char *Start,
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000509 unsigned NumOperands,
510 bool IsSimple)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000511{
512 static unsigned AsmCounter = 0;
513
514 AsmCounter++;
515
516 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000517 if (IsSimple) {
518 while (*Start) {
519 switch (*Start) {
520 default:
521 Result += *Start;
522 break;
523 case '$':
524 Result += "$$";
525 break;
526 }
527
528 Start++;
529 }
530
531 return Result;
532 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000533
534 while (*Start) {
535 switch (*Start) {
536 default:
537 Result += *Start;
538 break;
539 case '$':
540 Result += "$$";
541 break;
542 case '%':
543 // Escaped character
544 Start++;
545 if (!*Start) {
546 // FIXME: This should be caught during Sema.
547 assert(0 && "Trailing '%' in asm string.");
548 }
549
550 char EscapedChar = *Start;
551 if (EscapedChar == '%') {
552 // Escaped percentage sign.
553 Result += '%';
554 }
555 else if (EscapedChar == '=') {
556 // Generate an unique ID.
557 Result += llvm::utostr(AsmCounter);
558 } else if (isdigit(EscapedChar)) {
559 // %n - Assembler operand n
560 char *End;
561
562 unsigned long n = strtoul(Start, &End, 10);
563 if (Start == End) {
564 // FIXME: This should be caught during Sema.
565 assert(0 && "Missing operand!");
566 } else if (n >= NumOperands) {
567 // FIXME: This should be caught during Sema.
568 assert(0 && "Operand number out of range!");
569 }
570
571 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000572 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000573 } else if (isalpha(EscapedChar)) {
574 char *End;
575
576 unsigned long n = strtoul(Start + 1, &End, 10);
577 if (Start == End) {
578 // FIXME: This should be caught during Sema.
579 assert(0 && "Missing operand!");
580 } else if (n >= NumOperands) {
581 // FIXME: This should be caught during Sema.
582 assert(0 && "Operand number out of range!");
583 }
584
585 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000586 Start = End - 1;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000587 } else {
588 assert(0 && "Unhandled asm escaped character!");
589 }
590 }
591 Start++;
592 }
593
594 return Result;
595}
596
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000597static std::string SimplifyConstraint(const char* Constraint,
598 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000599 std::string Result;
600
601 while (*Constraint) {
602 switch (*Constraint) {
603 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000604 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000605 break;
606 // Ignore these
607 case '*':
608 case '?':
609 case '!':
610 break;
611 case 'g':
612 Result += "imr";
613 break;
614 }
615
616 Constraint++;
617 }
618
619 return Result;
620}
621
622void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
623 std::string AsmString =
624 ConvertAsmString(std::string(S.getAsmString()->getStrData(),
625 S.getAsmString()->getByteLength()).c_str(),
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000626 S.getNumOutputs() + S.getNumInputs(), S.isSimple());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000627
628 std::string Constraints;
629
630 llvm::Value *ResultAddr = 0;
631 const llvm::Type *ResultType = llvm::Type::VoidTy;
632
633 std::vector<const llvm::Type*> ArgTypes;
634 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000635
636 // Keep track of inout constraints.
637 std::string InOutConstraints;
638 std::vector<llvm::Value*> InOutArgs;
639 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000640
641 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
642 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
643 S.getOutputConstraint(i)->getByteLength());
644
645 TargetInfo::ConstraintInfo Info;
646 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
647 Info);
648 assert(result && "Failed to parse output constraint");
649
650 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000651 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000652
653 LValue Dest = EmitLValue(S.getOutputExpr(i));
654 const llvm::Type *DestValueType =
655 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
656
657 // If the first output operand is not a memory dest, we'll
658 // make it the return value.
659 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
660 DestValueType->isFirstClassType()) {
661 ResultAddr = Dest.getAddress();
662 ResultType = DestValueType;
663 Constraints += "=" + OutputConstraint;
664 } else {
665 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000666 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000667 if (i != 0)
668 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000669 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000670 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000671 }
672
673 if (Info & TargetInfo::CI_ReadWrite) {
674 // FIXME: This code should be shared with the code that handles inputs.
675 InOutConstraints += ',';
676
677 const Expr *InputExpr = S.getOutputExpr(i);
678 llvm::Value *Arg;
679 if ((Info & TargetInfo::CI_AllowsRegister) ||
680 !(Info & TargetInfo::CI_AllowsMemory)) {
681 if (ConvertType(InputExpr->getType())->isFirstClassType()) {
682 Arg = EmitScalarExpr(InputExpr);
683 } else {
684 assert(0 && "FIXME: Implement passing non first class types as inputs");
685 }
686 } else {
687 LValue Dest = EmitLValue(InputExpr);
688 Arg = Dest.getAddress();
689 InOutConstraints += '*';
690 }
691
692 InOutArgTypes.push_back(Arg->getType());
693 InOutArgs.push_back(Arg);
694 InOutConstraints += OutputConstraint;
695 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000696 }
697
698 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
699
700 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
701 const Expr *InputExpr = S.getInputExpr(i);
702
703 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
704 S.getInputConstraint(i)->getByteLength());
705
706 TargetInfo::ConstraintInfo Info;
707 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
708 NumConstraints,
709 Info);
710 assert(result && "Failed to parse input constraint");
711
712 if (i != 0 || S.getNumOutputs() > 0)
713 Constraints += ',';
714
715 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000716 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000717
718 llvm::Value *Arg;
719
720 if ((Info & TargetInfo::CI_AllowsRegister) ||
721 !(Info & TargetInfo::CI_AllowsMemory)) {
722 if (ConvertType(InputExpr->getType())->isFirstClassType()) {
723 Arg = EmitScalarExpr(InputExpr);
724 } else {
725 assert(0 && "FIXME: Implement passing non first class types as inputs");
726 }
727 } else {
728 LValue Dest = EmitLValue(InputExpr);
729 Arg = Dest.getAddress();
730 Constraints += '*';
731 }
732
733 ArgTypes.push_back(Arg->getType());
734 Args.push_back(Arg);
735 Constraints += InputConstraint;
736 }
737
Anders Carlssonf39a4212008-02-05 20:01:53 +0000738 // Append the "input" part of inout constraints last.
739 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
740 ArgTypes.push_back(InOutArgTypes[i]);
741 Args.push_back(InOutArgs[i]);
742 }
743 Constraints += InOutConstraints;
744
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000745 // Clobbers
746 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
747 std::string Clobber(S.getClobber(i)->getStrData(),
748 S.getClobber(i)->getByteLength());
749
750 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
751
Anders Carlssonea041752008-02-06 00:11:32 +0000752 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000753 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000754
755 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000756 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000757 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000758 }
759
760 // Add machine specific clobbers
761 if (const char *C = Target.getClobbers()) {
762 if (!Constraints.empty())
763 Constraints += ',';
764 Constraints += C;
765 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000766
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000767 const llvm::FunctionType *FTy =
768 llvm::FunctionType::get(ResultType, ArgTypes, false);
769
770 llvm::InlineAsm *IA =
771 llvm::InlineAsm::get(FTy, AsmString, Constraints,
772 S.isVolatile() || S.getNumOutputs() == 0);
773 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
774 if (ResultAddr)
775 Builder.CreateStore(Result, ResultAddr);
776}