blob: f70b86661df52080d3f766269c2890046b9eda5f [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) {
36 if (S->getLocStart().isValid()) {
37 DI->setLocation(S->getLocStart());
38 }
39
40 DI->EmitStopPoint(CurFn, Builder);
41 }
42
Reid Spencer5f016e22007-07-11 17:01:13 +000043 switch (S->getStmtClass()) {
44 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000045 // Must be an expression in a stmt context. Emit the value (to get
46 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000047 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000048 if (!hasAggregateLLVMType(E->getType()))
49 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000050 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000051 EmitComplexExpr(E);
52 else
53 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000054 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000055 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000056 }
57 break;
58 case Stmt::NullStmtClass: break;
59 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
60 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
61 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000062 case Stmt::IndirectGotoStmtClass:
63 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000064
65 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
66 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
67 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
68 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
69
70 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
71 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Chris Lattnerda138702007-07-16 21:28:45 +000072
Daniel Dunbara4275d12008-10-02 18:02:06 +000073 case Stmt::BreakStmtClass:
74 // FIXME: Implement break in @try or @catch blocks.
75 if (!ObjCEHStack.empty()) {
76 CGM.ErrorUnsupported(S, "continue inside an Obj-C exception block");
77 return;
78 }
79 EmitBreakStmt();
80 break;
81
82 case Stmt::ContinueStmtClass:
83 // FIXME: Implement continue in @try or @catch blocks.
84 if (!ObjCEHStack.empty()) {
85 CGM.ErrorUnsupported(S, "continue inside an Obj-C exception block");
86 return;
87 }
88 EmitContinueStmt();
89 break;
90
Devang Patel51b09f22007-10-04 23:45:31 +000091 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
92 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
93 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000094 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000095
96 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000097 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
98 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000099 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +0000100 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
101 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000102 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000103 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000104 break;
105 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000106 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000107 break;
108 case Stmt::ObjCAtSynchronizedStmtClass:
109 ErrorUnsupported(S, "@synchronized statement");
110 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000111 case Stmt::ObjCForCollectionStmtClass:
112 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000113 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000114 }
115}
116
Chris Lattner33793202007-08-31 22:09:40 +0000117/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
118/// this captures the expression result of the last sub-statement and returns it
119/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000120RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
121 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 // FIXME: handle vla's etc.
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000123 CGDebugInfo *DI = CGM.getDebugInfo();
124 if (DI) {
Chris Lattner345f7202008-07-26 20:15:14 +0000125 if (S.getLBracLoc().isValid())
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000126 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000127 DI->EmitRegionStart(CurFn, Builder);
128 }
129
Chris Lattner33793202007-08-31 22:09:40 +0000130 for (CompoundStmt::const_body_iterator I = S.body_begin(),
131 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000133
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000134 if (DI) {
Chris Lattner345f7202008-07-26 20:15:14 +0000135 if (S.getRBracLoc().isValid())
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000136 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000137 DI->EmitRegionEnd(CurFn, Builder);
138 }
139
Chris Lattner33793202007-08-31 22:09:40 +0000140 if (!GetLast)
141 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +0000142
Chris Lattner91d723d2008-07-26 20:23:23 +0000143 // We have to special case labels here. They are statements, but when put at
144 // the end of a statement expression, they yield the value of their
145 // subexpression. Handle this by walking through all labels we encounter,
146 // emitting them before we evaluate the subexpr.
147 const Stmt *LastStmt = S.body_back();
148 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
149 EmitLabel(*LS);
150 LastStmt = LS->getSubStmt();
151 }
152
153 return EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000154}
155
156void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
157 // Emit a branch from this block to the next one if this was a real block. If
158 // this was just a fall-through block after a terminator, don't emit it.
159 llvm::BasicBlock *LastBB = Builder.GetInsertBlock();
160
161 if (LastBB->getTerminator()) {
162 // If the previous block is already terminated, don't touch it.
Daniel Dunbar16f23572008-07-25 01:11:38 +0000163 } else if (LastBB->empty() && isDummyBlock(LastBB)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000164 // If the last block was an empty placeholder, remove it now.
165 // TODO: cache and reuse these.
Daniel Dunbar16f23572008-07-25 01:11:38 +0000166 LastBB->eraseFromParent();
Reid Spencer5f016e22007-07-11 17:01:13 +0000167 } else {
168 // Otherwise, create a fall-through branch.
169 Builder.CreateBr(BB);
170 }
171 CurFn->getBasicBlockList().push_back(BB);
172 Builder.SetInsertPoint(BB);
173}
174
Chris Lattner91d723d2008-07-26 20:23:23 +0000175void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000176 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000177 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000178}
179
180
181void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
182 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 EmitStmt(S.getSubStmt());
184}
185
186void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000187 // FIXME: Implement goto out in @try or @catch blocks.
188 if (!ObjCEHStack.empty()) {
189 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
190 return;
191 }
192
Reid Spencer5f016e22007-07-11 17:01:13 +0000193 Builder.CreateBr(getBasicBlockForLabel(S.getLabel()));
194
195 // Emit a block after the branch so that dead code after a goto has some place
196 // to go.
Gabor Greif984d0b42008-04-06 20:42:52 +0000197 Builder.SetInsertPoint(llvm::BasicBlock::Create("", CurFn));
Reid Spencer5f016e22007-07-11 17:01:13 +0000198}
199
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000200void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000201 // FIXME: Implement indirect goto in @try or @catch blocks.
202 if (!ObjCEHStack.empty()) {
203 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
204 return;
205 }
206
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000207 // Emit initial switch which will be patched up later by
208 // EmitIndirectSwitches(). We need a default dest, so we use the
209 // current BB, but this is overwritten.
210 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
211 llvm::Type::Int32Ty,
212 "addr");
213 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
214 IndirectSwitches.push_back(I);
215
216 // Emit a block after the branch so that dead code after a goto has some place
217 // to go.
218 Builder.SetInsertPoint(llvm::BasicBlock::Create("", CurFn));
219}
220
Reid Spencer5f016e22007-07-11 17:01:13 +0000221void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000222 // FIXME: It would probably be nice for us to skip emission of if
223 // (0) code here.
224
Reid Spencer5f016e22007-07-11 17:01:13 +0000225 // C99 6.8.4.1: The first substatement is executed if the expression compares
226 // unequal to 0. The condition must be a scalar type.
227 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
228
Gabor Greif984d0b42008-04-06 20:42:52 +0000229 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("ifend");
230 llvm::BasicBlock *ThenBlock = llvm::BasicBlock::Create("ifthen");
Reid Spencer5f016e22007-07-11 17:01:13 +0000231 llvm::BasicBlock *ElseBlock = ContBlock;
232
233 if (S.getElse())
Gabor Greif984d0b42008-04-06 20:42:52 +0000234 ElseBlock = llvm::BasicBlock::Create("ifelse");
Reid Spencer5f016e22007-07-11 17:01:13 +0000235
236 // Insert the conditional branch.
237 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
238
239 // Emit the 'then' code.
240 EmitBlock(ThenBlock);
241 EmitStmt(S.getThen());
Devang Pateld9363c32007-09-28 21:49:18 +0000242 llvm::BasicBlock *BB = Builder.GetInsertBlock();
243 if (isDummyBlock(BB)) {
244 BB->eraseFromParent();
245 Builder.SetInsertPoint(ThenBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000246 } else {
Devang Pateld9363c32007-09-28 21:49:18 +0000247 Builder.CreateBr(ContBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000248 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000249
250 // Emit the 'else' code if present.
251 if (const Stmt *Else = S.getElse()) {
252 EmitBlock(ElseBlock);
253 EmitStmt(Else);
Devang Pateld9363c32007-09-28 21:49:18 +0000254 llvm::BasicBlock *BB = Builder.GetInsertBlock();
255 if (isDummyBlock(BB)) {
256 BB->eraseFromParent();
257 Builder.SetInsertPoint(ElseBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000258 } else {
Devang Pateld9363c32007-09-28 21:49:18 +0000259 Builder.CreateBr(ContBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000260 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000261 }
262
263 // Emit the continuation block for code after the if.
264 EmitBlock(ContBlock);
265}
266
267void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000268 // Emit the header for the loop, insert it, which will create an uncond br to
269 // it.
Gabor Greif984d0b42008-04-06 20:42:52 +0000270 llvm::BasicBlock *LoopHeader = llvm::BasicBlock::Create("whilecond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000271 EmitBlock(LoopHeader);
272
273 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
274 // of the controlling expression takes place before each execution of the loop
275 // body.
276 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000277
278 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000280 bool EmitBoolCondBranch = true;
281 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
282 if (C->isOne())
283 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000284
285 // Create an exit block for when the condition fails, create a block for the
286 // body of the loop.
Gabor Greif984d0b42008-04-06 20:42:52 +0000287 llvm::BasicBlock *ExitBlock = llvm::BasicBlock::Create("whileexit");
288 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("whilebody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000289
290 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000291 if (EmitBoolCondBranch)
292 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000293
294 // Store the blocks to use for break and continue.
295 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000296
297 // Emit the loop body.
298 EmitBlock(LoopBody);
299 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000300
301 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000302
303 // Cycle to the condition.
304 Builder.CreateBr(LoopHeader);
305
306 // Emit the exit block.
307 EmitBlock(ExitBlock);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000308
309 // If LoopHeader is a simple forwarding block then eliminate it.
310 if (!EmitBoolCondBranch
311 && &LoopHeader->front() == LoopHeader->getTerminator()) {
312 LoopHeader->replaceAllUsesWith(LoopBody);
313 LoopHeader->getTerminator()->eraseFromParent();
314 LoopHeader->eraseFromParent();
315 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000316}
317
318void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 // Emit the body for the loop, insert it, which will create an uncond br to
320 // it.
Gabor Greif984d0b42008-04-06 20:42:52 +0000321 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("dobody");
322 llvm::BasicBlock *AfterDo = llvm::BasicBlock::Create("afterdo");
Reid Spencer5f016e22007-07-11 17:01:13 +0000323 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000324
Gabor Greif984d0b42008-04-06 20:42:52 +0000325 llvm::BasicBlock *DoCond = llvm::BasicBlock::Create("docond");
Chris Lattnerda138702007-07-16 21:28:45 +0000326
327 // Store the blocks to use for break and continue.
328 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000329
330 // Emit the body of the loop into the block.
331 EmitStmt(S.getBody());
332
Chris Lattnerda138702007-07-16 21:28:45 +0000333 BreakContinueStack.pop_back();
334
335 EmitBlock(DoCond);
336
Reid Spencer5f016e22007-07-11 17:01:13 +0000337 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
338 // after each execution of the loop body."
339
340 // Evaluate the conditional in the while header.
341 // C99 6.8.5p2/p4: The first substatement is executed if the expression
342 // compares unequal to 0. The condition must be a scalar type.
343 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000344
345 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
346 // to correctly handle break/continue though.
347 bool EmitBoolCondBranch = true;
348 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
349 if (C->isZero())
350 EmitBoolCondBranch = false;
351
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000353 if (EmitBoolCondBranch)
354 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000355
356 // Emit the exit block.
357 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000358
359 // If DoCond is a simple forwarding block then eliminate it.
360 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
361 DoCond->replaceAllUsesWith(AfterDo);
362 DoCond->getTerminator()->eraseFromParent();
363 DoCond->eraseFromParent();
364 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000365}
366
367void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
369 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000370 // TODO: We could keep track of whether the loop body contains any
371 // break/continue statements and not create unnecessary blocks (like
372 // "afterfor" for a condless loop) if it doesn't.
373
Reid Spencer5f016e22007-07-11 17:01:13 +0000374 // Evaluate the first part before the loop.
375 if (S.getInit())
376 EmitStmt(S.getInit());
377
378 // Start the loop with a block that tests the condition.
Gabor Greif984d0b42008-04-06 20:42:52 +0000379 llvm::BasicBlock *CondBlock = llvm::BasicBlock::Create("forcond");
380 llvm::BasicBlock *AfterFor = llvm::BasicBlock::Create("afterfor");
Chris Lattnerda138702007-07-16 21:28:45 +0000381
Reid Spencer5f016e22007-07-11 17:01:13 +0000382 EmitBlock(CondBlock);
383
384 // Evaluate the condition if present. If not, treat it as a non-zero-constant
385 // according to 6.8.5.3p2, aka, true.
386 if (S.getCond()) {
387 // C99 6.8.5p2/p4: The first substatement is executed if the expression
388 // compares unequal to 0. The condition must be a scalar type.
389 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
390
391 // As long as the condition is true, iterate the loop.
Gabor Greif984d0b42008-04-06 20:42:52 +0000392 llvm::BasicBlock *ForBody = llvm::BasicBlock::Create("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
394 EmitBlock(ForBody);
395 } else {
396 // Treat it as a non-zero constant. Don't even create a new block for the
397 // body, just fall into it.
398 }
399
Chris Lattnerda138702007-07-16 21:28:45 +0000400 // If the for loop doesn't have an increment we can just use the
401 // condition as the continue block.
402 llvm::BasicBlock *ContinueBlock;
403 if (S.getInc())
Gabor Greif984d0b42008-04-06 20:42:52 +0000404 ContinueBlock = llvm::BasicBlock::Create("forinc");
Chris Lattnerda138702007-07-16 21:28:45 +0000405 else
406 ContinueBlock = CondBlock;
407
408 // Store the blocks to use for break and continue.
409 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
410
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 // If the condition is true, execute the body of the for stmt.
412 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000413
414 BreakContinueStack.pop_back();
415
Reid Spencer5f016e22007-07-11 17:01:13 +0000416 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000417 if (S.getInc()) {
418 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000419 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000420 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000421
422 // Finally, branch back up to the condition for the next iteration.
423 Builder.CreateBr(CondBlock);
424
Chris Lattnerda138702007-07-16 21:28:45 +0000425 // Emit the fall-through block.
426 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000427}
428
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000429void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
430 if (RV.isScalar()) {
431 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
432 } else if (RV.isAggregate()) {
433 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
434 } else {
435 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
436 }
437 Builder.CreateBr(ReturnBlock);
438
439 // Emit a block after the branch so that dead code after a return has some
440 // place to go.
441 EmitBlock(llvm::BasicBlock::Create());
442}
443
Reid Spencer5f016e22007-07-11 17:01:13 +0000444/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
445/// if the function returns void, or may be missing one if the function returns
446/// non-void. Fun stuff :).
447void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000448 // Emit the result value, even if unused, to evalute the side effects.
449 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000450
451 // FIXME: Clean this up by using an LValue for ReturnTemp,
452 // EmitStoreThroughLValue, and EmitAnyExpr.
453 if (!ReturnValue) {
454 // Make sure not to return anything, but evaluate the expression
455 // for side effects.
456 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000457 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000458 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000459 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000460 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000461 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000462 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000463 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000464 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000465 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 }
Eli Friedman144ac612008-05-22 01:22:33 +0000467
Daniel Dunbar898d5082008-09-30 01:06:03 +0000468 if (!ObjCEHStack.empty()) {
469 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
470 e = ObjCEHStack.rend(); i != e; ++i) {
471 llvm::BasicBlock *ReturnPad = llvm::BasicBlock::Create("return.pad");
472 EmitJumpThroughFinally(*i, ReturnPad);
473 EmitBlock(ReturnPad);
474 }
475 }
476
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000477 Builder.CreateBr(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000478
479 // Emit a block after the branch so that dead code after a return has some
480 // place to go.
Gabor Greif984d0b42008-04-06 20:42:52 +0000481 EmitBlock(llvm::BasicBlock::Create());
Reid Spencer5f016e22007-07-11 17:01:13 +0000482}
483
484void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Steve Naroff94745042007-09-13 23:52:58 +0000485 for (const ScopedDecl *Decl = S.getDecl(); Decl;
486 Decl = Decl->getNextDeclarator())
Reid Spencer5f016e22007-07-11 17:01:13 +0000487 EmitDecl(*Decl);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000488}
Chris Lattnerda138702007-07-16 21:28:45 +0000489
490void CodeGenFunction::EmitBreakStmt() {
491 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
492
493 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
494 Builder.CreateBr(Block);
Gabor Greif984d0b42008-04-06 20:42:52 +0000495 EmitBlock(llvm::BasicBlock::Create());
Chris Lattnerda138702007-07-16 21:28:45 +0000496}
497
498void CodeGenFunction::EmitContinueStmt() {
499 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
500
501 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
502 Builder.CreateBr(Block);
Gabor Greif984d0b42008-04-06 20:42:52 +0000503 EmitBlock(llvm::BasicBlock::Create());
Chris Lattnerda138702007-07-16 21:28:45 +0000504}
Devang Patel51b09f22007-10-04 23:45:31 +0000505
Devang Patelc049e4f2007-10-08 20:57:48 +0000506/// EmitCaseStmtRange - If case statement range is not too big then
507/// add multiple cases to switch instruction, one for each value within
508/// the range. If range is too big then emit "if" condition check.
509void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000510 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000511
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000512 llvm::APSInt LHS = S.getLHS()->getIntegerConstantExprValue(getContext());
513 llvm::APSInt RHS = S.getRHS()->getIntegerConstantExprValue(getContext());
514
Daniel Dunbar16f23572008-07-25 01:11:38 +0000515 // Emit the code for this case. We do this first to make sure it is
516 // properly chained from our predecessor before generating the
517 // switch machinery to enter this block.
518 StartBlock("sw.bb");
519 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
520 EmitStmt(S.getSubStmt());
521
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000522 // If range is empty, do nothing.
523 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
524 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000525
526 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000527 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000528 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
529 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000530 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000531 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
532 LHS++;
533 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000534 return;
535 }
536
Daniel Dunbar16f23572008-07-25 01:11:38 +0000537 // The range is too big. Emit "if" condition into a new block,
538 // making sure to save and restore the current insertion point.
539 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000540
Daniel Dunbar16f23572008-07-25 01:11:38 +0000541 // Push this test onto the chain of range checks (which terminates
542 // in the default basic block). The switch's default will be changed
543 // to the top of this chain after switch emission is complete.
544 llvm::BasicBlock *FalseDest = CaseRangeBlock;
545 CaseRangeBlock = llvm::BasicBlock::Create("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000546
Daniel Dunbar16f23572008-07-25 01:11:38 +0000547 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
548 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000549
550 // Emit range check.
551 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000552 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
553 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000554 llvm::Value *Cond =
555 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
556 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
557
Daniel Dunbar16f23572008-07-25 01:11:38 +0000558 // Restore the appropriate insertion point.
559 Builder.SetInsertPoint(RestoreBB);
Devang Patelc049e4f2007-10-08 20:57:48 +0000560}
561
562void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
563 if (S.getRHS()) {
564 EmitCaseStmtRange(S);
565 return;
566 }
567
568 StartBlock("sw.bb");
569 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000570 llvm::APSInt CaseVal = S.getLHS()->getIntegerConstantExprValue(getContext());
571 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal),
572 CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000573 EmitStmt(S.getSubStmt());
574}
575
576void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000577 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
578 assert(DefaultBlock->empty() && "EmitDefaultStmt: Default block already defined?");
579 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000580 EmitStmt(S.getSubStmt());
581}
582
583void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
584 llvm::Value *CondV = EmitScalarExpr(S.getCond());
585
586 // Handle nested switch statements.
587 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000588 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000589
Daniel Dunbar16f23572008-07-25 01:11:38 +0000590 // Create basic block to hold stuff that comes after switch
591 // statement. We also need to create a default block now so that
592 // explicit case ranges tests can have a place to jump to on
593 // failure.
594 llvm::BasicBlock *NextBlock = llvm::BasicBlock::Create("sw.epilog");
595 llvm::BasicBlock *DefaultBlock = llvm::BasicBlock::Create("sw.default");
596 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
597 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000598
Eli Friedmand28a80d2008-05-12 16:08:04 +0000599 // Create basic block for body of switch
Daniel Dunbar16f23572008-07-25 01:11:38 +0000600 StartBlock("sw.body");
Eli Friedmand28a80d2008-05-12 16:08:04 +0000601
Devang Patele9b8c0a2007-10-30 20:59:40 +0000602 // All break statements jump to NextBlock. If BreakContinueStack is non empty
603 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000604 llvm::BasicBlock *ContinueBlock = NULL;
605 if (!BreakContinueStack.empty())
606 ContinueBlock = BreakContinueStack.back().ContinueBlock;
607 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
608
609 // Emit switch body.
610 EmitStmt(S.getBody());
611 BreakContinueStack.pop_back();
612
Daniel Dunbar16f23572008-07-25 01:11:38 +0000613 // Update the default block in case explicit case range tests have
614 // been chained on top.
615 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000616
Daniel Dunbar16f23572008-07-25 01:11:38 +0000617 // If a default was never emitted then reroute any jumps to it and
618 // discard.
619 if (!DefaultBlock->getParent()) {
620 DefaultBlock->replaceAllUsesWith(NextBlock);
621 delete DefaultBlock;
622 }
Devang Patel51b09f22007-10-04 23:45:31 +0000623
Daniel Dunbar16f23572008-07-25 01:11:38 +0000624 // Emit continuation.
625 EmitBlock(NextBlock);
626
Devang Patel51b09f22007-10-04 23:45:31 +0000627 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000628 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000629}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000630
Chris Lattner345f7202008-07-26 20:15:14 +0000631static std::string ConvertAsmString(const char *Start, unsigned NumOperands,
632 bool IsSimple) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000633 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000634 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000635 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000636 if (IsSimple) {
637 while (*Start) {
638 switch (*Start) {
639 default:
640 Result += *Start;
641 break;
642 case '$':
643 Result += "$$";
644 break;
645 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000646 Start++;
647 }
648
649 return Result;
650 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000651
652 while (*Start) {
653 switch (*Start) {
654 default:
655 Result += *Start;
656 break;
657 case '$':
658 Result += "$$";
659 break;
660 case '%':
661 // Escaped character
662 Start++;
663 if (!*Start) {
664 // FIXME: This should be caught during Sema.
665 assert(0 && "Trailing '%' in asm string.");
666 }
667
668 char EscapedChar = *Start;
669 if (EscapedChar == '%') {
670 // Escaped percentage sign.
671 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000672 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000673 // Generate an unique ID.
674 Result += llvm::utostr(AsmCounter);
675 } else if (isdigit(EscapedChar)) {
676 // %n - Assembler operand n
677 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000678 unsigned long n = strtoul(Start, &End, 10);
679 if (Start == End) {
680 // FIXME: This should be caught during Sema.
681 assert(0 && "Missing operand!");
682 } else if (n >= NumOperands) {
683 // FIXME: This should be caught during Sema.
684 assert(0 && "Operand number out of range!");
685 }
686
687 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000688 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000689 } else if (isalpha(EscapedChar)) {
690 char *End;
691
692 unsigned long n = strtoul(Start + 1, &End, 10);
693 if (Start == End) {
694 // FIXME: This should be caught during Sema.
695 assert(0 && "Missing operand!");
696 } else if (n >= NumOperands) {
697 // FIXME: This should be caught during Sema.
698 assert(0 && "Operand number out of range!");
699 }
700
701 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000702 Start = End - 1;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000703 } else {
704 assert(0 && "Unhandled asm escaped character!");
705 }
706 }
707 Start++;
708 }
709
710 return Result;
711}
712
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000713static std::string SimplifyConstraint(const char* Constraint,
714 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000715 std::string Result;
716
717 while (*Constraint) {
718 switch (*Constraint) {
719 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000720 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000721 break;
722 // Ignore these
723 case '*':
724 case '?':
725 case '!':
726 break;
727 case 'g':
728 Result += "imr";
729 break;
730 }
731
732 Constraint++;
733 }
734
735 return Result;
736}
737
738void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
739 std::string AsmString =
740 ConvertAsmString(std::string(S.getAsmString()->getStrData(),
741 S.getAsmString()->getByteLength()).c_str(),
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000742 S.getNumOutputs() + S.getNumInputs(), S.isSimple());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000743
744 std::string Constraints;
745
746 llvm::Value *ResultAddr = 0;
747 const llvm::Type *ResultType = llvm::Type::VoidTy;
748
749 std::vector<const llvm::Type*> ArgTypes;
750 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000751
752 // Keep track of inout constraints.
753 std::string InOutConstraints;
754 std::vector<llvm::Value*> InOutArgs;
755 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000756
757 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
758 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
759 S.getOutputConstraint(i)->getByteLength());
760
761 TargetInfo::ConstraintInfo Info;
762 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
763 Info);
764 assert(result && "Failed to parse output constraint");
765
766 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000767 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000768
769 LValue Dest = EmitLValue(S.getOutputExpr(i));
770 const llvm::Type *DestValueType =
771 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
772
773 // If the first output operand is not a memory dest, we'll
774 // make it the return value.
775 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000776 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000777 ResultAddr = Dest.getAddress();
778 ResultType = DestValueType;
779 Constraints += "=" + OutputConstraint;
780 } else {
781 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000782 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000783 if (i != 0)
784 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000785 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000786 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000787 }
788
789 if (Info & TargetInfo::CI_ReadWrite) {
790 // FIXME: This code should be shared with the code that handles inputs.
791 InOutConstraints += ',';
792
793 const Expr *InputExpr = S.getOutputExpr(i);
794 llvm::Value *Arg;
795 if ((Info & TargetInfo::CI_AllowsRegister) ||
796 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000797 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000798 Arg = EmitScalarExpr(InputExpr);
799 } else {
Daniel Dunbar662174c82008-08-29 17:28:43 +0000800 ErrorUnsupported(&S, "asm statement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000801 }
802 } else {
803 LValue Dest = EmitLValue(InputExpr);
804 Arg = Dest.getAddress();
805 InOutConstraints += '*';
806 }
807
808 InOutArgTypes.push_back(Arg->getType());
809 InOutArgs.push_back(Arg);
810 InOutConstraints += OutputConstraint;
811 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000812 }
813
814 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
815
816 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
817 const Expr *InputExpr = S.getInputExpr(i);
818
819 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
820 S.getInputConstraint(i)->getByteLength());
821
822 TargetInfo::ConstraintInfo Info;
823 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
824 NumConstraints,
825 Info);
826 assert(result && "Failed to parse input constraint");
827
828 if (i != 0 || S.getNumOutputs() > 0)
829 Constraints += ',';
830
831 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000832 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000833
834 llvm::Value *Arg;
835
836 if ((Info & TargetInfo::CI_AllowsRegister) ||
837 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000838 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000839 Arg = EmitScalarExpr(InputExpr);
840 } else {
Daniel Dunbar662174c82008-08-29 17:28:43 +0000841 ErrorUnsupported(&S, "asm statement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000842 }
843 } else {
844 LValue Dest = EmitLValue(InputExpr);
845 Arg = Dest.getAddress();
846 Constraints += '*';
847 }
848
849 ArgTypes.push_back(Arg->getType());
850 Args.push_back(Arg);
851 Constraints += InputConstraint;
852 }
853
Anders Carlssonf39a4212008-02-05 20:01:53 +0000854 // Append the "input" part of inout constraints last.
855 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
856 ArgTypes.push_back(InOutArgTypes[i]);
857 Args.push_back(InOutArgs[i]);
858 }
859 Constraints += InOutConstraints;
860
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000861 // Clobbers
862 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
863 std::string Clobber(S.getClobber(i)->getStrData(),
864 S.getClobber(i)->getByteLength());
865
866 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
867
Anders Carlssonea041752008-02-06 00:11:32 +0000868 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000869 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000870
871 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000872 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000873 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000874 }
875
876 // Add machine specific clobbers
877 if (const char *C = Target.getClobbers()) {
878 if (!Constraints.empty())
879 Constraints += ',';
880 Constraints += C;
881 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000882
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000883 const llvm::FunctionType *FTy =
884 llvm::FunctionType::get(ResultType, ArgTypes, false);
885
886 llvm::InlineAsm *IA =
887 llvm::InlineAsm::get(FTy, AsmString, Constraints,
888 S.isVolatile() || S.getNumOutputs() == 0);
889 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +0000890 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000891 Builder.CreateStore(Result, ResultAddr);
892}