blob: a66b6fec04186ea24129cb899c5d17bc6bad08bd [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"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000017#include "clang/AST/StmtVisitor.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000018#include "clang/Basic/TargetInfo.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000019#include "llvm/InlineAsm.h"
20#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021using namespace clang;
22using namespace CodeGen;
23
24//===----------------------------------------------------------------------===//
25// Statement Emission
26//===----------------------------------------------------------------------===//
27
Daniel Dunbar09124252008-11-12 08:21:33 +000028void CodeGenFunction::EmitStopPoint(const Stmt *S) {
29 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
30 DI->setLocation(S->getLocStart());
31 DI->EmitStopPoint(CurFn, Builder);
32 }
33}
34
Reid Spencer5f016e22007-07-11 17:01:13 +000035void CodeGenFunction::EmitStmt(const Stmt *S) {
36 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000037
Daniel Dunbar09124252008-11-12 08:21:33 +000038 // Check if we can handle this without bothering to generate an
39 // insert point or debug info.
40 if (EmitSimpleStmt(S))
41 return;
42
Daniel Dunbara448fb22008-11-11 23:11:34 +000043 // If we happen to be at an unreachable point just create a dummy
44 // basic block to hold the code. We could change parts of irgen to
45 // simply not generate this code, but this situation is rare and
46 // probably not worth the effort.
47 // FIXME: Verify previous performance/effort claim.
48 EnsureInsertPoint();
Reid Spencer5f016e22007-07-11 17:01:13 +000049
Daniel Dunbar09124252008-11-12 08:21:33 +000050 // Generate a stoppoint if we are emitting debug info.
51 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000052
Reid Spencer5f016e22007-07-11 17:01:13 +000053 switch (S->getStmtClass()) {
54 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000055 // Must be an expression in a stmt context. Emit the value (to get
56 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000057 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000058 if (!hasAggregateLLVMType(E->getType()))
59 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000060 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000061 EmitComplexExpr(E);
62 else
63 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000064 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000065 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000066 }
67 break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000068 case Stmt::IndirectGotoStmtClass:
69 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000070
71 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
72 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
73 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
74 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
75
76 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
77 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +000078
Devang Patel51b09f22007-10-04 23:45:31 +000079 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000080 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000081
82 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000083 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
84 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000085 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +000086 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
87 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000088 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000089 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +000090 break;
91 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000092 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000093 break;
94 case Stmt::ObjCAtSynchronizedStmtClass:
95 ErrorUnsupported(S, "@synchronized statement");
96 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +000097 case Stmt::ObjCForCollectionStmtClass:
98 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000099 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000100 }
101}
102
Daniel Dunbar09124252008-11-12 08:21:33 +0000103bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
104 switch (S->getStmtClass()) {
105 default: return false;
106 case Stmt::NullStmtClass: break;
107 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
108 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
109 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
110 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
111 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
112 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
113 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
114 }
115
116 return true;
117}
118
Chris Lattner33793202007-08-31 22:09:40 +0000119/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
120/// this captures the expression result of the last sub-statement and returns it
121/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000122RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
123 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000124 // FIXME: handle vla's etc.
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000125 CGDebugInfo *DI = CGM.getDebugInfo();
126 if (DI) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000127 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000128 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000129 DI->EmitRegionStart(CurFn, Builder);
130 }
131
Chris Lattner33793202007-08-31 22:09:40 +0000132 for (CompoundStmt::const_body_iterator I = S.body_begin(),
133 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000134 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000135
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000136 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000137 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000138 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000139 DI->EmitRegionEnd(CurFn, Builder);
140 }
141
Chris Lattner33793202007-08-31 22:09:40 +0000142 if (!GetLast)
143 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +0000144
Chris Lattner91d723d2008-07-26 20:23:23 +0000145 // We have to special case labels here. They are statements, but when put at
146 // the end of a statement expression, they yield the value of their
147 // subexpression. Handle this by walking through all labels we encounter,
148 // emitting them before we evaluate the subexpr.
149 const Stmt *LastStmt = S.body_back();
150 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
151 EmitLabel(*LS);
152 LastStmt = LS->getSubStmt();
153 }
154
Daniel Dunbara448fb22008-11-11 23:11:34 +0000155 EnsureInsertPoint();
156
Chris Lattner91d723d2008-07-26 20:23:23 +0000157 return EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000158}
159
160void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000161 // Fall out of the current block (if necessary).
162 EmitBranch(BB);
Reid Spencer5f016e22007-07-11 17:01:13 +0000163 CurFn->getBasicBlockList().push_back(BB);
164 Builder.SetInsertPoint(BB);
165}
166
Daniel Dunbard57a8712008-11-11 09:41:28 +0000167void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
168 // Emit a branch from the current block to the target one if this
169 // was a real block. If this was just a fall-through block after a
170 // terminator, don't emit it.
171 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
172
173 if (!CurBB || CurBB->getTerminator()) {
174 // If there is no insert point or the previous block is already
175 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000176 } else {
177 // Otherwise, create a fall-through branch.
178 Builder.CreateBr(Target);
179 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000180
181 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000182}
183
Chris Lattner91d723d2008-07-26 20:23:23 +0000184void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000185 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000187}
188
189
190void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
191 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 EmitStmt(S.getSubStmt());
193}
194
195void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000196 // FIXME: Implement goto out in @try or @catch blocks.
197 if (!ObjCEHStack.empty()) {
198 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
199 return;
200 }
201
Daniel Dunbar09124252008-11-12 08:21:33 +0000202 // If this code is reachable then emit a stop point (if generating
203 // debug info). We have to do this ourselves because we are on the
204 // "simple" statement path.
205 if (HaveInsertPoint())
206 EmitStopPoint(&S);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000207 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000208}
209
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000210void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000211 // FIXME: Implement indirect goto in @try or @catch blocks.
212 if (!ObjCEHStack.empty()) {
213 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
214 return;
215 }
216
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000217 // Emit initial switch which will be patched up later by
218 // EmitIndirectSwitches(). We need a default dest, so we use the
219 // current BB, but this is overwritten.
220 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
221 llvm::Type::Int32Ty,
222 "addr");
223 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
224 IndirectSwitches.push_back(I);
225
Daniel Dunbara448fb22008-11-11 23:11:34 +0000226 // Clear the insertion point to indicate we are in unreachable code.
227 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000228}
229
Chris Lattner62b72f62008-11-11 07:24:28 +0000230void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000231 // C99 6.8.4.1: The first substatement is executed if the expression compares
232 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000233
Chris Lattner9bc47e22008-11-12 07:46:33 +0000234 // If the condition constant folds and can be elided, try to avoid emitting
235 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000236 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000237 // Figure out which block (then or else) is executed.
238 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000239 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000240 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000241
Chris Lattner62b72f62008-11-11 07:24:28 +0000242 // If the skipped block has no labels in it, just emit the executed block.
243 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000244 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000245 if (Executed)
246 EmitStmt(Executed);
247 return;
248 }
249 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000250
251 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
252 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000253 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
254 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
255 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000257 ElseBlock = createBasicBlock("if.else");
258 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000259
260 // Emit the 'then' code.
261 EmitBlock(ThenBlock);
262 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000263 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000264
265 // Emit the 'else' code if present.
266 if (const Stmt *Else = S.getElse()) {
267 EmitBlock(ElseBlock);
268 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000269 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000270 }
271
272 // Emit the continuation block for code after the if.
273 EmitBlock(ContBlock);
274}
275
276void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 // Emit the header for the loop, insert it, which will create an uncond br to
278 // it.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000279 llvm::BasicBlock *LoopHeader = createBasicBlock("whilecond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000280 EmitBlock(LoopHeader);
281
282 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
283 // of the controlling expression takes place before each execution of the loop
284 // body.
285 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000286
287 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000288 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000289 bool EmitBoolCondBranch = true;
290 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
291 if (C->isOne())
292 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000293
294 // Create an exit block for when the condition fails, create a block for the
295 // body of the loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000296 llvm::BasicBlock *ExitBlock = createBasicBlock("whileexit");
297 llvm::BasicBlock *LoopBody = createBasicBlock("whilebody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000298
299 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000300 if (EmitBoolCondBranch)
301 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000302
Chris Lattnerda138702007-07-16 21:28:45 +0000303 // Store the blocks to use for break and continue.
304 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000305
306 // Emit the loop body.
307 EmitBlock(LoopBody);
308 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000309
310 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000311
312 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000313 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000314
315 // Emit the exit block.
316 EmitBlock(ExitBlock);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000317
318 // If LoopHeader is a simple forwarding block then eliminate it.
319 if (!EmitBoolCondBranch
320 && &LoopHeader->front() == LoopHeader->getTerminator()) {
321 LoopHeader->replaceAllUsesWith(LoopBody);
322 LoopHeader->getTerminator()->eraseFromParent();
323 LoopHeader->eraseFromParent();
324 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000325}
326
327void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000328 // Emit the body for the loop, insert it, which will create an uncond br to
329 // it.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000330 llvm::BasicBlock *LoopBody = createBasicBlock("dobody");
331 llvm::BasicBlock *AfterDo = createBasicBlock("afterdo");
Reid Spencer5f016e22007-07-11 17:01:13 +0000332 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000333
Daniel Dunbar55e87422008-11-11 02:29:29 +0000334 llvm::BasicBlock *DoCond = createBasicBlock("docond");
Chris Lattnerda138702007-07-16 21:28:45 +0000335
336 // Store the blocks to use for break and continue.
337 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000338
339 // Emit the body of the loop into the block.
340 EmitStmt(S.getBody());
341
Chris Lattnerda138702007-07-16 21:28:45 +0000342 BreakContinueStack.pop_back();
343
344 EmitBlock(DoCond);
345
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
347 // after each execution of the loop body."
348
349 // Evaluate the conditional in the while header.
350 // C99 6.8.5p2/p4: The first substatement is executed if the expression
351 // compares unequal to 0. The condition must be a scalar type.
352 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000353
354 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
355 // to correctly handle break/continue though.
356 bool EmitBoolCondBranch = true;
357 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
358 if (C->isZero())
359 EmitBoolCondBranch = false;
360
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000362 if (EmitBoolCondBranch)
363 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000364
365 // Emit the exit block.
366 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000367
368 // If DoCond is a simple forwarding block then eliminate it.
369 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
370 DoCond->replaceAllUsesWith(AfterDo);
371 DoCond->getTerminator()->eraseFromParent();
372 DoCond->eraseFromParent();
373 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000374}
375
376void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000377 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
378 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000379 // TODO: We could keep track of whether the loop body contains any
380 // break/continue statements and not create unnecessary blocks (like
381 // "afterfor" for a condless loop) if it doesn't.
382
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 // Evaluate the first part before the loop.
384 if (S.getInit())
385 EmitStmt(S.getInit());
386
387 // Start the loop with a block that tests the condition.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000388 llvm::BasicBlock *CondBlock = createBasicBlock("forcond");
389 llvm::BasicBlock *AfterFor = createBasicBlock("afterfor");
Chris Lattnerda138702007-07-16 21:28:45 +0000390
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 EmitBlock(CondBlock);
392
393 // Evaluate the condition if present. If not, treat it as a non-zero-constant
394 // according to 6.8.5.3p2, aka, true.
395 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 // As long as the condition is true, iterate the loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000397 llvm::BasicBlock *ForBody = createBasicBlock("forbody");
Chris Lattner31a09842008-11-12 08:04:58 +0000398
399 // C99 6.8.5p2/p4: The first substatement is executed if the expression
400 // compares unequal to 0. The condition must be a scalar type.
401 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
402
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 EmitBlock(ForBody);
404 } else {
405 // Treat it as a non-zero constant. Don't even create a new block for the
406 // body, just fall into it.
407 }
408
Chris Lattnerda138702007-07-16 21:28:45 +0000409 // If the for loop doesn't have an increment we can just use the
410 // condition as the continue block.
411 llvm::BasicBlock *ContinueBlock;
412 if (S.getInc())
Daniel Dunbar55e87422008-11-11 02:29:29 +0000413 ContinueBlock = createBasicBlock("forinc");
Chris Lattnerda138702007-07-16 21:28:45 +0000414 else
415 ContinueBlock = CondBlock;
416
417 // Store the blocks to use for break and continue.
418 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
419
Reid Spencer5f016e22007-07-11 17:01:13 +0000420 // If the condition is true, execute the body of the for stmt.
421 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000422
423 BreakContinueStack.pop_back();
424
Reid Spencer5f016e22007-07-11 17:01:13 +0000425 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000426 if (S.getInc()) {
427 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000428 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000429 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000430
431 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000432 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000433
Chris Lattnerda138702007-07-16 21:28:45 +0000434 // Emit the fall-through block.
435 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000436}
437
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000438void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
439 if (RV.isScalar()) {
440 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
441 } else if (RV.isAggregate()) {
442 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
443 } else {
444 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
445 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000446 EmitBranch(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000447}
448
Reid Spencer5f016e22007-07-11 17:01:13 +0000449/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
450/// if the function returns void, or may be missing one if the function returns
451/// non-void. Fun stuff :).
452void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000453 // Emit the result value, even if unused, to evalute the side effects.
454 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000455
456 // FIXME: Clean this up by using an LValue for ReturnTemp,
457 // EmitStoreThroughLValue, and EmitAnyExpr.
458 if (!ReturnValue) {
459 // Make sure not to return anything, but evaluate the expression
460 // for side effects.
461 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000462 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000463 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000464 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000465 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000466 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000467 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000468 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000469 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000470 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 }
Eli Friedman144ac612008-05-22 01:22:33 +0000472
Daniel Dunbar898d5082008-09-30 01:06:03 +0000473 if (!ObjCEHStack.empty()) {
474 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
475 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000476 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000477 EmitJumpThroughFinally(*i, ReturnPad);
478 EmitBlock(ReturnPad);
479 }
480 }
481
Daniel Dunbard57a8712008-11-11 09:41:28 +0000482 EmitBranch(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000483}
484
485void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000486 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
487 I != E; ++I)
488 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000489}
Chris Lattnerda138702007-07-16 21:28:45 +0000490
Daniel Dunbar09124252008-11-12 08:21:33 +0000491void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000492 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
493
Daniel Dunbar09124252008-11-12 08:21:33 +0000494 // FIXME: Implement break in @try or @catch blocks.
495 if (!ObjCEHStack.empty()) {
496 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
497 return;
498 }
499
500 // If this code is reachable then emit a stop point (if generating
501 // debug info). We have to do this ourselves because we are on the
502 // "simple" statement path.
503 if (HaveInsertPoint())
504 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000505 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000506 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000507}
508
Daniel Dunbar09124252008-11-12 08:21:33 +0000509void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000510 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
511
Daniel Dunbar09124252008-11-12 08:21:33 +0000512 // FIXME: Implement continue in @try or @catch blocks.
513 if (!ObjCEHStack.empty()) {
514 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
515 return;
516 }
517
518 // If this code is reachable then emit a stop point (if generating
519 // debug info). We have to do this ourselves because we are on the
520 // "simple" statement path.
521 if (HaveInsertPoint())
522 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000523 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000524 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000525}
Devang Patel51b09f22007-10-04 23:45:31 +0000526
Devang Patelc049e4f2007-10-08 20:57:48 +0000527/// EmitCaseStmtRange - If case statement range is not too big then
528/// add multiple cases to switch instruction, one for each value within
529/// the range. If range is too big then emit "if" condition check.
530void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000531 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000532
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000533 llvm::APSInt LHS = S.getLHS()->getIntegerConstantExprValue(getContext());
534 llvm::APSInt RHS = S.getRHS()->getIntegerConstantExprValue(getContext());
535
Daniel Dunbar16f23572008-07-25 01:11:38 +0000536 // Emit the code for this case. We do this first to make sure it is
537 // properly chained from our predecessor before generating the
538 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000539 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000540 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
541 EmitStmt(S.getSubStmt());
542
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000543 // If range is empty, do nothing.
544 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
545 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000546
547 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000548 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000549 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
550 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000551 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000552 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
553 LHS++;
554 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000555 return;
556 }
557
Daniel Dunbar16f23572008-07-25 01:11:38 +0000558 // The range is too big. Emit "if" condition into a new block,
559 // making sure to save and restore the current insertion point.
560 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000561
Daniel Dunbar16f23572008-07-25 01:11:38 +0000562 // Push this test onto the chain of range checks (which terminates
563 // in the default basic block). The switch's default will be changed
564 // to the top of this chain after switch emission is complete.
565 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000566 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000567
Daniel Dunbar16f23572008-07-25 01:11:38 +0000568 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
569 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000570
571 // Emit range check.
572 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000573 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
574 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000575 llvm::Value *Cond =
576 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
577 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
578
Daniel Dunbar16f23572008-07-25 01:11:38 +0000579 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000580 if (RestoreBB)
581 Builder.SetInsertPoint(RestoreBB);
582 else
583 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000584}
585
586void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
587 if (S.getRHS()) {
588 EmitCaseStmtRange(S);
589 return;
590 }
591
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000592 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000593 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000594 llvm::APSInt CaseVal = S.getLHS()->getIntegerConstantExprValue(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000595 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000596 EmitStmt(S.getSubStmt());
597}
598
599void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000600 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000601 assert(DefaultBlock->empty() &&
602 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000603 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000604 EmitStmt(S.getSubStmt());
605}
606
607void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
608 llvm::Value *CondV = EmitScalarExpr(S.getCond());
609
610 // Handle nested switch statements.
611 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000612 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000613
Daniel Dunbar16f23572008-07-25 01:11:38 +0000614 // Create basic block to hold stuff that comes after switch
615 // statement. We also need to create a default block now so that
616 // explicit case ranges tests can have a place to jump to on
617 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000618 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
619 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000620 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
621 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000622
Daniel Dunbar09124252008-11-12 08:21:33 +0000623 // Clear the insertion point to indicate we are in unreachable code.
624 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000625
Devang Patele9b8c0a2007-10-30 20:59:40 +0000626 // All break statements jump to NextBlock. If BreakContinueStack is non empty
627 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000628 llvm::BasicBlock *ContinueBlock = NULL;
629 if (!BreakContinueStack.empty())
630 ContinueBlock = BreakContinueStack.back().ContinueBlock;
631 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
632
633 // Emit switch body.
634 EmitStmt(S.getBody());
635 BreakContinueStack.pop_back();
636
Daniel Dunbar16f23572008-07-25 01:11:38 +0000637 // Update the default block in case explicit case range tests have
638 // been chained on top.
639 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000640
Daniel Dunbar16f23572008-07-25 01:11:38 +0000641 // If a default was never emitted then reroute any jumps to it and
642 // discard.
643 if (!DefaultBlock->getParent()) {
644 DefaultBlock->replaceAllUsesWith(NextBlock);
645 delete DefaultBlock;
646 }
Devang Patel51b09f22007-10-04 23:45:31 +0000647
Daniel Dunbar16f23572008-07-25 01:11:38 +0000648 // Emit continuation.
649 EmitBlock(NextBlock);
650
Devang Patel51b09f22007-10-04 23:45:31 +0000651 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000652 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000653}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000654
Anders Carlssonce179ab2008-11-09 18:54:14 +0000655static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
656{
657 // FIXME: No need to create new std::string here, we could just make sure
658 // that we don't read past the end of the string data.
659 std::string str(S.getAsmString()->getStrData(),
660 S.getAsmString()->getByteLength());
661 const char *Start = str.c_str();
662
663 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
664 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000665 Failed = false;
666
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000667 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000668 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000669 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000670 if (IsSimple) {
671 while (*Start) {
672 switch (*Start) {
673 default:
674 Result += *Start;
675 break;
676 case '$':
677 Result += "$$";
678 break;
679 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000680 Start++;
681 }
682
683 return Result;
684 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000685
686 while (*Start) {
687 switch (*Start) {
688 default:
689 Result += *Start;
690 break;
691 case '$':
692 Result += "$$";
693 break;
694 case '%':
695 // Escaped character
696 Start++;
697 if (!*Start) {
698 // FIXME: This should be caught during Sema.
699 assert(0 && "Trailing '%' in asm string.");
700 }
701
702 char EscapedChar = *Start;
703 if (EscapedChar == '%') {
704 // Escaped percentage sign.
705 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000706 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000707 // Generate an unique ID.
708 Result += llvm::utostr(AsmCounter);
709 } else if (isdigit(EscapedChar)) {
710 // %n - Assembler operand n
711 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000712 unsigned long n = strtoul(Start, &End, 10);
713 if (Start == End) {
714 // FIXME: This should be caught during Sema.
715 assert(0 && "Missing operand!");
716 } else if (n >= NumOperands) {
717 // FIXME: This should be caught during Sema.
718 assert(0 && "Operand number out of range!");
719 }
720
721 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000722 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000723 } else if (isalpha(EscapedChar)) {
724 char *End;
725
726 unsigned long n = strtoul(Start + 1, &End, 10);
727 if (Start == End) {
728 // FIXME: This should be caught during Sema.
729 assert(0 && "Missing operand!");
730 } else if (n >= NumOperands) {
731 // FIXME: This should be caught during Sema.
732 assert(0 && "Operand number out of range!");
733 }
734
735 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000736 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000737 } else if (EscapedChar == '[') {
738 std::string SymbolicName;
739
740 Start++;
741
742 while (*Start && *Start != ']') {
743 SymbolicName += *Start;
744
745 Start++;
746 }
747
748 if (!Start) {
749 // FIXME: Should be caught by sema.
750 assert(0 && "Could not parse symbolic name");
751 }
752
753 assert(*Start == ']' && "Error parsing symbolic name");
754
755 int Index = -1;
756
757 // Check if this is an output operand.
758 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
759 if (S.getOutputName(i) == SymbolicName) {
760 Index = i;
761 break;
762 }
763 }
764
765 if (Index == -1) {
766 for (unsigned i = 0; i < S.getNumInputs(); i++) {
767 if (S.getInputName(i) == SymbolicName) {
768 Index = S.getNumOutputs() + i;
769 }
770 }
771 }
772
773 assert(Index != -1 && "Did not find right operand!");
774
775 Result += '$' + llvm::utostr(Index);
776
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000777 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000778 Failed = true;
779 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000780 }
781 }
782 Start++;
783 }
784
785 return Result;
786}
787
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000788static std::string SimplifyConstraint(const char* Constraint,
789 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000790 std::string Result;
791
792 while (*Constraint) {
793 switch (*Constraint) {
794 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000795 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000796 break;
797 // Ignore these
798 case '*':
799 case '?':
800 case '!':
801 break;
802 case 'g':
803 Result += "imr";
804 break;
805 }
806
807 Constraint++;
808 }
809
810 return Result;
811}
812
813void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000814 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000815 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000816 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000817
818 if (Failed) {
819 ErrorUnsupported(&S, "asm string");
820 return;
821 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000822
823 std::string Constraints;
824
825 llvm::Value *ResultAddr = 0;
826 const llvm::Type *ResultType = llvm::Type::VoidTy;
827
828 std::vector<const llvm::Type*> ArgTypes;
829 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000830
831 // Keep track of inout constraints.
832 std::string InOutConstraints;
833 std::vector<llvm::Value*> InOutArgs;
834 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000835
836 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
837 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
838 S.getOutputConstraint(i)->getByteLength());
839
840 TargetInfo::ConstraintInfo Info;
841 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
842 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000843 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000844
845 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000846 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000847
848 LValue Dest = EmitLValue(S.getOutputExpr(i));
849 const llvm::Type *DestValueType =
850 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
851
852 // If the first output operand is not a memory dest, we'll
853 // make it the return value.
854 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000855 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000856 ResultAddr = Dest.getAddress();
857 ResultType = DestValueType;
858 Constraints += "=" + OutputConstraint;
859 } else {
860 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000861 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000862 if (i != 0)
863 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000864 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000865 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000866 }
867
868 if (Info & TargetInfo::CI_ReadWrite) {
869 // FIXME: This code should be shared with the code that handles inputs.
870 InOutConstraints += ',';
871
872 const Expr *InputExpr = S.getOutputExpr(i);
873 llvm::Value *Arg;
874 if ((Info & TargetInfo::CI_AllowsRegister) ||
875 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000876 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000877 Arg = EmitScalarExpr(InputExpr);
878 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000879 ErrorUnsupported(&S,
880 "asm statement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000881 }
882 } else {
883 LValue Dest = EmitLValue(InputExpr);
884 Arg = Dest.getAddress();
885 InOutConstraints += '*';
886 }
887
888 InOutArgTypes.push_back(Arg->getType());
889 InOutArgs.push_back(Arg);
890 InOutConstraints += OutputConstraint;
891 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000892 }
893
894 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
895
896 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
897 const Expr *InputExpr = S.getInputExpr(i);
898
899 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
900 S.getInputConstraint(i)->getByteLength());
901
902 TargetInfo::ConstraintInfo Info;
903 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Chris Lattner3304e552008-10-12 00:31:50 +0000904 NumConstraints, Info);
905 assert(result && "Failed to parse input constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000906
907 if (i != 0 || S.getNumOutputs() > 0)
908 Constraints += ',';
909
910 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000911 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000912
913 llvm::Value *Arg;
914
915 if ((Info & TargetInfo::CI_AllowsRegister) ||
916 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000917 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000918 Arg = EmitScalarExpr(InputExpr);
919 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000920 ErrorUnsupported(&S,
921 "asm statement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000922 }
923 } else {
924 LValue Dest = EmitLValue(InputExpr);
925 Arg = Dest.getAddress();
926 Constraints += '*';
927 }
928
929 ArgTypes.push_back(Arg->getType());
930 Args.push_back(Arg);
931 Constraints += InputConstraint;
932 }
933
Anders Carlssonf39a4212008-02-05 20:01:53 +0000934 // Append the "input" part of inout constraints last.
935 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
936 ArgTypes.push_back(InOutArgTypes[i]);
937 Args.push_back(InOutArgs[i]);
938 }
939 Constraints += InOutConstraints;
940
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000941 // Clobbers
942 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
943 std::string Clobber(S.getClobber(i)->getStrData(),
944 S.getClobber(i)->getByteLength());
945
946 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
947
Anders Carlssonea041752008-02-06 00:11:32 +0000948 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000949 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000950
951 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000952 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000953 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000954 }
955
956 // Add machine specific clobbers
957 if (const char *C = Target.getClobbers()) {
958 if (!Constraints.empty())
959 Constraints += ',';
960 Constraints += C;
961 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000962
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000963 const llvm::FunctionType *FTy =
964 llvm::FunctionType::get(ResultType, ArgTypes, false);
965
966 llvm::InlineAsm *IA =
967 llvm::InlineAsm::get(FTy, AsmString, Constraints,
968 S.isVolatile() || S.getNumOutputs() == 0);
969 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +0000970 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000971 Builder.CreateStore(Result, ResultAddr);
972}