blob: 1d9b30eca84485a5de8fe595d2d462594311666d [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
28void CodeGenFunction::EmitStmt(const Stmt *S) {
29 assert(S && "Null statement?");
30
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000031 // Generate stoppoints if we are emitting debug info.
32 // Beginning of a Compound Statement (e.g. an opening '{') does not produce
33 // executable code. So do not generate a stoppoint for that.
34 CGDebugInfo *DI = CGM.getDebugInfo();
35 if (DI && S->getStmtClass() != Stmt::CompoundStmtClass) {
Daniel Dunbar66031a52008-10-17 16:15:48 +000036 DI->setLocation(S->getLocStart());
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000037 DI->EmitStopPoint(CurFn, Builder);
38 }
39
Reid Spencer5f016e22007-07-11 17:01:13 +000040 switch (S->getStmtClass()) {
41 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000042 // Must be an expression in a stmt context. Emit the value (to get
43 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000044 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000045 if (!hasAggregateLLVMType(E->getType()))
46 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000047 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000048 EmitComplexExpr(E);
49 else
50 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000051 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000052 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000053 }
54 break;
55 case Stmt::NullStmtClass: break;
56 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
57 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
58 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000059 case Stmt::IndirectGotoStmtClass:
60 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000061
62 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
63 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
64 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
65 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
66
67 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
68 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Chris Lattnerda138702007-07-16 21:28:45 +000069
Daniel Dunbara4275d12008-10-02 18:02:06 +000070 case Stmt::BreakStmtClass:
71 // FIXME: Implement break in @try or @catch blocks.
72 if (!ObjCEHStack.empty()) {
73 CGM.ErrorUnsupported(S, "continue inside an Obj-C exception block");
74 return;
75 }
76 EmitBreakStmt();
77 break;
78
79 case Stmt::ContinueStmtClass:
80 // FIXME: Implement continue in @try or @catch blocks.
81 if (!ObjCEHStack.empty()) {
82 CGM.ErrorUnsupported(S, "continue inside an Obj-C exception block");
83 return;
84 }
85 EmitContinueStmt();
86 break;
87
Devang Patel51b09f22007-10-04 23:45:31 +000088 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
89 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
90 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000091 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000092
93 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000094 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
95 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000096 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +000097 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
98 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000099 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000100 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000101 break;
102 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000103 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000104 break;
105 case Stmt::ObjCAtSynchronizedStmtClass:
106 ErrorUnsupported(S, "@synchronized statement");
107 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000108 case Stmt::ObjCForCollectionStmtClass:
109 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000110 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 }
112}
113
Chris Lattner33793202007-08-31 22:09:40 +0000114/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
115/// this captures the expression result of the last sub-statement and returns it
116/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000117RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
118 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 // FIXME: handle vla's etc.
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000120 CGDebugInfo *DI = CGM.getDebugInfo();
121 if (DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000122 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000123 DI->EmitRegionStart(CurFn, Builder);
124 }
125
Chris Lattner33793202007-08-31 22:09:40 +0000126 for (CompoundStmt::const_body_iterator I = S.body_begin(),
127 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000128 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000129
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000130 if (DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000131 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000132 DI->EmitRegionEnd(CurFn, Builder);
133 }
134
Chris Lattner33793202007-08-31 22:09:40 +0000135 if (!GetLast)
136 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +0000137
Chris Lattner91d723d2008-07-26 20:23:23 +0000138 // We have to special case labels here. They are statements, but when put at
139 // the end of a statement expression, they yield the value of their
140 // subexpression. Handle this by walking through all labels we encounter,
141 // emitting them before we evaluate the subexpr.
142 const Stmt *LastStmt = S.body_back();
143 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
144 EmitLabel(*LS);
145 LastStmt = LS->getSubStmt();
146 }
147
148 return EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000149}
150
151void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
152 // Emit a branch from this block to the next one if this was a real block. If
153 // this was just a fall-through block after a terminator, don't emit it.
154 llvm::BasicBlock *LastBB = Builder.GetInsertBlock();
155
156 if (LastBB->getTerminator()) {
157 // If the previous block is already terminated, don't touch it.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000158 } else if (isDummyBlock(LastBB)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 // If the last block was an empty placeholder, remove it now.
160 // TODO: cache and reuse these.
Daniel Dunbar16f23572008-07-25 01:11:38 +0000161 LastBB->eraseFromParent();
Reid Spencer5f016e22007-07-11 17:01:13 +0000162 } else {
163 // Otherwise, create a fall-through branch.
164 Builder.CreateBr(BB);
165 }
166 CurFn->getBasicBlockList().push_back(BB);
167 Builder.SetInsertPoint(BB);
168}
169
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000170void CodeGenFunction::EmitDummyBlock() {
171 EmitBlock(createBasicBlock());
172}
173
Chris Lattner91d723d2008-07-26 20:23:23 +0000174void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000175 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000176 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000177}
178
179
180void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
181 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000182 EmitStmt(S.getSubStmt());
183}
184
185void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000186 // FIXME: Implement goto out in @try or @catch blocks.
187 if (!ObjCEHStack.empty()) {
188 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
189 return;
190 }
191
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 Builder.CreateBr(getBasicBlockForLabel(S.getLabel()));
193
194 // Emit a block after the branch so that dead code after a goto has some place
195 // to go.
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000196 EmitDummyBlock();
Reid Spencer5f016e22007-07-11 17:01:13 +0000197}
198
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000199void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000200 // FIXME: Implement indirect goto in @try or @catch blocks.
201 if (!ObjCEHStack.empty()) {
202 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
203 return;
204 }
205
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000206 // Emit initial switch which will be patched up later by
207 // EmitIndirectSwitches(). We need a default dest, so we use the
208 // current BB, but this is overwritten.
209 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
210 llvm::Type::Int32Ty,
211 "addr");
212 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
213 IndirectSwitches.push_back(I);
214
215 // Emit a block after the branch so that dead code after a goto has some place
216 // to go.
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000217 EmitDummyBlock();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000218}
219
Chris Lattner62b72f62008-11-11 07:24:28 +0000220/// ContainsLabel - Return true if the statement contains a label in it. If
221/// this statement is not executed normally, it not containing a label means
222/// that we can just remove the code.
223static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false) {
224 // If this is a label, we have to emit the code, consider something like:
225 // if (0) { ... foo: bar(); } goto foo;
226 if (isa<LabelStmt>(S))
227 return true;
228
229 // If this is a case/default statement, and we haven't seen a switch, we have
230 // to emit the code.
231 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
232 return true;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000233
Chris Lattner62b72f62008-11-11 07:24:28 +0000234 // If this is a switch statement, we want to ignore cases below it.
235 if (isa<SwitchStmt>(S))
236 IgnoreCaseStmts = true;
237
238 // Scan subexpressions for verboten labels.
239 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
240 I != E; ++I)
241 if (ContainsLabel(*I, IgnoreCaseStmts))
242 return true;
243
244 return false;
245}
246
247
248void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 // C99 6.8.4.1: The first substatement is executed if the expression compares
250 // unequal to 0. The condition must be a scalar type.
251 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
252
Chris Lattner62b72f62008-11-11 07:24:28 +0000253 // If we constant folded the condition to true or false, try to avoid emitting
254 // the dead arm at all.
255 if (llvm::ConstantInt *CondCst = dyn_cast<llvm::ConstantInt>(BoolCondVal)) {
256 // Figure out which block (then or else) is executed.
257 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
258 if (!CondCst->getZExtValue())
259 std::swap(Executed, Skipped);
260
261 // If the skipped block has no labels in it, just emit the executed block.
262 // This avoids emitting dead code and simplifies the CFG substantially.
263 if (Skipped == 0 || !ContainsLabel(Skipped)) {
264 if (Executed)
265 EmitStmt(Executed);
266 return;
267 }
268 }
269
Daniel Dunbar55e87422008-11-11 02:29:29 +0000270 llvm::BasicBlock *ContBlock = createBasicBlock("ifend");
271 llvm::BasicBlock *ThenBlock = createBasicBlock("ifthen");
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 llvm::BasicBlock *ElseBlock = ContBlock;
273
274 if (S.getElse())
Daniel Dunbar55e87422008-11-11 02:29:29 +0000275 ElseBlock = createBasicBlock("ifelse");
Reid Spencer5f016e22007-07-11 17:01:13 +0000276
277 // Insert the conditional branch.
278 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
279
280 // Emit the 'then' code.
281 EmitBlock(ThenBlock);
282 EmitStmt(S.getThen());
Devang Pateld9363c32007-09-28 21:49:18 +0000283 llvm::BasicBlock *BB = Builder.GetInsertBlock();
284 if (isDummyBlock(BB)) {
285 BB->eraseFromParent();
286 Builder.SetInsertPoint(ThenBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000287 } else {
Devang Pateld9363c32007-09-28 21:49:18 +0000288 Builder.CreateBr(ContBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000289 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000290
291 // Emit the 'else' code if present.
292 if (const Stmt *Else = S.getElse()) {
293 EmitBlock(ElseBlock);
294 EmitStmt(Else);
Devang Pateld9363c32007-09-28 21:49:18 +0000295 llvm::BasicBlock *BB = Builder.GetInsertBlock();
296 if (isDummyBlock(BB)) {
297 BB->eraseFromParent();
298 Builder.SetInsertPoint(ElseBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000299 } else {
Devang Pateld9363c32007-09-28 21:49:18 +0000300 Builder.CreateBr(ContBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000301 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000302 }
303
304 // Emit the continuation block for code after the if.
305 EmitBlock(ContBlock);
306}
307
308void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 // Emit the header for the loop, insert it, which will create an uncond br to
310 // it.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000311 llvm::BasicBlock *LoopHeader = createBasicBlock("whilecond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 EmitBlock(LoopHeader);
313
314 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
315 // of the controlling expression takes place before each execution of the loop
316 // body.
317 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000318
319 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000320 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000321 bool EmitBoolCondBranch = true;
322 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
323 if (C->isOne())
324 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000325
326 // Create an exit block for when the condition fails, create a block for the
327 // body of the loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000328 llvm::BasicBlock *ExitBlock = createBasicBlock("whileexit");
329 llvm::BasicBlock *LoopBody = createBasicBlock("whilebody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000330
331 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000332 if (EmitBoolCondBranch)
333 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000334
335 // Store the blocks to use for break and continue.
336 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000337
338 // Emit the loop body.
339 EmitBlock(LoopBody);
340 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000341
342 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000343
344 // Cycle to the condition.
345 Builder.CreateBr(LoopHeader);
346
347 // Emit the exit block.
348 EmitBlock(ExitBlock);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000349
350 // If LoopHeader is a simple forwarding block then eliminate it.
351 if (!EmitBoolCondBranch
352 && &LoopHeader->front() == LoopHeader->getTerminator()) {
353 LoopHeader->replaceAllUsesWith(LoopBody);
354 LoopHeader->getTerminator()->eraseFromParent();
355 LoopHeader->eraseFromParent();
356 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000357}
358
359void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000360 // Emit the body for the loop, insert it, which will create an uncond br to
361 // it.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000362 llvm::BasicBlock *LoopBody = createBasicBlock("dobody");
363 llvm::BasicBlock *AfterDo = createBasicBlock("afterdo");
Reid Spencer5f016e22007-07-11 17:01:13 +0000364 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000365
Daniel Dunbar55e87422008-11-11 02:29:29 +0000366 llvm::BasicBlock *DoCond = createBasicBlock("docond");
Chris Lattnerda138702007-07-16 21:28:45 +0000367
368 // Store the blocks to use for break and continue.
369 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000370
371 // Emit the body of the loop into the block.
372 EmitStmt(S.getBody());
373
Chris Lattnerda138702007-07-16 21:28:45 +0000374 BreakContinueStack.pop_back();
375
376 EmitBlock(DoCond);
377
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
379 // after each execution of the loop body."
380
381 // Evaluate the conditional in the while header.
382 // C99 6.8.5p2/p4: The first substatement is executed if the expression
383 // compares unequal to 0. The condition must be a scalar type.
384 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000385
386 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
387 // to correctly handle break/continue though.
388 bool EmitBoolCondBranch = true;
389 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
390 if (C->isZero())
391 EmitBoolCondBranch = false;
392
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000394 if (EmitBoolCondBranch)
395 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000396
397 // Emit the exit block.
398 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000399
400 // If DoCond is a simple forwarding block then eliminate it.
401 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
402 DoCond->replaceAllUsesWith(AfterDo);
403 DoCond->getTerminator()->eraseFromParent();
404 DoCond->eraseFromParent();
405 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000406}
407
408void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
410 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000411 // TODO: We could keep track of whether the loop body contains any
412 // break/continue statements and not create unnecessary blocks (like
413 // "afterfor" for a condless loop) if it doesn't.
414
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 // Evaluate the first part before the loop.
416 if (S.getInit())
417 EmitStmt(S.getInit());
418
419 // Start the loop with a block that tests the condition.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000420 llvm::BasicBlock *CondBlock = createBasicBlock("forcond");
421 llvm::BasicBlock *AfterFor = createBasicBlock("afterfor");
Chris Lattnerda138702007-07-16 21:28:45 +0000422
Reid Spencer5f016e22007-07-11 17:01:13 +0000423 EmitBlock(CondBlock);
424
425 // Evaluate the condition if present. If not, treat it as a non-zero-constant
426 // according to 6.8.5.3p2, aka, true.
427 if (S.getCond()) {
428 // C99 6.8.5p2/p4: The first substatement is executed if the expression
429 // compares unequal to 0. The condition must be a scalar type.
430 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
431
432 // As long as the condition is true, iterate the loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000433 llvm::BasicBlock *ForBody = createBasicBlock("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000434 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
435 EmitBlock(ForBody);
436 } else {
437 // Treat it as a non-zero constant. Don't even create a new block for the
438 // body, just fall into it.
439 }
440
Chris Lattnerda138702007-07-16 21:28:45 +0000441 // If the for loop doesn't have an increment we can just use the
442 // condition as the continue block.
443 llvm::BasicBlock *ContinueBlock;
444 if (S.getInc())
Daniel Dunbar55e87422008-11-11 02:29:29 +0000445 ContinueBlock = createBasicBlock("forinc");
Chris Lattnerda138702007-07-16 21:28:45 +0000446 else
447 ContinueBlock = CondBlock;
448
449 // Store the blocks to use for break and continue.
450 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
451
Reid Spencer5f016e22007-07-11 17:01:13 +0000452 // If the condition is true, execute the body of the for stmt.
453 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000454
455 BreakContinueStack.pop_back();
456
Reid Spencer5f016e22007-07-11 17:01:13 +0000457 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000458 if (S.getInc()) {
459 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000460 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000461 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000462
463 // Finally, branch back up to the condition for the next iteration.
464 Builder.CreateBr(CondBlock);
465
Chris Lattnerda138702007-07-16 21:28:45 +0000466 // Emit the fall-through block.
467 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000468}
469
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000470void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
471 if (RV.isScalar()) {
472 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
473 } else if (RV.isAggregate()) {
474 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
475 } else {
476 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
477 }
478 Builder.CreateBr(ReturnBlock);
479
480 // Emit a block after the branch so that dead code after a return has some
481 // place to go.
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000482 EmitDummyBlock();
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000483}
484
Reid Spencer5f016e22007-07-11 17:01:13 +0000485/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
486/// if the function returns void, or may be missing one if the function returns
487/// non-void. Fun stuff :).
488void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000489 // Emit the result value, even if unused, to evalute the side effects.
490 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000491
492 // FIXME: Clean this up by using an LValue for ReturnTemp,
493 // EmitStoreThroughLValue, and EmitAnyExpr.
494 if (!ReturnValue) {
495 // Make sure not to return anything, but evaluate the expression
496 // for side effects.
497 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000498 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000499 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000500 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000501 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000502 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000503 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000504 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000506 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000507 }
Eli Friedman144ac612008-05-22 01:22:33 +0000508
Daniel Dunbar898d5082008-09-30 01:06:03 +0000509 if (!ObjCEHStack.empty()) {
510 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
511 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000512 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000513 EmitJumpThroughFinally(*i, ReturnPad);
514 EmitBlock(ReturnPad);
515 }
516 }
517
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000518 Builder.CreateBr(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000519
520 // Emit a block after the branch so that dead code after a return has some
521 // place to go.
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000522 EmitDummyBlock();
Reid Spencer5f016e22007-07-11 17:01:13 +0000523}
524
525void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000526 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
527 I != E; ++I)
528 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000529}
Chris Lattnerda138702007-07-16 21:28:45 +0000530
531void CodeGenFunction::EmitBreakStmt() {
532 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
533
534 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
535 Builder.CreateBr(Block);
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000536 EmitDummyBlock();
Chris Lattnerda138702007-07-16 21:28:45 +0000537}
538
539void CodeGenFunction::EmitContinueStmt() {
540 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
541
542 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
543 Builder.CreateBr(Block);
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000544 EmitDummyBlock();
Chris Lattnerda138702007-07-16 21:28:45 +0000545}
Devang Patel51b09f22007-10-04 23:45:31 +0000546
Devang Patelc049e4f2007-10-08 20:57:48 +0000547/// EmitCaseStmtRange - If case statement range is not too big then
548/// add multiple cases to switch instruction, one for each value within
549/// the range. If range is too big then emit "if" condition check.
550void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000551 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000552
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000553 llvm::APSInt LHS = S.getLHS()->getIntegerConstantExprValue(getContext());
554 llvm::APSInt RHS = S.getRHS()->getIntegerConstantExprValue(getContext());
555
Daniel Dunbar16f23572008-07-25 01:11:38 +0000556 // Emit the code for this case. We do this first to make sure it is
557 // properly chained from our predecessor before generating the
558 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000559 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000560 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
561 EmitStmt(S.getSubStmt());
562
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000563 // If range is empty, do nothing.
564 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
565 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000566
567 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000568 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000569 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
570 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000571 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000572 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
573 LHS++;
574 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000575 return;
576 }
577
Daniel Dunbar16f23572008-07-25 01:11:38 +0000578 // The range is too big. Emit "if" condition into a new block,
579 // making sure to save and restore the current insertion point.
580 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000581
Daniel Dunbar16f23572008-07-25 01:11:38 +0000582 // Push this test onto the chain of range checks (which terminates
583 // in the default basic block). The switch's default will be changed
584 // to the top of this chain after switch emission is complete.
585 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000586 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000587
Daniel Dunbar16f23572008-07-25 01:11:38 +0000588 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
589 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000590
591 // Emit range check.
592 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000593 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
594 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000595 llvm::Value *Cond =
596 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
597 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
598
Daniel Dunbar16f23572008-07-25 01:11:38 +0000599 // Restore the appropriate insertion point.
600 Builder.SetInsertPoint(RestoreBB);
Devang Patelc049e4f2007-10-08 20:57:48 +0000601}
602
603void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
604 if (S.getRHS()) {
605 EmitCaseStmtRange(S);
606 return;
607 }
608
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000609 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000610 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000611 llvm::APSInt CaseVal = S.getLHS()->getIntegerConstantExprValue(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000612 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000613 EmitStmt(S.getSubStmt());
614}
615
616void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000617 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000618 assert(DefaultBlock->empty() &&
619 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000620 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000621 EmitStmt(S.getSubStmt());
622}
623
624void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
625 llvm::Value *CondV = EmitScalarExpr(S.getCond());
626
627 // Handle nested switch statements.
628 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000629 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000630
Daniel Dunbar16f23572008-07-25 01:11:38 +0000631 // Create basic block to hold stuff that comes after switch
632 // statement. We also need to create a default block now so that
633 // explicit case ranges tests can have a place to jump to on
634 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000635 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
636 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000637 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
638 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000639
Eli Friedmand28a80d2008-05-12 16:08:04 +0000640 // Create basic block for body of switch
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000641 EmitBlock(createBasicBlock("sw.body"));
Eli Friedmand28a80d2008-05-12 16:08:04 +0000642
Devang Patele9b8c0a2007-10-30 20:59:40 +0000643 // All break statements jump to NextBlock. If BreakContinueStack is non empty
644 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000645 llvm::BasicBlock *ContinueBlock = NULL;
646 if (!BreakContinueStack.empty())
647 ContinueBlock = BreakContinueStack.back().ContinueBlock;
648 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
649
650 // Emit switch body.
651 EmitStmt(S.getBody());
652 BreakContinueStack.pop_back();
653
Daniel Dunbar16f23572008-07-25 01:11:38 +0000654 // Update the default block in case explicit case range tests have
655 // been chained on top.
656 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000657
Daniel Dunbar16f23572008-07-25 01:11:38 +0000658 // If a default was never emitted then reroute any jumps to it and
659 // discard.
660 if (!DefaultBlock->getParent()) {
661 DefaultBlock->replaceAllUsesWith(NextBlock);
662 delete DefaultBlock;
663 }
Devang Patel51b09f22007-10-04 23:45:31 +0000664
Daniel Dunbar16f23572008-07-25 01:11:38 +0000665 // Emit continuation.
666 EmitBlock(NextBlock);
667
Devang Patel51b09f22007-10-04 23:45:31 +0000668 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000669 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000670}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000671
Anders Carlssonce179ab2008-11-09 18:54:14 +0000672static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
673{
674 // FIXME: No need to create new std::string here, we could just make sure
675 // that we don't read past the end of the string data.
676 std::string str(S.getAsmString()->getStrData(),
677 S.getAsmString()->getByteLength());
678 const char *Start = str.c_str();
679
680 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
681 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000682 Failed = false;
683
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000684 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000685 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000686 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000687 if (IsSimple) {
688 while (*Start) {
689 switch (*Start) {
690 default:
691 Result += *Start;
692 break;
693 case '$':
694 Result += "$$";
695 break;
696 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000697 Start++;
698 }
699
700 return Result;
701 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000702
703 while (*Start) {
704 switch (*Start) {
705 default:
706 Result += *Start;
707 break;
708 case '$':
709 Result += "$$";
710 break;
711 case '%':
712 // Escaped character
713 Start++;
714 if (!*Start) {
715 // FIXME: This should be caught during Sema.
716 assert(0 && "Trailing '%' in asm string.");
717 }
718
719 char EscapedChar = *Start;
720 if (EscapedChar == '%') {
721 // Escaped percentage sign.
722 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000723 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000724 // Generate an unique ID.
725 Result += llvm::utostr(AsmCounter);
726 } else if (isdigit(EscapedChar)) {
727 // %n - Assembler operand n
728 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000729 unsigned long n = strtoul(Start, &End, 10);
730 if (Start == End) {
731 // FIXME: This should be caught during Sema.
732 assert(0 && "Missing operand!");
733 } else if (n >= NumOperands) {
734 // FIXME: This should be caught during Sema.
735 assert(0 && "Operand number out of range!");
736 }
737
738 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000739 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000740 } else if (isalpha(EscapedChar)) {
741 char *End;
742
743 unsigned long n = strtoul(Start + 1, &End, 10);
744 if (Start == End) {
745 // FIXME: This should be caught during Sema.
746 assert(0 && "Missing operand!");
747 } else if (n >= NumOperands) {
748 // FIXME: This should be caught during Sema.
749 assert(0 && "Operand number out of range!");
750 }
751
752 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000753 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000754 } else if (EscapedChar == '[') {
755 std::string SymbolicName;
756
757 Start++;
758
759 while (*Start && *Start != ']') {
760 SymbolicName += *Start;
761
762 Start++;
763 }
764
765 if (!Start) {
766 // FIXME: Should be caught by sema.
767 assert(0 && "Could not parse symbolic name");
768 }
769
770 assert(*Start == ']' && "Error parsing symbolic name");
771
772 int Index = -1;
773
774 // Check if this is an output operand.
775 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
776 if (S.getOutputName(i) == SymbolicName) {
777 Index = i;
778 break;
779 }
780 }
781
782 if (Index == -1) {
783 for (unsigned i = 0; i < S.getNumInputs(); i++) {
784 if (S.getInputName(i) == SymbolicName) {
785 Index = S.getNumOutputs() + i;
786 }
787 }
788 }
789
790 assert(Index != -1 && "Did not find right operand!");
791
792 Result += '$' + llvm::utostr(Index);
793
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000794 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000795 Failed = true;
796 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000797 }
798 }
799 Start++;
800 }
801
802 return Result;
803}
804
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000805static std::string SimplifyConstraint(const char* Constraint,
806 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000807 std::string Result;
808
809 while (*Constraint) {
810 switch (*Constraint) {
811 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000812 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000813 break;
814 // Ignore these
815 case '*':
816 case '?':
817 case '!':
818 break;
819 case 'g':
820 Result += "imr";
821 break;
822 }
823
824 Constraint++;
825 }
826
827 return Result;
828}
829
830void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000831 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000832 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000833 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000834
835 if (Failed) {
836 ErrorUnsupported(&S, "asm string");
837 return;
838 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000839
840 std::string Constraints;
841
842 llvm::Value *ResultAddr = 0;
843 const llvm::Type *ResultType = llvm::Type::VoidTy;
844
845 std::vector<const llvm::Type*> ArgTypes;
846 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000847
848 // Keep track of inout constraints.
849 std::string InOutConstraints;
850 std::vector<llvm::Value*> InOutArgs;
851 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000852
853 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
854 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
855 S.getOutputConstraint(i)->getByteLength());
856
857 TargetInfo::ConstraintInfo Info;
858 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
859 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000860 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000861
862 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000863 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000864
865 LValue Dest = EmitLValue(S.getOutputExpr(i));
866 const llvm::Type *DestValueType =
867 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
868
869 // If the first output operand is not a memory dest, we'll
870 // make it the return value.
871 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000872 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000873 ResultAddr = Dest.getAddress();
874 ResultType = DestValueType;
875 Constraints += "=" + OutputConstraint;
876 } else {
877 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000878 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000879 if (i != 0)
880 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000881 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000882 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000883 }
884
885 if (Info & TargetInfo::CI_ReadWrite) {
886 // FIXME: This code should be shared with the code that handles inputs.
887 InOutConstraints += ',';
888
889 const Expr *InputExpr = S.getOutputExpr(i);
890 llvm::Value *Arg;
891 if ((Info & TargetInfo::CI_AllowsRegister) ||
892 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000893 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000894 Arg = EmitScalarExpr(InputExpr);
895 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000896 ErrorUnsupported(&S,
897 "asm statement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000898 }
899 } else {
900 LValue Dest = EmitLValue(InputExpr);
901 Arg = Dest.getAddress();
902 InOutConstraints += '*';
903 }
904
905 InOutArgTypes.push_back(Arg->getType());
906 InOutArgs.push_back(Arg);
907 InOutConstraints += OutputConstraint;
908 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000909 }
910
911 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
912
913 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
914 const Expr *InputExpr = S.getInputExpr(i);
915
916 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
917 S.getInputConstraint(i)->getByteLength());
918
919 TargetInfo::ConstraintInfo Info;
920 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Chris Lattner3304e552008-10-12 00:31:50 +0000921 NumConstraints, Info);
922 assert(result && "Failed to parse input constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000923
924 if (i != 0 || S.getNumOutputs() > 0)
925 Constraints += ',';
926
927 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000928 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000929
930 llvm::Value *Arg;
931
932 if ((Info & TargetInfo::CI_AllowsRegister) ||
933 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000934 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000935 Arg = EmitScalarExpr(InputExpr);
936 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000937 ErrorUnsupported(&S,
938 "asm statement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000939 }
940 } else {
941 LValue Dest = EmitLValue(InputExpr);
942 Arg = Dest.getAddress();
943 Constraints += '*';
944 }
945
946 ArgTypes.push_back(Arg->getType());
947 Args.push_back(Arg);
948 Constraints += InputConstraint;
949 }
950
Anders Carlssonf39a4212008-02-05 20:01:53 +0000951 // Append the "input" part of inout constraints last.
952 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
953 ArgTypes.push_back(InOutArgTypes[i]);
954 Args.push_back(InOutArgs[i]);
955 }
956 Constraints += InOutConstraints;
957
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000958 // Clobbers
959 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
960 std::string Clobber(S.getClobber(i)->getStrData(),
961 S.getClobber(i)->getByteLength());
962
963 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
964
Anders Carlssonea041752008-02-06 00:11:32 +0000965 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000966 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000967
968 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000969 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000970 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000971 }
972
973 // Add machine specific clobbers
974 if (const char *C = Target.getClobbers()) {
975 if (!Constraints.empty())
976 Constraints += ',';
977 Constraints += C;
978 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000979
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000980 const llvm::FunctionType *FTy =
981 llvm::FunctionType::get(ResultType, ArgTypes, false);
982
983 llvm::InlineAsm *IA =
984 llvm::InlineAsm::get(FTy, AsmString, Constraints,
985 S.isVolatile() || S.getNumOutputs() == 0);
986 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +0000987 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000988 Builder.CreateStore(Result, ResultAddr);
989}