blob: 551a4c040bf7ca8b12478893226261bf6384f191 [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"
Chris Lattner9bc47e22008-11-12 07:46:33 +000017#include "clang/AST/APValue.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/StmtVisitor.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000019#include "clang/Basic/TargetInfo.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?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000031
32 // If we happen to be at an unreachable point just create a dummy
33 // basic block to hold the code. We could change parts of irgen to
34 // simply not generate this code, but this situation is rare and
35 // probably not worth the effort.
36 // FIXME: Verify previous performance/effort claim.
37 EnsureInsertPoint();
Reid Spencer5f016e22007-07-11 17:01:13 +000038
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000039 // Generate stoppoints if we are emitting debug info.
40 // Beginning of a Compound Statement (e.g. an opening '{') does not produce
41 // executable code. So do not generate a stoppoint for that.
42 CGDebugInfo *DI = CGM.getDebugInfo();
43 if (DI && S->getStmtClass() != Stmt::CompoundStmtClass) {
Daniel Dunbar66031a52008-10-17 16:15:48 +000044 DI->setLocation(S->getLocStart());
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000045 DI->EmitStopPoint(CurFn, Builder);
46 }
47
Reid Spencer5f016e22007-07-11 17:01:13 +000048 switch (S->getStmtClass()) {
49 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000050 // Must be an expression in a stmt context. Emit the value (to get
51 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000052 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000053 if (!hasAggregateLLVMType(E->getType()))
54 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000055 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000056 EmitComplexExpr(E);
57 else
58 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000059 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000060 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000061 }
62 break;
63 case Stmt::NullStmtClass: break;
64 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
65 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
66 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000067 case Stmt::IndirectGotoStmtClass:
68 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000069
70 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
71 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
72 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
73 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
74
75 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
76 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Chris Lattnerda138702007-07-16 21:28:45 +000077
Daniel Dunbara4275d12008-10-02 18:02:06 +000078 case Stmt::BreakStmtClass:
79 // FIXME: Implement break in @try or @catch blocks.
80 if (!ObjCEHStack.empty()) {
81 CGM.ErrorUnsupported(S, "continue inside an Obj-C exception block");
82 return;
83 }
84 EmitBreakStmt();
85 break;
86
87 case Stmt::ContinueStmtClass:
88 // FIXME: Implement continue in @try or @catch blocks.
89 if (!ObjCEHStack.empty()) {
90 CGM.ErrorUnsupported(S, "continue inside an Obj-C exception block");
91 return;
92 }
93 EmitContinueStmt();
94 break;
95
Devang Patel51b09f22007-10-04 23:45:31 +000096 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
97 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
98 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000099 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000100
101 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000102 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
103 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000104 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +0000105 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
106 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000107 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000108 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000109 break;
110 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000111 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000112 break;
113 case Stmt::ObjCAtSynchronizedStmtClass:
114 ErrorUnsupported(S, "@synchronized statement");
115 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000116 case Stmt::ObjCForCollectionStmtClass:
117 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000118 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 }
120}
121
Chris Lattner33793202007-08-31 22:09:40 +0000122/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
123/// this captures the expression result of the last sub-statement and returns it
124/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000125RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
126 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 // FIXME: handle vla's etc.
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000128 CGDebugInfo *DI = CGM.getDebugInfo();
129 if (DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000130 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000131 DI->EmitRegionStart(CurFn, Builder);
132 }
133
Chris Lattner33793202007-08-31 22:09:40 +0000134 for (CompoundStmt::const_body_iterator I = S.body_begin(),
135 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000136 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000137
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000138 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000139 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000140 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000141 DI->EmitRegionEnd(CurFn, Builder);
142 }
143
Chris Lattner33793202007-08-31 22:09:40 +0000144 if (!GetLast)
145 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +0000146
Chris Lattner91d723d2008-07-26 20:23:23 +0000147 // We have to special case labels here. They are statements, but when put at
148 // the end of a statement expression, they yield the value of their
149 // subexpression. Handle this by walking through all labels we encounter,
150 // emitting them before we evaluate the subexpr.
151 const Stmt *LastStmt = S.body_back();
152 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
153 EmitLabel(*LS);
154 LastStmt = LS->getSubStmt();
155 }
156
Daniel Dunbara448fb22008-11-11 23:11:34 +0000157 EnsureInsertPoint();
158
Chris Lattner91d723d2008-07-26 20:23:23 +0000159 return EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000160}
161
162void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000163 // Fall out of the current block (if necessary).
164 EmitBranch(BB);
Reid Spencer5f016e22007-07-11 17:01:13 +0000165 CurFn->getBasicBlockList().push_back(BB);
166 Builder.SetInsertPoint(BB);
167}
168
Daniel Dunbard57a8712008-11-11 09:41:28 +0000169void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
170 // Emit a branch from the current block to the target one if this
171 // was a real block. If this was just a fall-through block after a
172 // terminator, don't emit it.
173 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
174
175 if (!CurBB || CurBB->getTerminator()) {
176 // If there is no insert point or the previous block is already
177 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000178 } else {
179 // Otherwise, create a fall-through branch.
180 Builder.CreateBr(Target);
181 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000182
183 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000184}
185
Chris Lattner91d723d2008-07-26 20:23:23 +0000186void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000188 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000189}
190
191
192void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
193 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000194 EmitStmt(S.getSubStmt());
195}
196
197void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000198 // FIXME: Implement goto out in @try or @catch blocks.
199 if (!ObjCEHStack.empty()) {
200 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
201 return;
202 }
203
Daniel Dunbard57a8712008-11-11 09:41:28 +0000204 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000205}
206
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000207void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000208 // FIXME: Implement indirect goto in @try or @catch blocks.
209 if (!ObjCEHStack.empty()) {
210 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
211 return;
212 }
213
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000214 // Emit initial switch which will be patched up later by
215 // EmitIndirectSwitches(). We need a default dest, so we use the
216 // current BB, but this is overwritten.
217 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
218 llvm::Type::Int32Ty,
219 "addr");
220 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
221 IndirectSwitches.push_back(I);
222
Daniel Dunbara448fb22008-11-11 23:11:34 +0000223 // Clear the insertion point to indicate we are in unreachable code.
224 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000225}
226
Chris Lattner9bc47e22008-11-12 07:46:33 +0000227
228/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
229/// a constant, or if it does but contains a label, return 0. If it constant
230/// folds to 'true' and does not contain a label, return 1, if it constant folds
231/// to 'false' and does not contain a label, return -1.
232static int ConstantFoldsToSimpleInteger(const Expr *Cond, ASTContext &Ctx) {
233 APValue V;
234 if (!Cond->tryEvaluate(V, Ctx))
235 return 0; // Not foldable.
236
237 if (CodeGenFunction::ContainsLabel(Cond))
238 return 0; // Contains a label.
239
240 return V.getInt().getBoolValue() ? 1 : -1;
241}
242
243
244/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
245/// statement) to the specified blocks. Based on the condition, this might try
246/// to simplify the codegen of the conditional based on the branch.
247///
248void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
249 llvm::BasicBlock *TrueBlock,
250 llvm::BasicBlock *FalseBlock) {
251 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
252 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
253
254 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
255 // Handle X && Y in a condition.
256 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
257 // If we have "1 && X", simplify the code. "0 && X" would have constant
258 // folded if the case was simple enough.
259 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), getContext()) == 1) {
260 // br(1 && X) -> br(X).
261 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
262 }
263
264 // If we have "X && 1", simplify the code to use an uncond branch.
265 // "X && 0" would have been constant folded to 0.
266 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), getContext()) == 1) {
267 // br(X && 1) -> br(X).
268 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
269 }
270
271 // Emit the LHS as a conditional. If the LHS conditional is false, we
272 // want to jump to the FalseBlock.
273 llvm::BasicBlock *LHSTrue = createBasicBlock("land_lhs_true");
274 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
275 EmitBlock(LHSTrue);
276
277 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
278 return;
279 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
280 // If we have "0 || X", simplify the code. "1 || X" would have constant
281 // folded if the case was simple enough.
282 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), getContext()) == -1) {
283 // br(0 || X) -> br(X).
284 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
285 }
286
287 // If we have "X || 0", simplify the code to use an uncond branch.
288 // "X || 1" would have been constant folded to 1.
289 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), getContext()) == -1) {
290 // br(X || 0) -> br(X).
291 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
292 }
293
294 // Emit the LHS as a conditional. If the LHS conditional is true, we
295 // want to jump to the TrueBlock.
296 llvm::BasicBlock *LHSFalse = createBasicBlock("lor_lhs_false");
297 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
298 EmitBlock(LHSFalse);
299
300 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
301 return;
302 }
303
304 }
305
306 // Emit the code with the fully general case.
307 llvm::Value *CondV = EvaluateExprAsBool(Cond);
308 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
309}
310
311
Chris Lattner62b72f62008-11-11 07:24:28 +0000312void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 // C99 6.8.4.1: The first substatement is executed if the expression compares
314 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000315
Chris Lattner9bc47e22008-11-12 07:46:33 +0000316 // If the condition constant folds and can be elided, try to avoid emitting
317 // the condition and the dead arm of the if/else.
318 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond(), getContext())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000319 // Figure out which block (then or else) is executed.
320 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000321 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000322 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000323
Chris Lattner62b72f62008-11-11 07:24:28 +0000324 // If the skipped block has no labels in it, just emit the executed block.
325 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000326 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000327 if (Executed)
328 EmitStmt(Executed);
329 return;
330 }
331 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000332
333 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
334 // the conditional branch.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000335 llvm::BasicBlock *ThenBlock = createBasicBlock("ifthen");
Chris Lattner9bc47e22008-11-12 07:46:33 +0000336 llvm::BasicBlock *ElseBlock = createBasicBlock("ifelse");
337 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000338
Chris Lattner9bc47e22008-11-12 07:46:33 +0000339 llvm::BasicBlock *ContBlock = ElseBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 if (S.getElse())
Chris Lattner9bc47e22008-11-12 07:46:33 +0000341 ContBlock = createBasicBlock("ifend");
Reid Spencer5f016e22007-07-11 17:01:13 +0000342
343 // Emit the 'then' code.
344 EmitBlock(ThenBlock);
345 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000346 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000347
348 // Emit the 'else' code if present.
349 if (const Stmt *Else = S.getElse()) {
350 EmitBlock(ElseBlock);
351 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000352 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 }
354
355 // Emit the continuation block for code after the if.
356 EmitBlock(ContBlock);
357}
358
359void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000360 // Emit the header for the loop, insert it, which will create an uncond br to
361 // it.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000362 llvm::BasicBlock *LoopHeader = createBasicBlock("whilecond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 EmitBlock(LoopHeader);
364
365 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
366 // of the controlling expression takes place before each execution of the loop
367 // body.
368 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000369
370 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000372 bool EmitBoolCondBranch = true;
373 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
374 if (C->isOne())
375 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000376
377 // Create an exit block for when the condition fails, create a block for the
378 // body of the loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000379 llvm::BasicBlock *ExitBlock = createBasicBlock("whileexit");
380 llvm::BasicBlock *LoopBody = createBasicBlock("whilebody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000381
382 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000383 if (EmitBoolCondBranch)
384 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000385
386 // Store the blocks to use for break and continue.
387 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000388
389 // Emit the loop body.
390 EmitBlock(LoopBody);
391 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000392
393 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000394
395 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000396 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000397
398 // Emit the exit block.
399 EmitBlock(ExitBlock);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000400
401 // If LoopHeader is a simple forwarding block then eliminate it.
402 if (!EmitBoolCondBranch
403 && &LoopHeader->front() == LoopHeader->getTerminator()) {
404 LoopHeader->replaceAllUsesWith(LoopBody);
405 LoopHeader->getTerminator()->eraseFromParent();
406 LoopHeader->eraseFromParent();
407 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000408}
409
410void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 // Emit the body for the loop, insert it, which will create an uncond br to
412 // it.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000413 llvm::BasicBlock *LoopBody = createBasicBlock("dobody");
414 llvm::BasicBlock *AfterDo = createBasicBlock("afterdo");
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000416
Daniel Dunbar55e87422008-11-11 02:29:29 +0000417 llvm::BasicBlock *DoCond = createBasicBlock("docond");
Chris Lattnerda138702007-07-16 21:28:45 +0000418
419 // Store the blocks to use for break and continue.
420 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000421
422 // Emit the body of the loop into the block.
423 EmitStmt(S.getBody());
424
Chris Lattnerda138702007-07-16 21:28:45 +0000425 BreakContinueStack.pop_back();
426
427 EmitBlock(DoCond);
428
Reid Spencer5f016e22007-07-11 17:01:13 +0000429 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
430 // after each execution of the loop body."
431
432 // Evaluate the conditional in the while header.
433 // C99 6.8.5p2/p4: The first substatement is executed if the expression
434 // compares unequal to 0. The condition must be a scalar type.
435 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000436
437 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
438 // to correctly handle break/continue though.
439 bool EmitBoolCondBranch = true;
440 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
441 if (C->isZero())
442 EmitBoolCondBranch = false;
443
Reid Spencer5f016e22007-07-11 17:01:13 +0000444 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000445 if (EmitBoolCondBranch)
446 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000447
448 // Emit the exit block.
449 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000450
451 // If DoCond is a simple forwarding block then eliminate it.
452 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
453 DoCond->replaceAllUsesWith(AfterDo);
454 DoCond->getTerminator()->eraseFromParent();
455 DoCond->eraseFromParent();
456 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000457}
458
459void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000460 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
461 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000462 // TODO: We could keep track of whether the loop body contains any
463 // break/continue statements and not create unnecessary blocks (like
464 // "afterfor" for a condless loop) if it doesn't.
465
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 // Evaluate the first part before the loop.
467 if (S.getInit())
468 EmitStmt(S.getInit());
469
470 // Start the loop with a block that tests the condition.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000471 llvm::BasicBlock *CondBlock = createBasicBlock("forcond");
472 llvm::BasicBlock *AfterFor = createBasicBlock("afterfor");
Chris Lattnerda138702007-07-16 21:28:45 +0000473
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 EmitBlock(CondBlock);
475
476 // Evaluate the condition if present. If not, treat it as a non-zero-constant
477 // according to 6.8.5.3p2, aka, true.
478 if (S.getCond()) {
479 // C99 6.8.5p2/p4: The first substatement is executed if the expression
480 // compares unequal to 0. The condition must be a scalar type.
481 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
482
483 // As long as the condition is true, iterate the loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000484 llvm::BasicBlock *ForBody = createBasicBlock("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000485 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
486 EmitBlock(ForBody);
487 } else {
488 // Treat it as a non-zero constant. Don't even create a new block for the
489 // body, just fall into it.
490 }
491
Chris Lattnerda138702007-07-16 21:28:45 +0000492 // If the for loop doesn't have an increment we can just use the
493 // condition as the continue block.
494 llvm::BasicBlock *ContinueBlock;
495 if (S.getInc())
Daniel Dunbar55e87422008-11-11 02:29:29 +0000496 ContinueBlock = createBasicBlock("forinc");
Chris Lattnerda138702007-07-16 21:28:45 +0000497 else
498 ContinueBlock = CondBlock;
499
500 // Store the blocks to use for break and continue.
501 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
502
Reid Spencer5f016e22007-07-11 17:01:13 +0000503 // If the condition is true, execute the body of the for stmt.
504 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000505
506 BreakContinueStack.pop_back();
507
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000509 if (S.getInc()) {
510 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000511 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000512 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000513
514 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000515 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000516
Chris Lattnerda138702007-07-16 21:28:45 +0000517 // Emit the fall-through block.
518 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000519}
520
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000521void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
522 if (RV.isScalar()) {
523 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
524 } else if (RV.isAggregate()) {
525 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
526 } else {
527 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
528 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000529 EmitBranch(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000530}
531
Reid Spencer5f016e22007-07-11 17:01:13 +0000532/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
533/// if the function returns void, or may be missing one if the function returns
534/// non-void. Fun stuff :).
535void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000536 // Emit the result value, even if unused, to evalute the side effects.
537 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000538
539 // FIXME: Clean this up by using an LValue for ReturnTemp,
540 // EmitStoreThroughLValue, and EmitAnyExpr.
541 if (!ReturnValue) {
542 // Make sure not to return anything, but evaluate the expression
543 // for side effects.
544 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000545 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000546 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000547 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000548 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000549 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000550 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000551 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000552 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000553 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000554 }
Eli Friedman144ac612008-05-22 01:22:33 +0000555
Daniel Dunbar898d5082008-09-30 01:06:03 +0000556 if (!ObjCEHStack.empty()) {
557 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
558 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000559 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000560 EmitJumpThroughFinally(*i, ReturnPad);
561 EmitBlock(ReturnPad);
562 }
563 }
564
Daniel Dunbard57a8712008-11-11 09:41:28 +0000565 EmitBranch(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000566}
567
568void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000569 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
570 I != E; ++I)
571 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000572}
Chris Lattnerda138702007-07-16 21:28:45 +0000573
574void CodeGenFunction::EmitBreakStmt() {
575 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
576
577 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000578 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000579}
580
581void CodeGenFunction::EmitContinueStmt() {
582 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
583
584 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000585 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000586}
Devang Patel51b09f22007-10-04 23:45:31 +0000587
Devang Patelc049e4f2007-10-08 20:57:48 +0000588/// EmitCaseStmtRange - If case statement range is not too big then
589/// add multiple cases to switch instruction, one for each value within
590/// the range. If range is too big then emit "if" condition check.
591void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000592 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000593
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000594 llvm::APSInt LHS = S.getLHS()->getIntegerConstantExprValue(getContext());
595 llvm::APSInt RHS = S.getRHS()->getIntegerConstantExprValue(getContext());
596
Daniel Dunbar16f23572008-07-25 01:11:38 +0000597 // Emit the code for this case. We do this first to make sure it is
598 // properly chained from our predecessor before generating the
599 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000600 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000601 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
602 EmitStmt(S.getSubStmt());
603
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000604 // If range is empty, do nothing.
605 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
606 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000607
608 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000609 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000610 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
611 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000612 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000613 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
614 LHS++;
615 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000616 return;
617 }
618
Daniel Dunbar16f23572008-07-25 01:11:38 +0000619 // The range is too big. Emit "if" condition into a new block,
620 // making sure to save and restore the current insertion point.
621 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000622
Daniel Dunbar16f23572008-07-25 01:11:38 +0000623 // Push this test onto the chain of range checks (which terminates
624 // in the default basic block). The switch's default will be changed
625 // to the top of this chain after switch emission is complete.
626 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000627 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000628
Daniel Dunbar16f23572008-07-25 01:11:38 +0000629 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
630 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000631
632 // Emit range check.
633 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000634 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
635 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000636 llvm::Value *Cond =
637 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
638 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
639
Daniel Dunbar16f23572008-07-25 01:11:38 +0000640 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000641 if (RestoreBB)
642 Builder.SetInsertPoint(RestoreBB);
643 else
644 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000645}
646
647void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
648 if (S.getRHS()) {
649 EmitCaseStmtRange(S);
650 return;
651 }
652
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000653 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000654 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000655 llvm::APSInt CaseVal = S.getLHS()->getIntegerConstantExprValue(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000656 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000657 EmitStmt(S.getSubStmt());
658}
659
660void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000661 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000662 assert(DefaultBlock->empty() &&
663 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000664 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000665 EmitStmt(S.getSubStmt());
666}
667
668void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
669 llvm::Value *CondV = EmitScalarExpr(S.getCond());
670
671 // Handle nested switch statements.
672 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000673 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000674
Daniel Dunbar16f23572008-07-25 01:11:38 +0000675 // Create basic block to hold stuff that comes after switch
676 // statement. We also need to create a default block now so that
677 // explicit case ranges tests can have a place to jump to on
678 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000679 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
680 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000681 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
682 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000683
Eli Friedmand28a80d2008-05-12 16:08:04 +0000684 // Create basic block for body of switch
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000685 EmitBlock(createBasicBlock("sw.body"));
Eli Friedmand28a80d2008-05-12 16:08:04 +0000686
Devang Patele9b8c0a2007-10-30 20:59:40 +0000687 // All break statements jump to NextBlock. If BreakContinueStack is non empty
688 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000689 llvm::BasicBlock *ContinueBlock = NULL;
690 if (!BreakContinueStack.empty())
691 ContinueBlock = BreakContinueStack.back().ContinueBlock;
692 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
693
694 // Emit switch body.
695 EmitStmt(S.getBody());
696 BreakContinueStack.pop_back();
697
Daniel Dunbar16f23572008-07-25 01:11:38 +0000698 // Update the default block in case explicit case range tests have
699 // been chained on top.
700 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000701
Daniel Dunbar16f23572008-07-25 01:11:38 +0000702 // If a default was never emitted then reroute any jumps to it and
703 // discard.
704 if (!DefaultBlock->getParent()) {
705 DefaultBlock->replaceAllUsesWith(NextBlock);
706 delete DefaultBlock;
707 }
Devang Patel51b09f22007-10-04 23:45:31 +0000708
Daniel Dunbar16f23572008-07-25 01:11:38 +0000709 // Emit continuation.
710 EmitBlock(NextBlock);
711
Devang Patel51b09f22007-10-04 23:45:31 +0000712 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000713 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000714}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000715
Anders Carlssonce179ab2008-11-09 18:54:14 +0000716static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
717{
718 // FIXME: No need to create new std::string here, we could just make sure
719 // that we don't read past the end of the string data.
720 std::string str(S.getAsmString()->getStrData(),
721 S.getAsmString()->getByteLength());
722 const char *Start = str.c_str();
723
724 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
725 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000726 Failed = false;
727
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000728 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000729 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000730 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000731 if (IsSimple) {
732 while (*Start) {
733 switch (*Start) {
734 default:
735 Result += *Start;
736 break;
737 case '$':
738 Result += "$$";
739 break;
740 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000741 Start++;
742 }
743
744 return Result;
745 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000746
747 while (*Start) {
748 switch (*Start) {
749 default:
750 Result += *Start;
751 break;
752 case '$':
753 Result += "$$";
754 break;
755 case '%':
756 // Escaped character
757 Start++;
758 if (!*Start) {
759 // FIXME: This should be caught during Sema.
760 assert(0 && "Trailing '%' in asm string.");
761 }
762
763 char EscapedChar = *Start;
764 if (EscapedChar == '%') {
765 // Escaped percentage sign.
766 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000767 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000768 // Generate an unique ID.
769 Result += llvm::utostr(AsmCounter);
770 } else if (isdigit(EscapedChar)) {
771 // %n - Assembler operand n
772 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000773 unsigned long n = strtoul(Start, &End, 10);
774 if (Start == End) {
775 // FIXME: This should be caught during Sema.
776 assert(0 && "Missing operand!");
777 } else if (n >= NumOperands) {
778 // FIXME: This should be caught during Sema.
779 assert(0 && "Operand number out of range!");
780 }
781
782 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000783 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000784 } else if (isalpha(EscapedChar)) {
785 char *End;
786
787 unsigned long n = strtoul(Start + 1, &End, 10);
788 if (Start == End) {
789 // FIXME: This should be caught during Sema.
790 assert(0 && "Missing operand!");
791 } else if (n >= NumOperands) {
792 // FIXME: This should be caught during Sema.
793 assert(0 && "Operand number out of range!");
794 }
795
796 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000797 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000798 } else if (EscapedChar == '[') {
799 std::string SymbolicName;
800
801 Start++;
802
803 while (*Start && *Start != ']') {
804 SymbolicName += *Start;
805
806 Start++;
807 }
808
809 if (!Start) {
810 // FIXME: Should be caught by sema.
811 assert(0 && "Could not parse symbolic name");
812 }
813
814 assert(*Start == ']' && "Error parsing symbolic name");
815
816 int Index = -1;
817
818 // Check if this is an output operand.
819 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
820 if (S.getOutputName(i) == SymbolicName) {
821 Index = i;
822 break;
823 }
824 }
825
826 if (Index == -1) {
827 for (unsigned i = 0; i < S.getNumInputs(); i++) {
828 if (S.getInputName(i) == SymbolicName) {
829 Index = S.getNumOutputs() + i;
830 }
831 }
832 }
833
834 assert(Index != -1 && "Did not find right operand!");
835
836 Result += '$' + llvm::utostr(Index);
837
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000838 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000839 Failed = true;
840 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000841 }
842 }
843 Start++;
844 }
845
846 return Result;
847}
848
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000849static std::string SimplifyConstraint(const char* Constraint,
850 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000851 std::string Result;
852
853 while (*Constraint) {
854 switch (*Constraint) {
855 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000856 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000857 break;
858 // Ignore these
859 case '*':
860 case '?':
861 case '!':
862 break;
863 case 'g':
864 Result += "imr";
865 break;
866 }
867
868 Constraint++;
869 }
870
871 return Result;
872}
873
874void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000875 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000876 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000877 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000878
879 if (Failed) {
880 ErrorUnsupported(&S, "asm string");
881 return;
882 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000883
884 std::string Constraints;
885
886 llvm::Value *ResultAddr = 0;
887 const llvm::Type *ResultType = llvm::Type::VoidTy;
888
889 std::vector<const llvm::Type*> ArgTypes;
890 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000891
892 // Keep track of inout constraints.
893 std::string InOutConstraints;
894 std::vector<llvm::Value*> InOutArgs;
895 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000896
897 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
898 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
899 S.getOutputConstraint(i)->getByteLength());
900
901 TargetInfo::ConstraintInfo Info;
902 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
903 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000904 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000905
906 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000907 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000908
909 LValue Dest = EmitLValue(S.getOutputExpr(i));
910 const llvm::Type *DestValueType =
911 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
912
913 // If the first output operand is not a memory dest, we'll
914 // make it the return value.
915 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000916 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000917 ResultAddr = Dest.getAddress();
918 ResultType = DestValueType;
919 Constraints += "=" + OutputConstraint;
920 } else {
921 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000922 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000923 if (i != 0)
924 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000925 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000926 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000927 }
928
929 if (Info & TargetInfo::CI_ReadWrite) {
930 // FIXME: This code should be shared with the code that handles inputs.
931 InOutConstraints += ',';
932
933 const Expr *InputExpr = S.getOutputExpr(i);
934 llvm::Value *Arg;
935 if ((Info & TargetInfo::CI_AllowsRegister) ||
936 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000937 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000938 Arg = EmitScalarExpr(InputExpr);
939 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000940 ErrorUnsupported(&S,
941 "asm statement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000942 }
943 } else {
944 LValue Dest = EmitLValue(InputExpr);
945 Arg = Dest.getAddress();
946 InOutConstraints += '*';
947 }
948
949 InOutArgTypes.push_back(Arg->getType());
950 InOutArgs.push_back(Arg);
951 InOutConstraints += OutputConstraint;
952 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000953 }
954
955 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
956
957 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
958 const Expr *InputExpr = S.getInputExpr(i);
959
960 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
961 S.getInputConstraint(i)->getByteLength());
962
963 TargetInfo::ConstraintInfo Info;
964 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Chris Lattner3304e552008-10-12 00:31:50 +0000965 NumConstraints, Info);
966 assert(result && "Failed to parse input constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000967
968 if (i != 0 || S.getNumOutputs() > 0)
969 Constraints += ',';
970
971 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000972 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000973
974 llvm::Value *Arg;
975
976 if ((Info & TargetInfo::CI_AllowsRegister) ||
977 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000978 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000979 Arg = EmitScalarExpr(InputExpr);
980 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000981 ErrorUnsupported(&S,
982 "asm statement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000983 }
984 } else {
985 LValue Dest = EmitLValue(InputExpr);
986 Arg = Dest.getAddress();
987 Constraints += '*';
988 }
989
990 ArgTypes.push_back(Arg->getType());
991 Args.push_back(Arg);
992 Constraints += InputConstraint;
993 }
994
Anders Carlssonf39a4212008-02-05 20:01:53 +0000995 // Append the "input" part of inout constraints last.
996 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
997 ArgTypes.push_back(InOutArgTypes[i]);
998 Args.push_back(InOutArgs[i]);
999 }
1000 Constraints += InOutConstraints;
1001
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001002 // Clobbers
1003 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1004 std::string Clobber(S.getClobber(i)->getStrData(),
1005 S.getClobber(i)->getByteLength());
1006
1007 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
1008
Anders Carlssonea041752008-02-06 00:11:32 +00001009 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001010 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +00001011
1012 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001013 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001014 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001015 }
1016
1017 // Add machine specific clobbers
1018 if (const char *C = Target.getClobbers()) {
1019 if (!Constraints.empty())
1020 Constraints += ',';
1021 Constraints += C;
1022 }
Anders Carlssonf39a4212008-02-05 20:01:53 +00001023
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001024 const llvm::FunctionType *FTy =
1025 llvm::FunctionType::get(ResultType, ArgTypes, false);
1026
1027 llvm::InlineAsm *IA =
1028 llvm::InlineAsm::get(FTy, AsmString, Constraints,
1029 S.isVolatile() || S.getNumOutputs() == 0);
1030 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +00001031 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001032 Builder.CreateStore(Result, ResultAddr);
1033}