blob: 25c8fd94931c5e8889d2dfec97955c8446f25fb9 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Stmt nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
15#include "CodeGenModule.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "CodeGenFunction.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000017#include "clang/AST/StmtVisitor.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000018#include "clang/Basic/TargetInfo.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000019#include "llvm/InlineAsm.h"
20#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021using namespace clang;
22using namespace CodeGen;
23
24//===----------------------------------------------------------------------===//
25// Statement Emission
26//===----------------------------------------------------------------------===//
27
Daniel Dunbar09124252008-11-12 08:21:33 +000028void CodeGenFunction::EmitStopPoint(const Stmt *S) {
29 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
30 DI->setLocation(S->getLocStart());
31 DI->EmitStopPoint(CurFn, Builder);
32 }
33}
34
Reid Spencer5f016e22007-07-11 17:01:13 +000035void CodeGenFunction::EmitStmt(const Stmt *S) {
36 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000037
Daniel Dunbar09124252008-11-12 08:21:33 +000038 // Check if we can handle this without bothering to generate an
39 // insert point or debug info.
40 if (EmitSimpleStmt(S))
41 return;
42
Daniel Dunbara448fb22008-11-11 23:11:34 +000043 // If we happen to be at an unreachable point just create a dummy
44 // basic block to hold the code. We could change parts of irgen to
45 // simply not generate this code, but this situation is rare and
46 // probably not worth the effort.
47 // FIXME: Verify previous performance/effort claim.
48 EnsureInsertPoint();
Reid Spencer5f016e22007-07-11 17:01:13 +000049
Daniel Dunbar09124252008-11-12 08:21:33 +000050 // Generate a stoppoint if we are emitting debug info.
51 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000052
Reid Spencer5f016e22007-07-11 17:01:13 +000053 switch (S->getStmtClass()) {
54 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000055 // Must be an expression in a stmt context. Emit the value (to get
56 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000057 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000058 if (!hasAggregateLLVMType(E->getType()))
59 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000060 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000061 EmitComplexExpr(E);
62 else
63 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000064 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000065 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000066 }
67 break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000068 case Stmt::IndirectGotoStmtClass:
69 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000070
71 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
72 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
73 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
74 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
75
76 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
77 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +000078
Devang Patel51b09f22007-10-04 23:45:31 +000079 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000080 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000081
82 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000083 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
84 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000085 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +000086 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
87 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000088 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000089 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +000090 break;
91 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000092 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000093 break;
94 case Stmt::ObjCAtSynchronizedStmtClass:
95 ErrorUnsupported(S, "@synchronized statement");
96 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +000097 case Stmt::ObjCForCollectionStmtClass:
98 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000099 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000100 }
101}
102
Daniel Dunbar09124252008-11-12 08:21:33 +0000103bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
104 switch (S->getStmtClass()) {
105 default: return false;
106 case Stmt::NullStmtClass: break;
107 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
108 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
109 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
110 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
111 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
112 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
113 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
114 }
115
116 return true;
117}
118
Chris Lattner33793202007-08-31 22:09:40 +0000119/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
120/// this captures the expression result of the last sub-statement and returns it
121/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000122RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
123 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000124 // FIXME: handle vla's etc.
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000125 CGDebugInfo *DI = CGM.getDebugInfo();
126 if (DI) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000127 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000128 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000129 DI->EmitRegionStart(CurFn, Builder);
130 }
131
Chris Lattner33793202007-08-31 22:09:40 +0000132 for (CompoundStmt::const_body_iterator I = S.body_begin(),
133 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000134 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000135
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000136 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000137 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000138 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000139 DI->EmitRegionEnd(CurFn, Builder);
140 }
141
Chris Lattner33793202007-08-31 22:09:40 +0000142 if (!GetLast)
143 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +0000144
Chris Lattner91d723d2008-07-26 20:23:23 +0000145 // We have to special case labels here. They are statements, but when put at
146 // the end of a statement expression, they yield the value of their
147 // subexpression. Handle this by walking through all labels we encounter,
148 // emitting them before we evaluate the subexpr.
149 const Stmt *LastStmt = S.body_back();
150 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
151 EmitLabel(*LS);
152 LastStmt = LS->getSubStmt();
153 }
154
Daniel Dunbara448fb22008-11-11 23:11:34 +0000155 EnsureInsertPoint();
156
Chris Lattner91d723d2008-07-26 20:23:23 +0000157 return EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000158}
159
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000160void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000161 // Fall out of the current block (if necessary).
162 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000163
164 if (IsFinished && BB->use_empty()) {
165 delete BB;
166 return;
167 }
168
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 CurFn->getBasicBlockList().push_back(BB);
170 Builder.SetInsertPoint(BB);
171}
172
Daniel Dunbard57a8712008-11-11 09:41:28 +0000173void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
174 // Emit a branch from the current block to the target one if this
175 // was a real block. If this was just a fall-through block after a
176 // terminator, don't emit it.
177 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
178
179 if (!CurBB || CurBB->getTerminator()) {
180 // If there is no insert point or the previous block is already
181 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000182 } else {
183 // Otherwise, create a fall-through branch.
184 Builder.CreateBr(Target);
185 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000186
187 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000188}
189
Chris Lattner91d723d2008-07-26 20:23:23 +0000190void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000193}
194
195
196void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
197 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 EmitStmt(S.getSubStmt());
199}
200
201void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000202 // FIXME: Implement goto out in @try or @catch blocks.
203 if (!ObjCEHStack.empty()) {
204 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
205 return;
206 }
207
Daniel Dunbar09124252008-11-12 08:21:33 +0000208 // If this code is reachable then emit a stop point (if generating
209 // debug info). We have to do this ourselves because we are on the
210 // "simple" statement path.
211 if (HaveInsertPoint())
212 EmitStopPoint(&S);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000213 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000214}
215
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000216void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000217 // FIXME: Implement indirect goto in @try or @catch blocks.
218 if (!ObjCEHStack.empty()) {
219 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
220 return;
221 }
222
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000223 // Emit initial switch which will be patched up later by
224 // EmitIndirectSwitches(). We need a default dest, so we use the
225 // current BB, but this is overwritten.
226 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
227 llvm::Type::Int32Ty,
228 "addr");
229 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
230 IndirectSwitches.push_back(I);
231
Daniel Dunbara448fb22008-11-11 23:11:34 +0000232 // Clear the insertion point to indicate we are in unreachable code.
233 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000234}
235
Chris Lattner62b72f62008-11-11 07:24:28 +0000236void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 // C99 6.8.4.1: The first substatement is executed if the expression compares
238 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000239
Chris Lattner9bc47e22008-11-12 07:46:33 +0000240 // If the condition constant folds and can be elided, try to avoid emitting
241 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000242 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000243 // Figure out which block (then or else) is executed.
244 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000245 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000246 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000247
Chris Lattner62b72f62008-11-11 07:24:28 +0000248 // If the skipped block has no labels in it, just emit the executed block.
249 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000250 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000251 if (Executed)
252 EmitStmt(Executed);
253 return;
254 }
255 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000256
257 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
258 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000259 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
260 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
261 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000262 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000263 ElseBlock = createBasicBlock("if.else");
264 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000265
266 // Emit the 'then' code.
267 EmitBlock(ThenBlock);
268 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000269 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000270
271 // Emit the 'else' code if present.
272 if (const Stmt *Else = S.getElse()) {
273 EmitBlock(ElseBlock);
274 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000275 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 }
277
278 // Emit the continuation block for code after the if.
279 EmitBlock(ContBlock);
280}
281
282void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000283 // Emit the header for the loop, insert it, which will create an uncond br to
284 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000285 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000286 EmitBlock(LoopHeader);
287
288 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
289 // of the controlling expression takes place before each execution of the loop
290 // body.
291 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000292
293 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000294 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000295 bool EmitBoolCondBranch = true;
296 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
297 if (C->isOne())
298 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000299
300 // Create an exit block for when the condition fails, create a block for the
301 // body of the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000302 llvm::BasicBlock *ExitBlock = createBasicBlock("while.exit");
303 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
Reid Spencer5f016e22007-07-11 17:01:13 +0000304
305 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000306 if (EmitBoolCondBranch)
307 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000308
Chris Lattnerda138702007-07-16 21:28:45 +0000309 // Store the blocks to use for break and continue.
310 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000311
312 // Emit the loop body.
313 EmitBlock(LoopBody);
314 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000315
316 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000317
318 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000319 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000320
321 // Emit the exit block.
322 EmitBlock(ExitBlock);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000323
324 // If LoopHeader is a simple forwarding block then eliminate it.
325 if (!EmitBoolCondBranch
326 && &LoopHeader->front() == LoopHeader->getTerminator()) {
327 LoopHeader->replaceAllUsesWith(LoopBody);
328 LoopHeader->getTerminator()->eraseFromParent();
329 LoopHeader->eraseFromParent();
330 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000331}
332
333void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 // Emit the body for the loop, insert it, which will create an uncond br to
335 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000336 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
337 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000339
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000340 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattnerda138702007-07-16 21:28:45 +0000341
342 // Store the blocks to use for break and continue.
343 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000344
345 // Emit the body of the loop into the block.
346 EmitStmt(S.getBody());
347
Chris Lattnerda138702007-07-16 21:28:45 +0000348 BreakContinueStack.pop_back();
349
350 EmitBlock(DoCond);
351
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
353 // after each execution of the loop body."
354
355 // Evaluate the conditional in the while header.
356 // C99 6.8.5p2/p4: The first substatement is executed if the expression
357 // compares unequal to 0. The condition must be a scalar type.
358 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000359
360 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
361 // to correctly handle break/continue though.
362 bool EmitBoolCondBranch = true;
363 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
364 if (C->isZero())
365 EmitBoolCondBranch = false;
366
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000368 if (EmitBoolCondBranch)
369 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000370
371 // Emit the exit block.
372 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000373
374 // If DoCond is a simple forwarding block then eliminate it.
375 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
376 DoCond->replaceAllUsesWith(AfterDo);
377 DoCond->getTerminator()->eraseFromParent();
378 DoCond->eraseFromParent();
379 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000380}
381
382void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
384 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000385 // TODO: We could keep track of whether the loop body contains any
386 // break/continue statements and not create unnecessary blocks (like
387 // "afterfor" for a condless loop) if it doesn't.
388
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 // Evaluate the first part before the loop.
390 if (S.getInit())
391 EmitStmt(S.getInit());
392
393 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000394 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
395 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattnerda138702007-07-16 21:28:45 +0000396
Reid Spencer5f016e22007-07-11 17:01:13 +0000397 EmitBlock(CondBlock);
398
399 // Evaluate the condition if present. If not, treat it as a non-zero-constant
400 // according to 6.8.5.3p2, aka, true.
401 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000403 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner31a09842008-11-12 08:04:58 +0000404
405 // C99 6.8.5p2/p4: The first substatement is executed if the expression
406 // compares unequal to 0. The condition must be a scalar type.
407 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
408
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 EmitBlock(ForBody);
410 } else {
411 // Treat it as a non-zero constant. Don't even create a new block for the
412 // body, just fall into it.
413 }
414
Chris Lattnerda138702007-07-16 21:28:45 +0000415 // If the for loop doesn't have an increment we can just use the
416 // condition as the continue block.
417 llvm::BasicBlock *ContinueBlock;
418 if (S.getInc())
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000419 ContinueBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000420 else
421 ContinueBlock = CondBlock;
422
423 // Store the blocks to use for break and continue.
424 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
425
Reid Spencer5f016e22007-07-11 17:01:13 +0000426 // If the condition is true, execute the body of the for stmt.
427 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000428
429 BreakContinueStack.pop_back();
430
Reid Spencer5f016e22007-07-11 17:01:13 +0000431 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000432 if (S.getInc()) {
433 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000434 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000435 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000436
437 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000438 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000439
Chris Lattnerda138702007-07-16 21:28:45 +0000440 // Emit the fall-through block.
441 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000442}
443
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000444void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
445 if (RV.isScalar()) {
446 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
447 } else if (RV.isAggregate()) {
448 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
449 } else {
450 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
451 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000452 EmitBranch(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000453}
454
Reid Spencer5f016e22007-07-11 17:01:13 +0000455/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
456/// if the function returns void, or may be missing one if the function returns
457/// non-void. Fun stuff :).
458void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000459 // Emit the result value, even if unused, to evalute the side effects.
460 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000461
462 // FIXME: Clean this up by using an LValue for ReturnTemp,
463 // EmitStoreThroughLValue, and EmitAnyExpr.
464 if (!ReturnValue) {
465 // Make sure not to return anything, but evaluate the expression
466 // for side effects.
467 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000468 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000469 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000470 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000471 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000472 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000473 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000474 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000475 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000476 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000477 }
Eli Friedman144ac612008-05-22 01:22:33 +0000478
Daniel Dunbar898d5082008-09-30 01:06:03 +0000479 if (!ObjCEHStack.empty()) {
480 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
481 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000482 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000483 EmitJumpThroughFinally(*i, ReturnPad);
484 EmitBlock(ReturnPad);
485 }
486 }
487
Daniel Dunbard57a8712008-11-11 09:41:28 +0000488 EmitBranch(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000489}
490
491void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000492 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
493 I != E; ++I)
494 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000495}
Chris Lattnerda138702007-07-16 21:28:45 +0000496
Daniel Dunbar09124252008-11-12 08:21:33 +0000497void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000498 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
499
Daniel Dunbar09124252008-11-12 08:21:33 +0000500 // FIXME: Implement break in @try or @catch blocks.
501 if (!ObjCEHStack.empty()) {
502 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
503 return;
504 }
505
506 // If this code is reachable then emit a stop point (if generating
507 // debug info). We have to do this ourselves because we are on the
508 // "simple" statement path.
509 if (HaveInsertPoint())
510 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000511 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000512 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000513}
514
Daniel Dunbar09124252008-11-12 08:21:33 +0000515void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000516 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
517
Daniel Dunbar09124252008-11-12 08:21:33 +0000518 // FIXME: Implement continue in @try or @catch blocks.
519 if (!ObjCEHStack.empty()) {
520 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
521 return;
522 }
523
524 // If this code is reachable then emit a stop point (if generating
525 // debug info). We have to do this ourselves because we are on the
526 // "simple" statement path.
527 if (HaveInsertPoint())
528 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000529 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000530 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000531}
Devang Patel51b09f22007-10-04 23:45:31 +0000532
Devang Patelc049e4f2007-10-08 20:57:48 +0000533/// EmitCaseStmtRange - If case statement range is not too big then
534/// add multiple cases to switch instruction, one for each value within
535/// the range. If range is too big then emit "if" condition check.
536void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000537 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000538
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000539 llvm::APSInt LHS = S.getLHS()->getIntegerConstantExprValue(getContext());
540 llvm::APSInt RHS = S.getRHS()->getIntegerConstantExprValue(getContext());
541
Daniel Dunbar16f23572008-07-25 01:11:38 +0000542 // Emit the code for this case. We do this first to make sure it is
543 // properly chained from our predecessor before generating the
544 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000545 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000546 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
547 EmitStmt(S.getSubStmt());
548
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000549 // If range is empty, do nothing.
550 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
551 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000552
553 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000554 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000555 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
556 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000557 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000558 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
559 LHS++;
560 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000561 return;
562 }
563
Daniel Dunbar16f23572008-07-25 01:11:38 +0000564 // The range is too big. Emit "if" condition into a new block,
565 // making sure to save and restore the current insertion point.
566 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000567
Daniel Dunbar16f23572008-07-25 01:11:38 +0000568 // Push this test onto the chain of range checks (which terminates
569 // in the default basic block). The switch's default will be changed
570 // to the top of this chain after switch emission is complete.
571 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000572 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000573
Daniel Dunbar16f23572008-07-25 01:11:38 +0000574 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
575 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000576
577 // Emit range check.
578 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000579 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
580 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000581 llvm::Value *Cond =
582 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
583 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
584
Daniel Dunbar16f23572008-07-25 01:11:38 +0000585 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000586 if (RestoreBB)
587 Builder.SetInsertPoint(RestoreBB);
588 else
589 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000590}
591
592void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
593 if (S.getRHS()) {
594 EmitCaseStmtRange(S);
595 return;
596 }
597
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000598 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000599 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000600 llvm::APSInt CaseVal = S.getLHS()->getIntegerConstantExprValue(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000601 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000602 EmitStmt(S.getSubStmt());
603}
604
605void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000606 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000607 assert(DefaultBlock->empty() &&
608 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000609 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000610 EmitStmt(S.getSubStmt());
611}
612
613void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
614 llvm::Value *CondV = EmitScalarExpr(S.getCond());
615
616 // Handle nested switch statements.
617 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000618 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000619
Daniel Dunbar16f23572008-07-25 01:11:38 +0000620 // Create basic block to hold stuff that comes after switch
621 // statement. We also need to create a default block now so that
622 // explicit case ranges tests can have a place to jump to on
623 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000624 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
625 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000626 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
627 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000628
Daniel Dunbar09124252008-11-12 08:21:33 +0000629 // Clear the insertion point to indicate we are in unreachable code.
630 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000631
Devang Patele9b8c0a2007-10-30 20:59:40 +0000632 // All break statements jump to NextBlock. If BreakContinueStack is non empty
633 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000634 llvm::BasicBlock *ContinueBlock = NULL;
635 if (!BreakContinueStack.empty())
636 ContinueBlock = BreakContinueStack.back().ContinueBlock;
637 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
638
639 // Emit switch body.
640 EmitStmt(S.getBody());
641 BreakContinueStack.pop_back();
642
Daniel Dunbar16f23572008-07-25 01:11:38 +0000643 // Update the default block in case explicit case range tests have
644 // been chained on top.
645 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000646
Daniel Dunbar16f23572008-07-25 01:11:38 +0000647 // If a default was never emitted then reroute any jumps to it and
648 // discard.
649 if (!DefaultBlock->getParent()) {
650 DefaultBlock->replaceAllUsesWith(NextBlock);
651 delete DefaultBlock;
652 }
Devang Patel51b09f22007-10-04 23:45:31 +0000653
Daniel Dunbar16f23572008-07-25 01:11:38 +0000654 // Emit continuation.
655 EmitBlock(NextBlock);
656
Devang Patel51b09f22007-10-04 23:45:31 +0000657 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000658 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000659}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000660
Anders Carlssonce179ab2008-11-09 18:54:14 +0000661static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
662{
663 // FIXME: No need to create new std::string here, we could just make sure
664 // that we don't read past the end of the string data.
665 std::string str(S.getAsmString()->getStrData(),
666 S.getAsmString()->getByteLength());
667 const char *Start = str.c_str();
668
669 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
670 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000671 Failed = false;
672
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000673 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000674 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000675 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000676 if (IsSimple) {
677 while (*Start) {
678 switch (*Start) {
679 default:
680 Result += *Start;
681 break;
682 case '$':
683 Result += "$$";
684 break;
685 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000686 Start++;
687 }
688
689 return Result;
690 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000691
692 while (*Start) {
693 switch (*Start) {
694 default:
695 Result += *Start;
696 break;
697 case '$':
698 Result += "$$";
699 break;
700 case '%':
701 // Escaped character
702 Start++;
703 if (!*Start) {
704 // FIXME: This should be caught during Sema.
705 assert(0 && "Trailing '%' in asm string.");
706 }
707
708 char EscapedChar = *Start;
709 if (EscapedChar == '%') {
710 // Escaped percentage sign.
711 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000712 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000713 // Generate an unique ID.
714 Result += llvm::utostr(AsmCounter);
715 } else if (isdigit(EscapedChar)) {
716 // %n - Assembler operand n
717 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000718 unsigned long n = strtoul(Start, &End, 10);
719 if (Start == End) {
720 // FIXME: This should be caught during Sema.
721 assert(0 && "Missing operand!");
722 } else if (n >= NumOperands) {
723 // FIXME: This should be caught during Sema.
724 assert(0 && "Operand number out of range!");
725 }
726
727 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000728 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000729 } else if (isalpha(EscapedChar)) {
730 char *End;
731
732 unsigned long n = strtoul(Start + 1, &End, 10);
733 if (Start == End) {
734 // FIXME: This should be caught during Sema.
735 assert(0 && "Missing operand!");
736 } else if (n >= NumOperands) {
737 // FIXME: This should be caught during Sema.
738 assert(0 && "Operand number out of range!");
739 }
740
741 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000742 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000743 } else if (EscapedChar == '[') {
744 std::string SymbolicName;
745
746 Start++;
747
748 while (*Start && *Start != ']') {
749 SymbolicName += *Start;
750
751 Start++;
752 }
753
754 if (!Start) {
755 // FIXME: Should be caught by sema.
756 assert(0 && "Could not parse symbolic name");
757 }
758
759 assert(*Start == ']' && "Error parsing symbolic name");
760
761 int Index = -1;
762
763 // Check if this is an output operand.
764 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
765 if (S.getOutputName(i) == SymbolicName) {
766 Index = i;
767 break;
768 }
769 }
770
771 if (Index == -1) {
772 for (unsigned i = 0; i < S.getNumInputs(); i++) {
773 if (S.getInputName(i) == SymbolicName) {
774 Index = S.getNumOutputs() + i;
775 }
776 }
777 }
778
779 assert(Index != -1 && "Did not find right operand!");
780
781 Result += '$' + llvm::utostr(Index);
782
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000783 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000784 Failed = true;
785 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000786 }
787 }
788 Start++;
789 }
790
791 return Result;
792}
793
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000794static std::string SimplifyConstraint(const char* Constraint,
795 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000796 std::string Result;
797
798 while (*Constraint) {
799 switch (*Constraint) {
800 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000801 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000802 break;
803 // Ignore these
804 case '*':
805 case '?':
806 case '!':
807 break;
808 case 'g':
809 Result += "imr";
810 break;
811 }
812
813 Constraint++;
814 }
815
816 return Result;
817}
818
819void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000820 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000821 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000822 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000823
824 if (Failed) {
825 ErrorUnsupported(&S, "asm string");
826 return;
827 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000828
829 std::string Constraints;
830
831 llvm::Value *ResultAddr = 0;
832 const llvm::Type *ResultType = llvm::Type::VoidTy;
833
834 std::vector<const llvm::Type*> ArgTypes;
835 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000836
837 // Keep track of inout constraints.
838 std::string InOutConstraints;
839 std::vector<llvm::Value*> InOutArgs;
840 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000841
842 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
843 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
844 S.getOutputConstraint(i)->getByteLength());
845
846 TargetInfo::ConstraintInfo Info;
847 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
848 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000849 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000850
851 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000852 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000853
854 LValue Dest = EmitLValue(S.getOutputExpr(i));
855 const llvm::Type *DestValueType =
856 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
857
858 // If the first output operand is not a memory dest, we'll
859 // make it the return value.
860 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000861 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000862 ResultAddr = Dest.getAddress();
863 ResultType = DestValueType;
864 Constraints += "=" + OutputConstraint;
865 } else {
866 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000867 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000868 if (i != 0)
869 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000870 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000871 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000872 }
873
874 if (Info & TargetInfo::CI_ReadWrite) {
875 // FIXME: This code should be shared with the code that handles inputs.
876 InOutConstraints += ',';
877
878 const Expr *InputExpr = S.getOutputExpr(i);
879 llvm::Value *Arg;
880 if ((Info & TargetInfo::CI_AllowsRegister) ||
881 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000882 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000883 Arg = EmitScalarExpr(InputExpr);
884 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000885 ErrorUnsupported(&S,
886 "asm statement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000887 }
888 } else {
889 LValue Dest = EmitLValue(InputExpr);
890 Arg = Dest.getAddress();
891 InOutConstraints += '*';
892 }
893
894 InOutArgTypes.push_back(Arg->getType());
895 InOutArgs.push_back(Arg);
896 InOutConstraints += OutputConstraint;
897 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000898 }
899
900 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
901
902 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
903 const Expr *InputExpr = S.getInputExpr(i);
904
905 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
906 S.getInputConstraint(i)->getByteLength());
907
908 TargetInfo::ConstraintInfo Info;
909 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Chris Lattner3304e552008-10-12 00:31:50 +0000910 NumConstraints, Info);
911 assert(result && "Failed to parse input constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000912
913 if (i != 0 || S.getNumOutputs() > 0)
914 Constraints += ',';
915
916 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000917 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000918
919 llvm::Value *Arg;
920
921 if ((Info & TargetInfo::CI_AllowsRegister) ||
922 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000923 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000924 Arg = EmitScalarExpr(InputExpr);
925 } else {
Chris Lattner62b72f62008-11-11 07:24:28 +0000926 ErrorUnsupported(&S,
927 "asm statement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000928 }
929 } else {
930 LValue Dest = EmitLValue(InputExpr);
931 Arg = Dest.getAddress();
932 Constraints += '*';
933 }
934
935 ArgTypes.push_back(Arg->getType());
936 Args.push_back(Arg);
937 Constraints += InputConstraint;
938 }
939
Anders Carlssonf39a4212008-02-05 20:01:53 +0000940 // Append the "input" part of inout constraints last.
941 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
942 ArgTypes.push_back(InOutArgTypes[i]);
943 Args.push_back(InOutArgs[i]);
944 }
945 Constraints += InOutConstraints;
946
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000947 // Clobbers
948 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
949 std::string Clobber(S.getClobber(i)->getStrData(),
950 S.getClobber(i)->getByteLength());
951
952 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
953
Anders Carlssonea041752008-02-06 00:11:32 +0000954 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000955 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000956
957 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000958 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000959 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000960 }
961
962 // Add machine specific clobbers
963 if (const char *C = Target.getClobbers()) {
964 if (!Constraints.empty())
965 Constraints += ',';
966 Constraints += C;
967 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000968
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000969 const llvm::FunctionType *FTy =
970 llvm::FunctionType::get(ResultType, ArgTypes, false);
971
972 llvm::InlineAsm *IA =
973 llvm::InlineAsm::get(FTy, AsmString, Constraints,
974 S.isVolatile() || S.getNumOutputs() == 0);
975 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +0000976 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000977 Builder.CreateStore(Result, ResultAddr);
978}