blob: b042261ec380400eecabe02d0a6fb764965f5970 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Stmt nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
15#include "CodeGenModule.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "CodeGenFunction.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000017#include "clang/AST/StmtVisitor.h"
Anders Carlssonaf6a6c22008-02-05 16:35:33 +000018#include "clang/Basic/TargetInfo.h"
Anders Carlssonaf6a6c22008-02-05 16:35:33 +000019#include "llvm/InlineAsm.h"
20#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +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 Gupta40e56a12008-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 Dunbar6fc1f972008-10-17 16:15:48 +000036 DI->setLocation(S->getLocStart());
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000037 DI->EmitStopPoint(CurFn, Builder);
38 }
39
Chris Lattner4b009652007-07-25 00:24:17 +000040 switch (S->getStmtClass()) {
41 default:
Chris Lattner35055b82007-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.
Chris Lattner4b009652007-07-25 00:24:17 +000044 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner35055b82007-08-26 22:58:05 +000045 if (!hasAggregateLLVMType(E->getType()))
46 EmitScalarExpr(E);
Chris Lattnerde0908b2008-04-04 16:54:41 +000047 else if (E->getType()->isAnyComplexType())
Chris Lattner35055b82007-08-26 22:58:05 +000048 EmitComplexExpr(E);
49 else
50 EmitAggExpr(E, 0, false);
Chris Lattner4b009652007-07-25 00:24:17 +000051 } else {
Daniel Dunbar9503b782008-08-16 00:56:44 +000052 ErrorUnsupported(S, "statement");
Chris Lattner4b009652007-07-25 00:24:17 +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 Dunbar879788d2008-08-04 16:51:22 +000059 case Stmt::IndirectGotoStmtClass:
60 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Chris Lattner4b009652007-07-25 00:24:17 +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;
69
Daniel Dunbar66e021e2008-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 Patele58e0802007-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 Carlssonaf6a6c22008-02-05 16:35:33 +000091 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar5e105892008-08-23 10:51:21 +000092
93 case Stmt::ObjCAtTryStmtClass:
Anders Carlssonb01a2112008-09-09 10:04:29 +000094 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
95 break;
Daniel Dunbar5e105892008-08-23 10:51:21 +000096 case Stmt::ObjCAtCatchStmtClass:
Anders Carlsson75d86732008-09-11 09:15:33 +000097 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
98 break;
Daniel Dunbar5e105892008-08-23 10:51:21 +000099 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlssonb01a2112008-09-09 10:04:29 +0000100 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar5e105892008-08-23 10:51:21 +0000101 break;
102 case Stmt::ObjCAtThrowStmtClass:
Anders Carlssonb01a2112008-09-09 10:04:29 +0000103 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar5e105892008-08-23 10:51:21 +0000104 break;
105 case Stmt::ObjCAtSynchronizedStmtClass:
106 ErrorUnsupported(S, "@synchronized statement");
107 break;
Anders Carlsson82b0d0c2008-08-30 19:51:14 +0000108 case Stmt::ObjCForCollectionStmtClass:
109 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar5e105892008-08-23 10:51:21 +0000110 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000111 }
112}
113
Chris Lattnerea6cdd72007-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 Lattnere24c4cf2007-08-31 22:49:20 +0000117RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
118 llvm::Value *AggLoc, bool isAggVol) {
Chris Lattner4b009652007-07-25 00:24:17 +0000119 // FIXME: handle vla's etc.
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000120 CGDebugInfo *DI = CGM.getDebugInfo();
121 if (DI) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000122 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000123 DI->EmitRegionStart(CurFn, Builder);
124 }
125
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000126 for (CompoundStmt::const_body_iterator I = S.body_begin(),
127 E = S.body_end()-GetLast; I != E; ++I)
Chris Lattner4b009652007-07-25 00:24:17 +0000128 EmitStmt(*I);
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000129
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000130 if (DI) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000131 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000132 DI->EmitRegionEnd(CurFn, Builder);
133 }
134
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000135 if (!GetLast)
136 return RValue::get(0);
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000137
Chris Lattner09cee852008-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);
Chris Lattner4b009652007-07-25 00:24:17 +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 Dunbar42bd06a2008-11-11 04:12:31 +0000158 } else if (isDummyBlock(LastBB)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000159 // If the last block was an empty placeholder, remove it now.
160 // TODO: cache and reuse these.
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000161 LastBB->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +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 Dunbara2209a62008-11-11 04:34:23 +0000170void CodeGenFunction::EmitDummyBlock() {
171 EmitBlock(createBasicBlock());
172}
173
Chris Lattner09cee852008-07-26 20:23:23 +0000174void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000175 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Chris Lattner4b009652007-07-25 00:24:17 +0000176 EmitBlock(NextBB);
Chris Lattner09cee852008-07-26 20:23:23 +0000177}
178
179
180void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
181 EmitLabel(S);
Chris Lattner4b009652007-07-25 00:24:17 +0000182 EmitStmt(S.getSubStmt());
183}
184
185void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar66e021e2008-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
Chris Lattner4b009652007-07-25 00:24:17 +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 Dunbara2209a62008-11-11 04:34:23 +0000196 EmitDummyBlock();
Chris Lattner4b009652007-07-25 00:24:17 +0000197}
198
Daniel Dunbar879788d2008-08-04 16:51:22 +0000199void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbar66e021e2008-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 Dunbar879788d2008-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 Dunbara2209a62008-11-11 04:34:23 +0000217 EmitDummyBlock();
Daniel Dunbar879788d2008-08-04 16:51:22 +0000218}
219
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000220void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000221 // C99 6.8.4.1: The first substatement is executed if the expression compares
222 // unequal to 0. The condition must be a scalar type.
223 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
224
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000225 // If we constant folded the condition to true or false, try to avoid emitting
226 // the dead arm at all.
227 if (llvm::ConstantInt *CondCst = dyn_cast<llvm::ConstantInt>(BoolCondVal)) {
228 // Figure out which block (then or else) is executed.
229 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
230 if (!CondCst->getZExtValue())
231 std::swap(Executed, Skipped);
232
233 // If the skipped block has no labels in it, just emit the executed block.
234 // This avoids emitting dead code and simplifies the CFG substantially.
235 if (Skipped == 0 || !ContainsLabel(Skipped)) {
236 if (Executed)
237 EmitStmt(Executed);
238 return;
239 }
240 }
241
Daniel Dunbar72f96552008-11-11 02:29:29 +0000242 llvm::BasicBlock *ContBlock = createBasicBlock("ifend");
243 llvm::BasicBlock *ThenBlock = createBasicBlock("ifthen");
Chris Lattner4b009652007-07-25 00:24:17 +0000244 llvm::BasicBlock *ElseBlock = ContBlock;
245
246 if (S.getElse())
Daniel Dunbar72f96552008-11-11 02:29:29 +0000247 ElseBlock = createBasicBlock("ifelse");
Chris Lattner4b009652007-07-25 00:24:17 +0000248
249 // Insert the conditional branch.
250 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
251
252 // Emit the 'then' code.
253 EmitBlock(ThenBlock);
254 EmitStmt(S.getThen());
Devang Patel97299362007-09-28 21:49:18 +0000255 llvm::BasicBlock *BB = Builder.GetInsertBlock();
256 if (isDummyBlock(BB)) {
257 BB->eraseFromParent();
258 Builder.SetInsertPoint(ThenBlock);
Chris Lattnera23eb7b2008-07-26 20:15:14 +0000259 } else {
Devang Patel97299362007-09-28 21:49:18 +0000260 Builder.CreateBr(ContBlock);
Chris Lattnera23eb7b2008-07-26 20:15:14 +0000261 }
Chris Lattner4b009652007-07-25 00:24:17 +0000262
263 // Emit the 'else' code if present.
264 if (const Stmt *Else = S.getElse()) {
265 EmitBlock(ElseBlock);
266 EmitStmt(Else);
Devang Patel97299362007-09-28 21:49:18 +0000267 llvm::BasicBlock *BB = Builder.GetInsertBlock();
268 if (isDummyBlock(BB)) {
269 BB->eraseFromParent();
270 Builder.SetInsertPoint(ElseBlock);
Chris Lattnera23eb7b2008-07-26 20:15:14 +0000271 } else {
Devang Patel97299362007-09-28 21:49:18 +0000272 Builder.CreateBr(ContBlock);
Chris Lattnera23eb7b2008-07-26 20:15:14 +0000273 }
Chris Lattner4b009652007-07-25 00:24:17 +0000274 }
275
276 // Emit the continuation block for code after the if.
277 EmitBlock(ContBlock);
278}
279
280void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
281 // Emit the header for the loop, insert it, which will create an uncond br to
282 // it.
Daniel Dunbar72f96552008-11-11 02:29:29 +0000283 llvm::BasicBlock *LoopHeader = createBasicBlock("whilecond");
Chris Lattner4b009652007-07-25 00:24:17 +0000284 EmitBlock(LoopHeader);
285
286 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
287 // of the controlling expression takes place before each execution of the loop
288 // body.
289 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel706f8442007-10-09 20:51:27 +0000290
291 // while(1) is common, avoid extra exit blocks. Be sure
Chris Lattner4b009652007-07-25 00:24:17 +0000292 // to correctly handle break/continue though.
Devang Patel706f8442007-10-09 20:51:27 +0000293 bool EmitBoolCondBranch = true;
294 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
295 if (C->isOne())
296 EmitBoolCondBranch = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000297
298 // Create an exit block for when the condition fails, create a block for the
299 // body of the loop.
Daniel Dunbar72f96552008-11-11 02:29:29 +0000300 llvm::BasicBlock *ExitBlock = createBasicBlock("whileexit");
301 llvm::BasicBlock *LoopBody = createBasicBlock("whilebody");
Chris Lattner4b009652007-07-25 00:24:17 +0000302
303 // As long as the condition is true, go to the loop body.
Devang Patel706f8442007-10-09 20:51:27 +0000304 if (EmitBoolCondBranch)
305 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000306
307 // Store the blocks to use for break and continue.
308 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
309
310 // Emit the loop body.
311 EmitBlock(LoopBody);
312 EmitStmt(S.getBody());
313
314 BreakContinueStack.pop_back();
315
316 // Cycle to the condition.
317 Builder.CreateBr(LoopHeader);
318
319 // Emit the exit block.
320 EmitBlock(ExitBlock);
Devang Patel706f8442007-10-09 20:51:27 +0000321
322 // If LoopHeader is a simple forwarding block then eliminate it.
323 if (!EmitBoolCondBranch
324 && &LoopHeader->front() == LoopHeader->getTerminator()) {
325 LoopHeader->replaceAllUsesWith(LoopBody);
326 LoopHeader->getTerminator()->eraseFromParent();
327 LoopHeader->eraseFromParent();
328 }
Chris Lattner4b009652007-07-25 00:24:17 +0000329}
330
331void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000332 // Emit the body for the loop, insert it, which will create an uncond br to
333 // it.
Daniel Dunbar72f96552008-11-11 02:29:29 +0000334 llvm::BasicBlock *LoopBody = createBasicBlock("dobody");
335 llvm::BasicBlock *AfterDo = createBasicBlock("afterdo");
Chris Lattner4b009652007-07-25 00:24:17 +0000336 EmitBlock(LoopBody);
337
Daniel Dunbar72f96552008-11-11 02:29:29 +0000338 llvm::BasicBlock *DoCond = createBasicBlock("docond");
Chris Lattner4b009652007-07-25 00:24:17 +0000339
340 // Store the blocks to use for break and continue.
341 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
342
343 // Emit the body of the loop into the block.
344 EmitStmt(S.getBody());
345
346 BreakContinueStack.pop_back();
347
348 EmitBlock(DoCond);
349
350 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
351 // after each execution of the loop body."
352
353 // Evaluate the conditional in the while header.
354 // C99 6.8.5p2/p4: The first substatement is executed if the expression
355 // compares unequal to 0. The condition must be a scalar type.
356 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel716d02c2007-10-09 20:33:39 +0000357
358 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
359 // to correctly handle break/continue though.
360 bool EmitBoolCondBranch = true;
361 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
362 if (C->isZero())
363 EmitBoolCondBranch = false;
364
Chris Lattner4b009652007-07-25 00:24:17 +0000365 // As long as the condition is true, iterate the loop.
Devang Patel716d02c2007-10-09 20:33:39 +0000366 if (EmitBoolCondBranch)
367 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Chris Lattner4b009652007-07-25 00:24:17 +0000368
369 // Emit the exit block.
370 EmitBlock(AfterDo);
Devang Patel716d02c2007-10-09 20:33:39 +0000371
372 // If DoCond is a simple forwarding block then eliminate it.
373 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
374 DoCond->replaceAllUsesWith(AfterDo);
375 DoCond->getTerminator()->eraseFromParent();
376 DoCond->eraseFromParent();
377 }
Chris Lattner4b009652007-07-25 00:24:17 +0000378}
379
380void CodeGenFunction::EmitForStmt(const ForStmt &S) {
381 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
382 // which contains a continue/break?
383 // TODO: We could keep track of whether the loop body contains any
384 // break/continue statements and not create unnecessary blocks (like
385 // "afterfor" for a condless loop) if it doesn't.
386
387 // Evaluate the first part before the loop.
388 if (S.getInit())
389 EmitStmt(S.getInit());
390
391 // Start the loop with a block that tests the condition.
Daniel Dunbar72f96552008-11-11 02:29:29 +0000392 llvm::BasicBlock *CondBlock = createBasicBlock("forcond");
393 llvm::BasicBlock *AfterFor = createBasicBlock("afterfor");
Chris Lattner4b009652007-07-25 00:24:17 +0000394
395 EmitBlock(CondBlock);
396
397 // Evaluate the condition if present. If not, treat it as a non-zero-constant
398 // according to 6.8.5.3p2, aka, true.
399 if (S.getCond()) {
400 // C99 6.8.5p2/p4: The first substatement is executed if the expression
401 // compares unequal to 0. The condition must be a scalar type.
402 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
403
404 // As long as the condition is true, iterate the loop.
Daniel Dunbar72f96552008-11-11 02:29:29 +0000405 llvm::BasicBlock *ForBody = createBasicBlock("forbody");
Chris Lattner4b009652007-07-25 00:24:17 +0000406 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
407 EmitBlock(ForBody);
408 } else {
409 // Treat it as a non-zero constant. Don't even create a new block for the
410 // body, just fall into it.
411 }
412
413 // If the for loop doesn't have an increment we can just use the
414 // condition as the continue block.
415 llvm::BasicBlock *ContinueBlock;
416 if (S.getInc())
Daniel Dunbar72f96552008-11-11 02:29:29 +0000417 ContinueBlock = createBasicBlock("forinc");
Chris Lattner4b009652007-07-25 00:24:17 +0000418 else
419 ContinueBlock = CondBlock;
420
421 // Store the blocks to use for break and continue.
422 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
423
424 // If the condition is true, execute the body of the for stmt.
425 EmitStmt(S.getBody());
426
427 BreakContinueStack.pop_back();
428
Chris Lattner4b009652007-07-25 00:24:17 +0000429 // If there is an increment, emit it next.
Daniel Dunbar8ca61b22008-09-28 00:19:22 +0000430 if (S.getInc()) {
431 EmitBlock(ContinueBlock);
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000432 EmitStmt(S.getInc());
Daniel Dunbar8ca61b22008-09-28 00:19:22 +0000433 }
Chris Lattner4b009652007-07-25 00:24:17 +0000434
435 // Finally, branch back up to the condition for the next iteration.
436 Builder.CreateBr(CondBlock);
437
438 // Emit the fall-through block.
439 EmitBlock(AfterFor);
440}
441
Daniel Dunbare856ac22008-09-24 04:00:38 +0000442void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
443 if (RV.isScalar()) {
444 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
445 } else if (RV.isAggregate()) {
446 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
447 } else {
448 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
449 }
450 Builder.CreateBr(ReturnBlock);
451
452 // Emit a block after the branch so that dead code after a return has some
453 // place to go.
Daniel Dunbara2209a62008-11-11 04:34:23 +0000454 EmitDummyBlock();
Daniel Dunbare856ac22008-09-24 04:00:38 +0000455}
456
Chris Lattner4b009652007-07-25 00:24:17 +0000457/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
458/// if the function returns void, or may be missing one if the function returns
459/// non-void. Fun stuff :).
460void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000461 // Emit the result value, even if unused, to evalute the side effects.
462 const Expr *RV = S.getRetValue();
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000463
464 // FIXME: Clean this up by using an LValue for ReturnTemp,
465 // EmitStoreThroughLValue, and EmitAnyExpr.
466 if (!ReturnValue) {
467 // Make sure not to return anything, but evaluate the expression
468 // for side effects.
469 if (RV)
Eli Friedman56977312008-05-22 01:22:33 +0000470 EmitAnyExpr(RV);
Chris Lattner4b009652007-07-25 00:24:17 +0000471 } else if (RV == 0) {
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000472 // Do nothing (return value is left uninitialized)
Chris Lattner74b93032007-08-26 07:14:44 +0000473 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000474 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattnerde0908b2008-04-04 16:54:41 +0000475 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000476 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000477 } else {
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000478 EmitAggExpr(RV, ReturnValue, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000479 }
Eli Friedman56977312008-05-22 01:22:33 +0000480
Daniel Dunbare9900eb2008-09-30 01:06:03 +0000481 if (!ObjCEHStack.empty()) {
482 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
483 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar72f96552008-11-11 02:29:29 +0000484 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbare9900eb2008-09-30 01:06:03 +0000485 EmitJumpThroughFinally(*i, ReturnPad);
486 EmitBlock(ReturnPad);
487 }
488 }
489
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000490 Builder.CreateBr(ReturnBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000491
492 // Emit a block after the branch so that dead code after a return has some
493 // place to go.
Daniel Dunbara2209a62008-11-11 04:34:23 +0000494 EmitDummyBlock();
Chris Lattner4b009652007-07-25 00:24:17 +0000495}
496
497void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneka6b2b272008-10-06 18:42:27 +0000498 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
499 I != E; ++I)
500 EmitDecl(**I);
Chris Lattner4b009652007-07-25 00:24:17 +0000501}
502
503void CodeGenFunction::EmitBreakStmt() {
504 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
505
506 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
507 Builder.CreateBr(Block);
Daniel Dunbara2209a62008-11-11 04:34:23 +0000508 EmitDummyBlock();
Chris Lattner4b009652007-07-25 00:24:17 +0000509}
510
511void CodeGenFunction::EmitContinueStmt() {
512 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
513
514 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
515 Builder.CreateBr(Block);
Daniel Dunbara2209a62008-11-11 04:34:23 +0000516 EmitDummyBlock();
Chris Lattner4b009652007-07-25 00:24:17 +0000517}
Devang Patele58e0802007-10-04 23:45:31 +0000518
Devang Patel347ca322007-10-08 20:57:48 +0000519/// EmitCaseStmtRange - If case statement range is not too big then
520/// add multiple cases to switch instruction, one for each value within
521/// the range. If range is too big then emit "if" condition check.
522void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000523 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patel347ca322007-10-08 20:57:48 +0000524
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000525 llvm::APSInt LHS = S.getLHS()->getIntegerConstantExprValue(getContext());
526 llvm::APSInt RHS = S.getRHS()->getIntegerConstantExprValue(getContext());
527
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000528 // Emit the code for this case. We do this first to make sure it is
529 // properly chained from our predecessor before generating the
530 // switch machinery to enter this block.
Daniel Dunbar42bd06a2008-11-11 04:12:31 +0000531 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000532 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
533 EmitStmt(S.getSubStmt());
534
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000535 // If range is empty, do nothing.
536 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
537 return;
Devang Patel347ca322007-10-08 20:57:48 +0000538
539 llvm::APInt Range = RHS - LHS;
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000540 // FIXME: parameters such as this should not be hardcoded.
Devang Patel347ca322007-10-08 20:57:48 +0000541 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
542 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000543 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patelcf9dbf22007-10-05 20:54:07 +0000544 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
545 LHS++;
546 }
Devang Patel347ca322007-10-08 20:57:48 +0000547 return;
548 }
549
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000550 // The range is too big. Emit "if" condition into a new block,
551 // making sure to save and restore the current insertion point.
552 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patelcf9dbf22007-10-05 20:54:07 +0000553
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000554 // Push this test onto the chain of range checks (which terminates
555 // in the default basic block). The switch's default will be changed
556 // to the top of this chain after switch emission is complete.
557 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar72f96552008-11-11 02:29:29 +0000558 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patel347ca322007-10-08 20:57:48 +0000559
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000560 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
561 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patel347ca322007-10-08 20:57:48 +0000562
563 // Emit range check.
564 llvm::Value *Diff =
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000565 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
566 "tmp");
Devang Patel347ca322007-10-08 20:57:48 +0000567 llvm::Value *Cond =
568 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
569 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
570
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000571 // Restore the appropriate insertion point.
572 Builder.SetInsertPoint(RestoreBB);
Devang Patel347ca322007-10-08 20:57:48 +0000573}
574
575void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
576 if (S.getRHS()) {
577 EmitCaseStmtRange(S);
578 return;
579 }
580
Daniel Dunbar42bd06a2008-11-11 04:12:31 +0000581 EmitBlock(createBasicBlock("sw.bb"));
Devang Patel347ca322007-10-08 20:57:48 +0000582 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000583 llvm::APSInt CaseVal = S.getLHS()->getIntegerConstantExprValue(getContext());
Daniel Dunbar72f96552008-11-11 02:29:29 +0000584 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patele58e0802007-10-04 23:45:31 +0000585 EmitStmt(S.getSubStmt());
586}
587
588void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000589 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar72f96552008-11-11 02:29:29 +0000590 assert(DefaultBlock->empty() &&
591 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000592 EmitBlock(DefaultBlock);
Devang Patele58e0802007-10-04 23:45:31 +0000593 EmitStmt(S.getSubStmt());
594}
595
596void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
597 llvm::Value *CondV = EmitScalarExpr(S.getCond());
598
599 // Handle nested switch statements.
600 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patel347ca322007-10-08 20:57:48 +0000601 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patele58e0802007-10-04 23:45:31 +0000602
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000603 // Create basic block to hold stuff that comes after switch
604 // statement. We also need to create a default block now so that
605 // explicit case ranges tests can have a place to jump to on
606 // failure.
Daniel Dunbar72f96552008-11-11 02:29:29 +0000607 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
608 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000609 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
610 CaseRangeBlock = DefaultBlock;
Devang Patele58e0802007-10-04 23:45:31 +0000611
Eli Friedman51eaf1b2008-05-12 16:08:04 +0000612 // Create basic block for body of switch
Daniel Dunbar42bd06a2008-11-11 04:12:31 +0000613 EmitBlock(createBasicBlock("sw.body"));
Eli Friedman51eaf1b2008-05-12 16:08:04 +0000614
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000615 // All break statements jump to NextBlock. If BreakContinueStack is non empty
616 // then reuse last ContinueBlock.
Devang Patele58e0802007-10-04 23:45:31 +0000617 llvm::BasicBlock *ContinueBlock = NULL;
618 if (!BreakContinueStack.empty())
619 ContinueBlock = BreakContinueStack.back().ContinueBlock;
620 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
621
622 // Emit switch body.
623 EmitStmt(S.getBody());
624 BreakContinueStack.pop_back();
625
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000626 // Update the default block in case explicit case range tests have
627 // been chained on top.
628 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patel347ca322007-10-08 20:57:48 +0000629
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000630 // If a default was never emitted then reroute any jumps to it and
631 // discard.
632 if (!DefaultBlock->getParent()) {
633 DefaultBlock->replaceAllUsesWith(NextBlock);
634 delete DefaultBlock;
635 }
Devang Patele58e0802007-10-04 23:45:31 +0000636
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000637 // Emit continuation.
638 EmitBlock(NextBlock);
639
Devang Patele58e0802007-10-04 23:45:31 +0000640 SwitchInsn = SavedSwitchInsn;
Devang Patel347ca322007-10-08 20:57:48 +0000641 CaseRangeBlock = SavedCRBlock;
Devang Patele58e0802007-10-04 23:45:31 +0000642}
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000643
Anders Carlssondf8f3042008-11-09 18:54:14 +0000644static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
645{
646 // FIXME: No need to create new std::string here, we could just make sure
647 // that we don't read past the end of the string data.
648 std::string str(S.getAsmString()->getStrData(),
649 S.getAsmString()->getByteLength());
650 const char *Start = str.c_str();
651
652 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
653 bool IsSimple = S.isSimple();
Daniel Dunbar33cd0ff2008-10-17 20:58:01 +0000654 Failed = false;
655
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000656 static unsigned AsmCounter = 0;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000657 AsmCounter++;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000658 std::string Result;
Anders Carlsson52234522008-02-05 23:18:57 +0000659 if (IsSimple) {
660 while (*Start) {
661 switch (*Start) {
662 default:
663 Result += *Start;
664 break;
665 case '$':
666 Result += "$$";
667 break;
668 }
Anders Carlsson52234522008-02-05 23:18:57 +0000669 Start++;
670 }
671
672 return Result;
673 }
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000674
675 while (*Start) {
676 switch (*Start) {
677 default:
678 Result += *Start;
679 break;
680 case '$':
681 Result += "$$";
682 break;
683 case '%':
684 // Escaped character
685 Start++;
686 if (!*Start) {
687 // FIXME: This should be caught during Sema.
688 assert(0 && "Trailing '%' in asm string.");
689 }
690
691 char EscapedChar = *Start;
692 if (EscapedChar == '%') {
693 // Escaped percentage sign.
694 Result += '%';
Chris Lattnera23eb7b2008-07-26 20:15:14 +0000695 } else if (EscapedChar == '=') {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000696 // Generate an unique ID.
697 Result += llvm::utostr(AsmCounter);
698 } else if (isdigit(EscapedChar)) {
699 // %n - Assembler operand n
700 char *End;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000701 unsigned long n = strtoul(Start, &End, 10);
702 if (Start == End) {
703 // FIXME: This should be caught during Sema.
704 assert(0 && "Missing operand!");
705 } else if (n >= NumOperands) {
706 // FIXME: This should be caught during Sema.
707 assert(0 && "Operand number out of range!");
708 }
709
710 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancioee48f3f2008-02-26 19:19:58 +0000711 Start = End - 1;
Anders Carlsson52234522008-02-05 23:18:57 +0000712 } else if (isalpha(EscapedChar)) {
713 char *End;
714
715 unsigned long n = strtoul(Start + 1, &End, 10);
716 if (Start == End) {
717 // FIXME: This should be caught during Sema.
718 assert(0 && "Missing operand!");
719 } else if (n >= NumOperands) {
720 // FIXME: This should be caught during Sema.
721 assert(0 && "Operand number out of range!");
722 }
723
724 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancioee48f3f2008-02-26 19:19:58 +0000725 Start = End - 1;
Anders Carlssondf8f3042008-11-09 18:54:14 +0000726 } else if (EscapedChar == '[') {
727 std::string SymbolicName;
728
729 Start++;
730
731 while (*Start && *Start != ']') {
732 SymbolicName += *Start;
733
734 Start++;
735 }
736
737 if (!Start) {
738 // FIXME: Should be caught by sema.
739 assert(0 && "Could not parse symbolic name");
740 }
741
742 assert(*Start == ']' && "Error parsing symbolic name");
743
744 int Index = -1;
745
746 // Check if this is an output operand.
747 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
748 if (S.getOutputName(i) == SymbolicName) {
749 Index = i;
750 break;
751 }
752 }
753
754 if (Index == -1) {
755 for (unsigned i = 0; i < S.getNumInputs(); i++) {
756 if (S.getInputName(i) == SymbolicName) {
757 Index = S.getNumOutputs() + i;
758 }
759 }
760 }
761
762 assert(Index != -1 && "Did not find right operand!");
763
764 Result += '$' + llvm::utostr(Index);
765
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000766 } else {
Daniel Dunbar33cd0ff2008-10-17 20:58:01 +0000767 Failed = true;
768 return "";
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000769 }
770 }
771 Start++;
772 }
773
774 return Result;
775}
776
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +0000777static std::string SimplifyConstraint(const char* Constraint,
778 TargetInfo &Target) {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000779 std::string Result;
780
781 while (*Constraint) {
782 switch (*Constraint) {
783 default:
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +0000784 Result += Target.convertConstraint(*Constraint);
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000785 break;
786 // Ignore these
787 case '*':
788 case '?':
789 case '!':
790 break;
791 case 'g':
792 Result += "imr";
793 break;
794 }
795
796 Constraint++;
797 }
798
799 return Result;
800}
801
802void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar33cd0ff2008-10-17 20:58:01 +0000803 bool Failed;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000804 std::string AsmString =
Anders Carlssondf8f3042008-11-09 18:54:14 +0000805 ConvertAsmString(S, Failed);
Daniel Dunbar33cd0ff2008-10-17 20:58:01 +0000806
807 if (Failed) {
808 ErrorUnsupported(&S, "asm string");
809 return;
810 }
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000811
812 std::string Constraints;
813
814 llvm::Value *ResultAddr = 0;
815 const llvm::Type *ResultType = llvm::Type::VoidTy;
816
817 std::vector<const llvm::Type*> ArgTypes;
818 std::vector<llvm::Value*> Args;
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000819
820 // Keep track of inout constraints.
821 std::string InOutConstraints;
822 std::vector<llvm::Value*> InOutArgs;
823 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000824
825 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
826 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
827 S.getOutputConstraint(i)->getByteLength());
828
829 TargetInfo::ConstraintInfo Info;
830 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
831 Info);
Chris Lattner94c4b2d2008-10-12 00:31:50 +0000832 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000833
834 // Simplify the output constraint.
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +0000835 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000836
837 LValue Dest = EmitLValue(S.getOutputExpr(i));
838 const llvm::Type *DestValueType =
839 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
840
841 // If the first output operand is not a memory dest, we'll
842 // make it the return value.
843 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohman377ba9f2008-05-22 22:12:56 +0000844 DestValueType->isSingleValueType()) {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000845 ResultAddr = Dest.getAddress();
846 ResultType = DestValueType;
847 Constraints += "=" + OutputConstraint;
848 } else {
849 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlsson78725072008-02-05 16:57:38 +0000850 Args.push_back(Dest.getAddress());
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000851 if (i != 0)
852 Constraints += ',';
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000853 Constraints += "=*";
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000854 Constraints += OutputConstraint;
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000855 }
856
857 if (Info & TargetInfo::CI_ReadWrite) {
858 // FIXME: This code should be shared with the code that handles inputs.
859 InOutConstraints += ',';
860
861 const Expr *InputExpr = S.getOutputExpr(i);
862 llvm::Value *Arg;
863 if ((Info & TargetInfo::CI_AllowsRegister) ||
864 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohman377ba9f2008-05-22 22:12:56 +0000865 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000866 Arg = EmitScalarExpr(InputExpr);
867 } else {
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000868 ErrorUnsupported(&S,
869 "asm statement passing multiple-value types as inputs");
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000870 }
871 } else {
872 LValue Dest = EmitLValue(InputExpr);
873 Arg = Dest.getAddress();
874 InOutConstraints += '*';
875 }
876
877 InOutArgTypes.push_back(Arg->getType());
878 InOutArgs.push_back(Arg);
879 InOutConstraints += OutputConstraint;
880 }
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000881 }
882
883 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
884
885 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
886 const Expr *InputExpr = S.getInputExpr(i);
887
888 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
889 S.getInputConstraint(i)->getByteLength());
890
891 TargetInfo::ConstraintInfo Info;
892 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Chris Lattner94c4b2d2008-10-12 00:31:50 +0000893 NumConstraints, Info);
894 assert(result && "Failed to parse input constraint"); result=result;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000895
896 if (i != 0 || S.getNumOutputs() > 0)
897 Constraints += ',';
898
899 // Simplify the input constraint.
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +0000900 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000901
902 llvm::Value *Arg;
903
904 if ((Info & TargetInfo::CI_AllowsRegister) ||
905 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohman377ba9f2008-05-22 22:12:56 +0000906 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000907 Arg = EmitScalarExpr(InputExpr);
908 } else {
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000909 ErrorUnsupported(&S,
910 "asm statement passing multiple-value types as inputs");
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000911 }
912 } else {
913 LValue Dest = EmitLValue(InputExpr);
914 Arg = Dest.getAddress();
915 Constraints += '*';
916 }
917
918 ArgTypes.push_back(Arg->getType());
919 Args.push_back(Arg);
920 Constraints += InputConstraint;
921 }
922
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000923 // Append the "input" part of inout constraints last.
924 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
925 ArgTypes.push_back(InOutArgTypes[i]);
926 Args.push_back(InOutArgs[i]);
927 }
928 Constraints += InOutConstraints;
929
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000930 // Clobbers
931 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
932 std::string Clobber(S.getClobber(i)->getStrData(),
933 S.getClobber(i)->getByteLength());
934
935 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
936
Anders Carlsson74385982008-02-06 00:11:32 +0000937 if (i != 0 || NumConstraints != 0)
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000938 Constraints += ',';
Anders Carlsson74385982008-02-06 00:11:32 +0000939
940 Constraints += "~{";
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000941 Constraints += Clobber;
Anders Carlsson74385982008-02-06 00:11:32 +0000942 Constraints += '}';
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000943 }
944
945 // Add machine specific clobbers
946 if (const char *C = Target.getClobbers()) {
947 if (!Constraints.empty())
948 Constraints += ',';
949 Constraints += C;
950 }
Anders Carlsson0d3019e2008-02-05 20:01:53 +0000951
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000952 const llvm::FunctionType *FTy =
953 llvm::FunctionType::get(ResultType, ArgTypes, false);
954
955 llvm::InlineAsm *IA =
956 llvm::InlineAsm::get(FTy, AsmString, Constraints,
957 S.isVolatile() || S.getNumOutputs() == 0);
958 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman2e630542008-06-13 23:01:12 +0000959 if (ResultAddr) // FIXME: volatility
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000960 Builder.CreateStore(Result, ResultAddr);
961}