blob: f2088f416d5f585cfd5b3243c56de2673e67de3b [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) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000152 // Fall out of the current block (if necessary).
153 EmitBranch(BB);
Reid Spencer5f016e22007-07-11 17:01:13 +0000154 CurFn->getBasicBlockList().push_back(BB);
155 Builder.SetInsertPoint(BB);
156}
157
Daniel Dunbard57a8712008-11-11 09:41:28 +0000158void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
159 // Emit a branch from the current block to the target one if this
160 // was a real block. If this was just a fall-through block after a
161 // terminator, don't emit it.
162 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
163
164 if (!CurBB || CurBB->getTerminator()) {
165 // If there is no insert point or the previous block is already
166 // terminated, don't touch it.
167 } else if (isDummyBlock(CurBB)) {
168 // If the last block was an empty placeholder, remove it now.
169 // TODO: cache and reuse these.
170 CurBB->eraseFromParent();
171 Builder.ClearInsertionPoint();
172 } else {
173 // Otherwise, create a fall-through branch.
174 Builder.CreateBr(Target);
175 }
176}
177
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000178void CodeGenFunction::EmitDummyBlock() {
179 EmitBlock(createBasicBlock());
180}
181
Chris Lattner91d723d2008-07-26 20:23:23 +0000182void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000184 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000185}
186
187
188void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
189 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 EmitStmt(S.getSubStmt());
191}
192
193void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000194 // FIXME: Implement goto out in @try or @catch blocks.
195 if (!ObjCEHStack.empty()) {
196 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
197 return;
198 }
199
Daniel Dunbard57a8712008-11-11 09:41:28 +0000200 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000201
202 // Emit a block after the branch so that dead code after a goto has some place
203 // to go.
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000204 EmitDummyBlock();
Reid Spencer5f016e22007-07-11 17:01:13 +0000205}
206
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000207void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000208 // FIXME: Implement indirect goto in @try or @catch blocks.
209 if (!ObjCEHStack.empty()) {
210 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
211 return;
212 }
213
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000214 // Emit initial switch which will be patched up later by
215 // EmitIndirectSwitches(). We need a default dest, so we use the
216 // current BB, but this is overwritten.
217 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
218 llvm::Type::Int32Ty,
219 "addr");
220 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
221 IndirectSwitches.push_back(I);
222
223 // Emit a block after the branch so that dead code after a goto has some place
224 // to go.
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000225 EmitDummyBlock();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000226}
227
Chris Lattner62b72f62008-11-11 07:24:28 +0000228void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000229 // C99 6.8.4.1: The first substatement is executed if the expression compares
230 // unequal to 0. The condition must be a scalar type.
231 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
232
Chris Lattner62b72f62008-11-11 07:24:28 +0000233 // If we constant folded the condition to true or false, try to avoid emitting
234 // the dead arm at all.
235 if (llvm::ConstantInt *CondCst = dyn_cast<llvm::ConstantInt>(BoolCondVal)) {
236 // Figure out which block (then or else) is executed.
237 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
238 if (!CondCst->getZExtValue())
239 std::swap(Executed, Skipped);
240
241 // If the skipped block has no labels in it, just emit the executed block.
242 // This avoids emitting dead code and simplifies the CFG substantially.
243 if (Skipped == 0 || !ContainsLabel(Skipped)) {
244 if (Executed)
245 EmitStmt(Executed);
246 return;
247 }
248 }
249
Daniel Dunbar55e87422008-11-11 02:29:29 +0000250 llvm::BasicBlock *ContBlock = createBasicBlock("ifend");
251 llvm::BasicBlock *ThenBlock = createBasicBlock("ifthen");
Reid Spencer5f016e22007-07-11 17:01:13 +0000252 llvm::BasicBlock *ElseBlock = ContBlock;
253
254 if (S.getElse())
Daniel Dunbar55e87422008-11-11 02:29:29 +0000255 ElseBlock = createBasicBlock("ifelse");
Reid Spencer5f016e22007-07-11 17:01:13 +0000256
257 // Insert the conditional branch.
258 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
259
260 // Emit the 'then' code.
261 EmitBlock(ThenBlock);
262 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000263 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000264
265 // Emit the 'else' code if present.
266 if (const Stmt *Else = S.getElse()) {
267 EmitBlock(ElseBlock);
268 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000269 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000270 }
271
272 // Emit the continuation block for code after the if.
273 EmitBlock(ContBlock);
274}
275
276void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 // Emit the header for the loop, insert it, which will create an uncond br to
278 // it.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000279 llvm::BasicBlock *LoopHeader = createBasicBlock("whilecond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000280 EmitBlock(LoopHeader);
281
282 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
283 // of the controlling expression takes place before each execution of the loop
284 // body.
285 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000286
287 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000288 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000289 bool EmitBoolCondBranch = true;
290 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
291 if (C->isOne())
292 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000293
294 // Create an exit block for when the condition fails, create a block for the
295 // body of the loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000296 llvm::BasicBlock *ExitBlock = createBasicBlock("whileexit");
297 llvm::BasicBlock *LoopBody = createBasicBlock("whilebody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000298
299 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000300 if (EmitBoolCondBranch)
301 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000302
303 // Store the blocks to use for break and continue.
304 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000305
306 // Emit the loop body.
307 EmitBlock(LoopBody);
308 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000309
310 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000311
312 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000313 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000314
315 // Emit the exit block.
316 EmitBlock(ExitBlock);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000317
318 // If LoopHeader is a simple forwarding block then eliminate it.
319 if (!EmitBoolCondBranch
320 && &LoopHeader->front() == LoopHeader->getTerminator()) {
321 LoopHeader->replaceAllUsesWith(LoopBody);
322 LoopHeader->getTerminator()->eraseFromParent();
323 LoopHeader->eraseFromParent();
324 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000325}
326
327void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000328 // Emit the body for the loop, insert it, which will create an uncond br to
329 // it.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000330 llvm::BasicBlock *LoopBody = createBasicBlock("dobody");
331 llvm::BasicBlock *AfterDo = createBasicBlock("afterdo");
Reid Spencer5f016e22007-07-11 17:01:13 +0000332 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000333
Daniel Dunbar55e87422008-11-11 02:29:29 +0000334 llvm::BasicBlock *DoCond = createBasicBlock("docond");
Chris Lattnerda138702007-07-16 21:28:45 +0000335
336 // Store the blocks to use for break and continue.
337 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000338
339 // Emit the body of the loop into the block.
340 EmitStmt(S.getBody());
341
Chris Lattnerda138702007-07-16 21:28:45 +0000342 BreakContinueStack.pop_back();
343
344 EmitBlock(DoCond);
345
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
347 // after each execution of the loop body."
348
349 // Evaluate the conditional in the while header.
350 // C99 6.8.5p2/p4: The first substatement is executed if the expression
351 // compares unequal to 0. The condition must be a scalar type.
352 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000353
354 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
355 // to correctly handle break/continue though.
356 bool EmitBoolCondBranch = true;
357 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
358 if (C->isZero())
359 EmitBoolCondBranch = false;
360
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000362 if (EmitBoolCondBranch)
363 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000364
365 // Emit the exit block.
366 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000367
368 // If DoCond is a simple forwarding block then eliminate it.
369 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
370 DoCond->replaceAllUsesWith(AfterDo);
371 DoCond->getTerminator()->eraseFromParent();
372 DoCond->eraseFromParent();
373 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000374}
375
376void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000377 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
378 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000379 // TODO: We could keep track of whether the loop body contains any
380 // break/continue statements and not create unnecessary blocks (like
381 // "afterfor" for a condless loop) if it doesn't.
382
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 // Evaluate the first part before the loop.
384 if (S.getInit())
385 EmitStmt(S.getInit());
386
387 // Start the loop with a block that tests the condition.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000388 llvm::BasicBlock *CondBlock = createBasicBlock("forcond");
389 llvm::BasicBlock *AfterFor = createBasicBlock("afterfor");
Chris Lattnerda138702007-07-16 21:28:45 +0000390
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 EmitBlock(CondBlock);
392
393 // Evaluate the condition if present. If not, treat it as a non-zero-constant
394 // according to 6.8.5.3p2, aka, true.
395 if (S.getCond()) {
396 // C99 6.8.5p2/p4: The first substatement is executed if the expression
397 // compares unequal to 0. The condition must be a scalar type.
398 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
399
400 // As long as the condition is true, iterate the loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000401 llvm::BasicBlock *ForBody = createBasicBlock("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
403 EmitBlock(ForBody);
404 } else {
405 // Treat it as a non-zero constant. Don't even create a new block for the
406 // body, just fall into it.
407 }
408
Chris Lattnerda138702007-07-16 21:28:45 +0000409 // If the for loop doesn't have an increment we can just use the
410 // condition as the continue block.
411 llvm::BasicBlock *ContinueBlock;
412 if (S.getInc())
Daniel Dunbar55e87422008-11-11 02:29:29 +0000413 ContinueBlock = createBasicBlock("forinc");
Chris Lattnerda138702007-07-16 21:28:45 +0000414 else
415 ContinueBlock = CondBlock;
416
417 // Store the blocks to use for break and continue.
418 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
419
Reid Spencer5f016e22007-07-11 17:01:13 +0000420 // If the condition is true, execute the body of the for stmt.
421 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000422
423 BreakContinueStack.pop_back();
424
Reid Spencer5f016e22007-07-11 17:01:13 +0000425 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000426 if (S.getInc()) {
427 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000428 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000429 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000430
431 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000432 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000433
Chris Lattnerda138702007-07-16 21:28:45 +0000434 // Emit the fall-through block.
435 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000436}
437
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000438void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
439 if (RV.isScalar()) {
440 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
441 } else if (RV.isAggregate()) {
442 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
443 } else {
444 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
445 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000446 EmitBranch(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000447
448 // Emit a block after the branch so that dead code after a return has some
449 // place to go.
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000450 EmitDummyBlock();
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000451}
452
Reid Spencer5f016e22007-07-11 17:01:13 +0000453/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
454/// if the function returns void, or may be missing one if the function returns
455/// non-void. Fun stuff :).
456void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000457 // Emit the result value, even if unused, to evalute the side effects.
458 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000459
460 // FIXME: Clean this up by using an LValue for ReturnTemp,
461 // EmitStoreThroughLValue, and EmitAnyExpr.
462 if (!ReturnValue) {
463 // Make sure not to return anything, but evaluate the expression
464 // for side effects.
465 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000466 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000468 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000469 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000470 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000471 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000472 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000473 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000474 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000475 }
Eli Friedman144ac612008-05-22 01:22:33 +0000476
Daniel Dunbar898d5082008-09-30 01:06:03 +0000477 if (!ObjCEHStack.empty()) {
478 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
479 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000480 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000481 EmitJumpThroughFinally(*i, ReturnPad);
482 EmitBlock(ReturnPad);
483 }
484 }
485
Daniel Dunbard57a8712008-11-11 09:41:28 +0000486 EmitBranch(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000487
488 // Emit a block after the branch so that dead code after a return has some
489 // place to go.
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000490 EmitDummyBlock();
Reid Spencer5f016e22007-07-11 17:01:13 +0000491}
492
493void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000494 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
495 I != E; ++I)
496 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000497}
Chris Lattnerda138702007-07-16 21:28:45 +0000498
499void CodeGenFunction::EmitBreakStmt() {
500 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
501
502 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000503 EmitBranch(Block);
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000504 EmitDummyBlock();
Chris Lattnerda138702007-07-16 21:28:45 +0000505}
506
507void CodeGenFunction::EmitContinueStmt() {
508 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
509
510 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000511 EmitBranch(Block);
Daniel Dunbar824e3bd2008-11-11 04:34:23 +0000512 EmitDummyBlock();
Chris Lattnerda138702007-07-16 21:28:45 +0000513}
Devang Patel51b09f22007-10-04 23:45:31 +0000514
Devang Patelc049e4f2007-10-08 20:57:48 +0000515/// EmitCaseStmtRange - If case statement range is not too big then
516/// add multiple cases to switch instruction, one for each value within
517/// the range. If range is too big then emit "if" condition check.
518void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000519 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000520
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000521 llvm::APSInt LHS = S.getLHS()->getIntegerConstantExprValue(getContext());
522 llvm::APSInt RHS = S.getRHS()->getIntegerConstantExprValue(getContext());
523
Daniel Dunbar16f23572008-07-25 01:11:38 +0000524 // Emit the code for this case. We do this first to make sure it is
525 // properly chained from our predecessor before generating the
526 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000527 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000528 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
529 EmitStmt(S.getSubStmt());
530
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000531 // If range is empty, do nothing.
532 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
533 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000534
535 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000536 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000537 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
538 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000539 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000540 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
541 LHS++;
542 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000543 return;
544 }
545
Daniel Dunbar16f23572008-07-25 01:11:38 +0000546 // The range is too big. Emit "if" condition into a new block,
547 // making sure to save and restore the current insertion point.
548 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000549
Daniel Dunbar16f23572008-07-25 01:11:38 +0000550 // Push this test onto the chain of range checks (which terminates
551 // in the default basic block). The switch's default will be changed
552 // to the top of this chain after switch emission is complete.
553 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000554 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000555
Daniel Dunbar16f23572008-07-25 01:11:38 +0000556 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
557 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000558
559 // Emit range check.
560 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000561 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
562 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000563 llvm::Value *Cond =
564 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
565 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
566
Daniel Dunbar16f23572008-07-25 01:11:38 +0000567 // Restore the appropriate insertion point.
568 Builder.SetInsertPoint(RestoreBB);
Devang Patelc049e4f2007-10-08 20:57:48 +0000569}
570
571void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
572 if (S.getRHS()) {
573 EmitCaseStmtRange(S);
574 return;
575 }
576
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000577 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000578 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000579 llvm::APSInt CaseVal = S.getLHS()->getIntegerConstantExprValue(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000580 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000581 EmitStmt(S.getSubStmt());
582}
583
584void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000585 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000586 assert(DefaultBlock->empty() &&
587 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000588 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000589 EmitStmt(S.getSubStmt());
590}
591
592void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
593 llvm::Value *CondV = EmitScalarExpr(S.getCond());
594
595 // Handle nested switch statements.
596 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000597 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000598
Daniel Dunbar16f23572008-07-25 01:11:38 +0000599 // Create basic block to hold stuff that comes after switch
600 // statement. We also need to create a default block now so that
601 // explicit case ranges tests can have a place to jump to on
602 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000603 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
604 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000605 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
606 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000607
Eli Friedmand28a80d2008-05-12 16:08:04 +0000608 // Create basic block for body of switch
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000609 EmitBlock(createBasicBlock("sw.body"));
Eli Friedmand28a80d2008-05-12 16:08:04 +0000610
Devang Patele9b8c0a2007-10-30 20:59:40 +0000611 // All break statements jump to NextBlock. If BreakContinueStack is non empty
612 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000613 llvm::BasicBlock *ContinueBlock = NULL;
614 if (!BreakContinueStack.empty())
615 ContinueBlock = BreakContinueStack.back().ContinueBlock;
616 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
617
618 // Emit switch body.
619 EmitStmt(S.getBody());
620 BreakContinueStack.pop_back();
621
Daniel Dunbar16f23572008-07-25 01:11:38 +0000622 // Update the default block in case explicit case range tests have
623 // been chained on top.
624 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000625
Daniel Dunbar16f23572008-07-25 01:11:38 +0000626 // If a default was never emitted then reroute any jumps to it and
627 // discard.
628 if (!DefaultBlock->getParent()) {
629 DefaultBlock->replaceAllUsesWith(NextBlock);
630 delete DefaultBlock;
631 }
Devang Patel51b09f22007-10-04 23:45:31 +0000632
Daniel Dunbar16f23572008-07-25 01:11:38 +0000633 // Emit continuation.
634 EmitBlock(NextBlock);
635
Devang Patel51b09f22007-10-04 23:45:31 +0000636 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000637 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000638}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000639
Anders Carlssonce179ab2008-11-09 18:54:14 +0000640static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
641{
642 // FIXME: No need to create new std::string here, we could just make sure
643 // that we don't read past the end of the string data.
644 std::string str(S.getAsmString()->getStrData(),
645 S.getAsmString()->getByteLength());
646 const char *Start = str.c_str();
647
648 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
649 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000650 Failed = false;
651
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000652 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000653 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000654 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000655 if (IsSimple) {
656 while (*Start) {
657 switch (*Start) {
658 default:
659 Result += *Start;
660 break;
661 case '$':
662 Result += "$$";
663 break;
664 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000665 Start++;
666 }
667
668 return Result;
669 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000670
671 while (*Start) {
672 switch (*Start) {
673 default:
674 Result += *Start;
675 break;
676 case '$':
677 Result += "$$";
678 break;
679 case '%':
680 // Escaped character
681 Start++;
682 if (!*Start) {
683 // FIXME: This should be caught during Sema.
684 assert(0 && "Trailing '%' in asm string.");
685 }
686
687 char EscapedChar = *Start;
688 if (EscapedChar == '%') {
689 // Escaped percentage sign.
690 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000691 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000692 // Generate an unique ID.
693 Result += llvm::utostr(AsmCounter);
694 } else if (isdigit(EscapedChar)) {
695 // %n - Assembler operand n
696 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000697 unsigned long n = strtoul(Start, &End, 10);
698 if (Start == End) {
699 // FIXME: This should be caught during Sema.
700 assert(0 && "Missing operand!");
701 } else if (n >= NumOperands) {
702 // FIXME: This should be caught during Sema.
703 assert(0 && "Operand number out of range!");
704 }
705
706 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000707 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000708 } else if (isalpha(EscapedChar)) {
709 char *End;
710
711 unsigned long n = strtoul(Start + 1, &End, 10);
712 if (Start == End) {
713 // FIXME: This should be caught during Sema.
714 assert(0 && "Missing operand!");
715 } else if (n >= NumOperands) {
716 // FIXME: This should be caught during Sema.
717 assert(0 && "Operand number out of range!");
718 }
719
720 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000721 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000722 } else if (EscapedChar == '[') {
723 std::string SymbolicName;
724
725 Start++;
726
727 while (*Start && *Start != ']') {
728 SymbolicName += *Start;
729
730 Start++;
731 }
732
733 if (!Start) {
734 // FIXME: Should be caught by sema.
735 assert(0 && "Could not parse symbolic name");
736 }
737
738 assert(*Start == ']' && "Error parsing symbolic name");
739
740 int Index = -1;
741
742 // Check if this is an output operand.
743 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
744 if (S.getOutputName(i) == SymbolicName) {
745 Index = i;
746 break;
747 }
748 }
749
750 if (Index == -1) {
751 for (unsigned i = 0; i < S.getNumInputs(); i++) {
752 if (S.getInputName(i) == SymbolicName) {
753 Index = S.getNumOutputs() + i;
754 }
755 }
756 }
757
758 assert(Index != -1 && "Did not find right operand!");
759
760 Result += '$' + llvm::utostr(Index);
761
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000762 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000763 Failed = true;
764 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000765 }
766 }
767 Start++;
768 }
769
770 return Result;
771}
772
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000773static std::string SimplifyConstraint(const char* Constraint,
774 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000775 std::string Result;
776
777 while (*Constraint) {
778 switch (*Constraint) {
779 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000780 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000781 break;
782 // Ignore these
783 case '*':
784 case '?':
785 case '!':
786 break;
787 case 'g':
788 Result += "imr";
789 break;
790 }
791
792 Constraint++;
793 }
794
795 return Result;
796}
797
798void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000799 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000800 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000801 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000802
803 if (Failed) {
804 ErrorUnsupported(&S, "asm string");
805 return;
806 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000807
808 std::string Constraints;
809
810 llvm::Value *ResultAddr = 0;
811 const llvm::Type *ResultType = llvm::Type::VoidTy;
812
813 std::vector<const llvm::Type*> ArgTypes;
814 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000815
816 // Keep track of inout constraints.
817 std::string InOutConstraints;
818 std::vector<llvm::Value*> InOutArgs;
819 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000820
821 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
822 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
823 S.getOutputConstraint(i)->getByteLength());
824
825 TargetInfo::ConstraintInfo Info;
826 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
827 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000828 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000829
830 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000831 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000832
833 LValue Dest = EmitLValue(S.getOutputExpr(i));
834 const llvm::Type *DestValueType =
835 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
836
837 // If the first output operand is not a memory dest, we'll
838 // make it the return value.
839 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000840 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000841 ResultAddr = Dest.getAddress();
842 ResultType = DestValueType;
843 Constraints += "=" + OutputConstraint;
844 } else {
845 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000846 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000847 if (i != 0)
848 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000849 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000850 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000851 }
852
853 if (Info & TargetInfo::CI_ReadWrite) {
854 // FIXME: This code should be shared with the code that handles inputs.
855 InOutConstraints += ',';
856
857 const Expr *InputExpr = S.getOutputExpr(i);
858 llvm::Value *Arg;
859 if ((Info & TargetInfo::CI_AllowsRegister) ||
860 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000861 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000862 Arg = EmitScalarExpr(InputExpr);
863 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000864 ErrorUnsupported(&S,
865 "asm statement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000866 }
867 } else {
868 LValue Dest = EmitLValue(InputExpr);
869 Arg = Dest.getAddress();
870 InOutConstraints += '*';
871 }
872
873 InOutArgTypes.push_back(Arg->getType());
874 InOutArgs.push_back(Arg);
875 InOutConstraints += OutputConstraint;
876 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000877 }
878
879 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
880
881 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
882 const Expr *InputExpr = S.getInputExpr(i);
883
884 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
885 S.getInputConstraint(i)->getByteLength());
886
887 TargetInfo::ConstraintInfo Info;
888 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Chris Lattner3304e552008-10-12 00:31:50 +0000889 NumConstraints, Info);
890 assert(result && "Failed to parse input constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000891
892 if (i != 0 || S.getNumOutputs() > 0)
893 Constraints += ',';
894
895 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000896 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000897
898 llvm::Value *Arg;
899
900 if ((Info & TargetInfo::CI_AllowsRegister) ||
901 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000902 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000903 Arg = EmitScalarExpr(InputExpr);
904 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000905 ErrorUnsupported(&S,
906 "asm statement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000907 }
908 } else {
909 LValue Dest = EmitLValue(InputExpr);
910 Arg = Dest.getAddress();
911 Constraints += '*';
912 }
913
914 ArgTypes.push_back(Arg->getType());
915 Args.push_back(Arg);
916 Constraints += InputConstraint;
917 }
918
Anders Carlssonf39a4212008-02-05 20:01:53 +0000919 // Append the "input" part of inout constraints last.
920 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
921 ArgTypes.push_back(InOutArgTypes[i]);
922 Args.push_back(InOutArgs[i]);
923 }
924 Constraints += InOutConstraints;
925
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000926 // Clobbers
927 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
928 std::string Clobber(S.getClobber(i)->getStrData(),
929 S.getClobber(i)->getByteLength());
930
931 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
932
Anders Carlssonea041752008-02-06 00:11:32 +0000933 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000934 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000935
936 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000937 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000938 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000939 }
940
941 // Add machine specific clobbers
942 if (const char *C = Target.getClobbers()) {
943 if (!Constraints.empty())
944 Constraints += ',';
945 Constraints += C;
946 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000947
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000948 const llvm::FunctionType *FTy =
949 llvm::FunctionType::get(ResultType, ArgTypes, false);
950
951 llvm::InlineAsm *IA =
952 llvm::InlineAsm::get(FTy, AsmString, Constraints,
953 S.isVolatile() || S.getNumOutputs() == 0);
954 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +0000955 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000956 Builder.CreateStore(Result, ResultAddr);
957}