blob: 9743c7cadf37860b3db7c464b087e7471685801f [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"
17#include "clang/AST/AST.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000018#include "clang/Basic/TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000022#include "llvm/InlineAsm.h"
23#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25using namespace CodeGen;
26
27//===----------------------------------------------------------------------===//
28// Statement Emission
29//===----------------------------------------------------------------------===//
30
31void CodeGenFunction::EmitStmt(const Stmt *S) {
32 assert(S && "Null statement?");
33
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000034 // Generate stoppoints if we are emitting debug info.
35 // Beginning of a Compound Statement (e.g. an opening '{') does not produce
36 // executable code. So do not generate a stoppoint for that.
37 CGDebugInfo *DI = CGM.getDebugInfo();
38 if (DI && S->getStmtClass() != Stmt::CompoundStmtClass) {
39 if (S->getLocStart().isValid()) {
40 DI->setLocation(S->getLocStart());
41 }
42
43 DI->EmitStopPoint(CurFn, Builder);
44 }
45
Reid Spencer5f016e22007-07-11 17:01:13 +000046 switch (S->getStmtClass()) {
47 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000048 // Must be an expression in a stmt context. Emit the value (to get
49 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000050 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000051 if (!hasAggregateLLVMType(E->getType()))
52 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000053 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000054 EmitComplexExpr(E);
55 else
56 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000057 } else {
Chris Lattnerdc4d2802007-12-02 01:49:16 +000058 WarnUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000059 }
60 break;
61 case Stmt::NullStmtClass: break;
62 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
63 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
64 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
65
66 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
67 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
68 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
69 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
70
71 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
72 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Chris Lattnerda138702007-07-16 21:28:45 +000073
74 case Stmt::BreakStmtClass: EmitBreakStmt(); break;
75 case Stmt::ContinueStmtClass: EmitContinueStmt(); break;
Devang Patel51b09f22007-10-04 23:45:31 +000076 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
77 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
78 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000079 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000080 }
81}
82
Chris Lattner33793202007-08-31 22:09:40 +000083/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
84/// this captures the expression result of the last sub-statement and returns it
85/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +000086RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
87 llvm::Value *AggLoc, bool isAggVol) {
Reid Spencer5f016e22007-07-11 17:01:13 +000088 // FIXME: handle vla's etc.
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +000089 CGDebugInfo *DI = CGM.getDebugInfo();
90 if (DI) {
Chris Lattner345f7202008-07-26 20:15:14 +000091 if (S.getLBracLoc().isValid())
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +000092 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +000093 DI->EmitRegionStart(CurFn, Builder);
94 }
95
Chris Lattner33793202007-08-31 22:09:40 +000096 for (CompoundStmt::const_body_iterator I = S.body_begin(),
97 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +000098 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000099
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000100 if (DI) {
Chris Lattner345f7202008-07-26 20:15:14 +0000101 if (S.getRBracLoc().isValid())
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000102 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000103 DI->EmitRegionEnd(CurFn, Builder);
104 }
105
Chris Lattner33793202007-08-31 22:09:40 +0000106 if (!GetLast)
107 return RValue::get(0);
Chris Lattner9b655512007-08-31 22:49:20 +0000108
Chris Lattner91d723d2008-07-26 20:23:23 +0000109 // We have to special case labels here. They are statements, but when put at
110 // the end of a statement expression, they yield the value of their
111 // subexpression. Handle this by walking through all labels we encounter,
112 // emitting them before we evaluate the subexpr.
113 const Stmt *LastStmt = S.body_back();
114 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
115 EmitLabel(*LS);
116 LastStmt = LS->getSubStmt();
117 }
118
119 return EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000120}
121
122void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB) {
123 // Emit a branch from this block to the next one if this was a real block. If
124 // this was just a fall-through block after a terminator, don't emit it.
125 llvm::BasicBlock *LastBB = Builder.GetInsertBlock();
126
127 if (LastBB->getTerminator()) {
128 // If the previous block is already terminated, don't touch it.
Daniel Dunbar16f23572008-07-25 01:11:38 +0000129 } else if (LastBB->empty() && isDummyBlock(LastBB)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000130 // If the last block was an empty placeholder, remove it now.
131 // TODO: cache and reuse these.
Daniel Dunbar16f23572008-07-25 01:11:38 +0000132 LastBB->eraseFromParent();
Reid Spencer5f016e22007-07-11 17:01:13 +0000133 } else {
134 // Otherwise, create a fall-through branch.
135 Builder.CreateBr(BB);
136 }
137 CurFn->getBasicBlockList().push_back(BB);
138 Builder.SetInsertPoint(BB);
139}
140
Chris Lattner91d723d2008-07-26 20:23:23 +0000141void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000144}
145
146
147void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
148 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000149 EmitStmt(S.getSubStmt());
150}
151
152void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
153 Builder.CreateBr(getBasicBlockForLabel(S.getLabel()));
154
155 // Emit a block after the branch so that dead code after a goto has some place
156 // to go.
Gabor Greif984d0b42008-04-06 20:42:52 +0000157 Builder.SetInsertPoint(llvm::BasicBlock::Create("", CurFn));
Reid Spencer5f016e22007-07-11 17:01:13 +0000158}
159
160void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
161 // C99 6.8.4.1: The first substatement is executed if the expression compares
162 // unequal to 0. The condition must be a scalar type.
163 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
164
Gabor Greif984d0b42008-04-06 20:42:52 +0000165 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("ifend");
166 llvm::BasicBlock *ThenBlock = llvm::BasicBlock::Create("ifthen");
Reid Spencer5f016e22007-07-11 17:01:13 +0000167 llvm::BasicBlock *ElseBlock = ContBlock;
168
169 if (S.getElse())
Gabor Greif984d0b42008-04-06 20:42:52 +0000170 ElseBlock = llvm::BasicBlock::Create("ifelse");
Reid Spencer5f016e22007-07-11 17:01:13 +0000171
172 // Insert the conditional branch.
173 Builder.CreateCondBr(BoolCondVal, ThenBlock, ElseBlock);
174
175 // Emit the 'then' code.
176 EmitBlock(ThenBlock);
177 EmitStmt(S.getThen());
Devang Pateld9363c32007-09-28 21:49:18 +0000178 llvm::BasicBlock *BB = Builder.GetInsertBlock();
179 if (isDummyBlock(BB)) {
180 BB->eraseFromParent();
181 Builder.SetInsertPoint(ThenBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000182 } else {
Devang Pateld9363c32007-09-28 21:49:18 +0000183 Builder.CreateBr(ContBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000184 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000185
186 // Emit the 'else' code if present.
187 if (const Stmt *Else = S.getElse()) {
188 EmitBlock(ElseBlock);
189 EmitStmt(Else);
Devang Pateld9363c32007-09-28 21:49:18 +0000190 llvm::BasicBlock *BB = Builder.GetInsertBlock();
191 if (isDummyBlock(BB)) {
192 BB->eraseFromParent();
193 Builder.SetInsertPoint(ElseBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000194 } else {
Devang Pateld9363c32007-09-28 21:49:18 +0000195 Builder.CreateBr(ContBlock);
Chris Lattner345f7202008-07-26 20:15:14 +0000196 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000197 }
198
199 // Emit the continuation block for code after the if.
200 EmitBlock(ContBlock);
201}
202
203void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000204 // Emit the header for the loop, insert it, which will create an uncond br to
205 // it.
Gabor Greif984d0b42008-04-06 20:42:52 +0000206 llvm::BasicBlock *LoopHeader = llvm::BasicBlock::Create("whilecond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000207 EmitBlock(LoopHeader);
208
209 // Evaluate the conditional in the while header. C99 6.8.5.1: The evaluation
210 // of the controlling expression takes place before each execution of the loop
211 // body.
212 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000213
214 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000215 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000216 bool EmitBoolCondBranch = true;
217 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
218 if (C->isOne())
219 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000220
221 // Create an exit block for when the condition fails, create a block for the
222 // body of the loop.
Gabor Greif984d0b42008-04-06 20:42:52 +0000223 llvm::BasicBlock *ExitBlock = llvm::BasicBlock::Create("whileexit");
224 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("whilebody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000225
226 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000227 if (EmitBoolCondBranch)
228 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000229
230 // Store the blocks to use for break and continue.
231 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000232
233 // Emit the loop body.
234 EmitBlock(LoopBody);
235 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000236
237 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000238
239 // Cycle to the condition.
240 Builder.CreateBr(LoopHeader);
241
242 // Emit the exit block.
243 EmitBlock(ExitBlock);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000244
245 // If LoopHeader is a simple forwarding block then eliminate it.
246 if (!EmitBoolCondBranch
247 && &LoopHeader->front() == LoopHeader->getTerminator()) {
248 LoopHeader->replaceAllUsesWith(LoopBody);
249 LoopHeader->getTerminator()->eraseFromParent();
250 LoopHeader->eraseFromParent();
251 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000252}
253
254void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000255 // Emit the body for the loop, insert it, which will create an uncond br to
256 // it.
Gabor Greif984d0b42008-04-06 20:42:52 +0000257 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("dobody");
258 llvm::BasicBlock *AfterDo = llvm::BasicBlock::Create("afterdo");
Reid Spencer5f016e22007-07-11 17:01:13 +0000259 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000260
Gabor Greif984d0b42008-04-06 20:42:52 +0000261 llvm::BasicBlock *DoCond = llvm::BasicBlock::Create("docond");
Chris Lattnerda138702007-07-16 21:28:45 +0000262
263 // Store the blocks to use for break and continue.
264 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000265
266 // Emit the body of the loop into the block.
267 EmitStmt(S.getBody());
268
Chris Lattnerda138702007-07-16 21:28:45 +0000269 BreakContinueStack.pop_back();
270
271 EmitBlock(DoCond);
272
Reid Spencer5f016e22007-07-11 17:01:13 +0000273 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
274 // after each execution of the loop body."
275
276 // Evaluate the conditional in the while header.
277 // C99 6.8.5p2/p4: The first substatement is executed if the expression
278 // compares unequal to 0. The condition must be a scalar type.
279 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000280
281 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
282 // to correctly handle break/continue though.
283 bool EmitBoolCondBranch = true;
284 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
285 if (C->isZero())
286 EmitBoolCondBranch = false;
287
Reid Spencer5f016e22007-07-11 17:01:13 +0000288 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000289 if (EmitBoolCondBranch)
290 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000291
292 // Emit the exit block.
293 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000294
295 // If DoCond is a simple forwarding block then eliminate it.
296 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
297 DoCond->replaceAllUsesWith(AfterDo);
298 DoCond->getTerminator()->eraseFromParent();
299 DoCond->eraseFromParent();
300 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000301}
302
303void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
305 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000306 // TODO: We could keep track of whether the loop body contains any
307 // break/continue statements and not create unnecessary blocks (like
308 // "afterfor" for a condless loop) if it doesn't.
309
Reid Spencer5f016e22007-07-11 17:01:13 +0000310 // Evaluate the first part before the loop.
311 if (S.getInit())
312 EmitStmt(S.getInit());
313
314 // Start the loop with a block that tests the condition.
Gabor Greif984d0b42008-04-06 20:42:52 +0000315 llvm::BasicBlock *CondBlock = llvm::BasicBlock::Create("forcond");
316 llvm::BasicBlock *AfterFor = llvm::BasicBlock::Create("afterfor");
Chris Lattnerda138702007-07-16 21:28:45 +0000317
Reid Spencer5f016e22007-07-11 17:01:13 +0000318 EmitBlock(CondBlock);
319
320 // Evaluate the condition if present. If not, treat it as a non-zero-constant
321 // according to 6.8.5.3p2, aka, true.
322 if (S.getCond()) {
323 // C99 6.8.5p2/p4: The first substatement is executed if the expression
324 // compares unequal to 0. The condition must be a scalar type.
325 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
326
327 // As long as the condition is true, iterate the loop.
Gabor Greif984d0b42008-04-06 20:42:52 +0000328 llvm::BasicBlock *ForBody = llvm::BasicBlock::Create("forbody");
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 Builder.CreateCondBr(BoolCondVal, ForBody, AfterFor);
330 EmitBlock(ForBody);
331 } else {
332 // Treat it as a non-zero constant. Don't even create a new block for the
333 // body, just fall into it.
334 }
335
Chris Lattnerda138702007-07-16 21:28:45 +0000336 // If the for loop doesn't have an increment we can just use the
337 // condition as the continue block.
338 llvm::BasicBlock *ContinueBlock;
339 if (S.getInc())
Gabor Greif984d0b42008-04-06 20:42:52 +0000340 ContinueBlock = llvm::BasicBlock::Create("forinc");
Chris Lattnerda138702007-07-16 21:28:45 +0000341 else
342 ContinueBlock = CondBlock;
343
344 // Store the blocks to use for break and continue.
345 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
346
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 // If the condition is true, execute the body of the for stmt.
348 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000349
350 BreakContinueStack.pop_back();
351
352 if (S.getInc())
353 EmitBlock(ContinueBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000354
355 // If there is an increment, emit it next.
356 if (S.getInc())
Chris Lattner883f6a72007-08-11 00:04:45 +0000357 EmitStmt(S.getInc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000358
359 // Finally, branch back up to the condition for the next iteration.
360 Builder.CreateBr(CondBlock);
361
Chris Lattnerda138702007-07-16 21:28:45 +0000362 // Emit the fall-through block.
363 EmitBlock(AfterFor);
Reid Spencer5f016e22007-07-11 17:01:13 +0000364}
365
366/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
367/// if the function returns void, or may be missing one if the function returns
368/// non-void. Fun stuff :).
369void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 // Emit the result value, even if unused, to evalute the side effects.
371 const Expr *RV = S.getRetValue();
Chris Lattner4b0029d2007-08-26 07:14:44 +0000372
Eli Friedman144ac612008-05-22 01:22:33 +0000373 llvm::Value* RetValue = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000374 if (FnRetTy->isVoidType()) {
Eli Friedman144ac612008-05-22 01:22:33 +0000375 // Make sure not to return anything
376 if (RV) {
377 // Evaluate the expression for side effects
378 EmitAnyExpr(RV);
379 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000380 } else if (RV == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 const llvm::Type *RetTy = CurFn->getFunctionType()->getReturnType();
Eli Friedman144ac612008-05-22 01:22:33 +0000382 if (RetTy != llvm::Type::VoidTy) {
383 // Handle "return;" in a function that returns a value.
384 RetValue = llvm::UndefValue::get(RetTy);
385 }
Chris Lattner4b0029d2007-08-26 07:14:44 +0000386 } else if (!hasAggregateLLVMType(RV->getType())) {
Eli Friedman144ac612008-05-22 01:22:33 +0000387 RetValue = EmitScalarExpr(RV);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000388 } else if (RV->getType()->isAnyComplexType()) {
Chris Lattner345f7202008-07-26 20:15:14 +0000389 EmitComplexExprIntoAddr(RV, CurFn->arg_begin(), false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000390 } else {
Chris Lattner345f7202008-07-26 20:15:14 +0000391 EmitAggExpr(RV, CurFn->arg_begin(), false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000392 }
Eli Friedman144ac612008-05-22 01:22:33 +0000393
394 if (RetValue) {
395 Builder.CreateRet(RetValue);
396 } else {
397 Builder.CreateRetVoid();
398 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000399
400 // Emit a block after the branch so that dead code after a return has some
401 // place to go.
Gabor Greif984d0b42008-04-06 20:42:52 +0000402 EmitBlock(llvm::BasicBlock::Create());
Reid Spencer5f016e22007-07-11 17:01:13 +0000403}
404
405void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Steve Naroff94745042007-09-13 23:52:58 +0000406 for (const ScopedDecl *Decl = S.getDecl(); Decl;
407 Decl = Decl->getNextDeclarator())
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 EmitDecl(*Decl);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000409}
Chris Lattnerda138702007-07-16 21:28:45 +0000410
411void CodeGenFunction::EmitBreakStmt() {
412 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
413
414 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
415 Builder.CreateBr(Block);
Gabor Greif984d0b42008-04-06 20:42:52 +0000416 EmitBlock(llvm::BasicBlock::Create());
Chris Lattnerda138702007-07-16 21:28:45 +0000417}
418
419void CodeGenFunction::EmitContinueStmt() {
420 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
421
422 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
423 Builder.CreateBr(Block);
Gabor Greif984d0b42008-04-06 20:42:52 +0000424 EmitBlock(llvm::BasicBlock::Create());
Chris Lattnerda138702007-07-16 21:28:45 +0000425}
Devang Patel51b09f22007-10-04 23:45:31 +0000426
Devang Patelc049e4f2007-10-08 20:57:48 +0000427/// EmitCaseStmtRange - If case statement range is not too big then
428/// add multiple cases to switch instruction, one for each value within
429/// the range. If range is too big then emit "if" condition check.
430void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000431 // XXX kill me with param - ddunbar
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000432 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000433
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000434 llvm::APSInt LHS = S.getLHS()->getIntegerConstantExprValue(getContext());
435 llvm::APSInt RHS = S.getRHS()->getIntegerConstantExprValue(getContext());
436
Daniel Dunbar16f23572008-07-25 01:11:38 +0000437 // Emit the code for this case. We do this first to make sure it is
438 // properly chained from our predecessor before generating the
439 // switch machinery to enter this block.
440 StartBlock("sw.bb");
441 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
442 EmitStmt(S.getSubStmt());
443
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000444 // If range is empty, do nothing.
445 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
446 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000447
448 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000449 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000450 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
451 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000452 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000453 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
454 LHS++;
455 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000456 return;
457 }
458
Daniel Dunbar16f23572008-07-25 01:11:38 +0000459 // The range is too big. Emit "if" condition into a new block,
460 // making sure to save and restore the current insertion point.
461 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000462
Daniel Dunbar16f23572008-07-25 01:11:38 +0000463 // Push this test onto the chain of range checks (which terminates
464 // in the default basic block). The switch's default will be changed
465 // to the top of this chain after switch emission is complete.
466 llvm::BasicBlock *FalseDest = CaseRangeBlock;
467 CaseRangeBlock = llvm::BasicBlock::Create("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000468
Daniel Dunbar16f23572008-07-25 01:11:38 +0000469 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
470 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000471
472 // Emit range check.
473 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000474 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
475 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000476 llvm::Value *Cond =
477 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
478 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
479
Daniel Dunbar16f23572008-07-25 01:11:38 +0000480 // Restore the appropriate insertion point.
481 Builder.SetInsertPoint(RestoreBB);
Devang Patelc049e4f2007-10-08 20:57:48 +0000482}
483
484void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
485 if (S.getRHS()) {
486 EmitCaseStmtRange(S);
487 return;
488 }
489
490 StartBlock("sw.bb");
491 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000492 llvm::APSInt CaseVal = S.getLHS()->getIntegerConstantExprValue(getContext());
493 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal),
494 CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000495 EmitStmt(S.getSubStmt());
496}
497
498void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000499 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
500 assert(DefaultBlock->empty() && "EmitDefaultStmt: Default block already defined?");
501 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000502 EmitStmt(S.getSubStmt());
503}
504
505void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
506 llvm::Value *CondV = EmitScalarExpr(S.getCond());
507
508 // Handle nested switch statements.
509 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000510 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000511
Daniel Dunbar16f23572008-07-25 01:11:38 +0000512 // Create basic block to hold stuff that comes after switch
513 // statement. We also need to create a default block now so that
514 // explicit case ranges tests can have a place to jump to on
515 // failure.
516 llvm::BasicBlock *NextBlock = llvm::BasicBlock::Create("sw.epilog");
517 llvm::BasicBlock *DefaultBlock = llvm::BasicBlock::Create("sw.default");
518 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
519 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000520
Eli Friedmand28a80d2008-05-12 16:08:04 +0000521 // Create basic block for body of switch
Daniel Dunbar16f23572008-07-25 01:11:38 +0000522 StartBlock("sw.body");
Eli Friedmand28a80d2008-05-12 16:08:04 +0000523
Devang Patele9b8c0a2007-10-30 20:59:40 +0000524 // All break statements jump to NextBlock. If BreakContinueStack is non empty
525 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000526 llvm::BasicBlock *ContinueBlock = NULL;
527 if (!BreakContinueStack.empty())
528 ContinueBlock = BreakContinueStack.back().ContinueBlock;
529 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
530
531 // Emit switch body.
532 EmitStmt(S.getBody());
533 BreakContinueStack.pop_back();
534
Daniel Dunbar16f23572008-07-25 01:11:38 +0000535 // Update the default block in case explicit case range tests have
536 // been chained on top.
537 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000538
Daniel Dunbar16f23572008-07-25 01:11:38 +0000539 // If a default was never emitted then reroute any jumps to it and
540 // discard.
541 if (!DefaultBlock->getParent()) {
542 DefaultBlock->replaceAllUsesWith(NextBlock);
543 delete DefaultBlock;
544 }
Devang Patel51b09f22007-10-04 23:45:31 +0000545
Daniel Dunbar16f23572008-07-25 01:11:38 +0000546 // Emit continuation.
547 EmitBlock(NextBlock);
548
Devang Patel51b09f22007-10-04 23:45:31 +0000549 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000550 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000551}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000552
Chris Lattner345f7202008-07-26 20:15:14 +0000553static std::string ConvertAsmString(const char *Start, unsigned NumOperands,
554 bool IsSimple) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000555 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000556 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000557 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000558 if (IsSimple) {
559 while (*Start) {
560 switch (*Start) {
561 default:
562 Result += *Start;
563 break;
564 case '$':
565 Result += "$$";
566 break;
567 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000568 Start++;
569 }
570
571 return Result;
572 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000573
574 while (*Start) {
575 switch (*Start) {
576 default:
577 Result += *Start;
578 break;
579 case '$':
580 Result += "$$";
581 break;
582 case '%':
583 // Escaped character
584 Start++;
585 if (!*Start) {
586 // FIXME: This should be caught during Sema.
587 assert(0 && "Trailing '%' in asm string.");
588 }
589
590 char EscapedChar = *Start;
591 if (EscapedChar == '%') {
592 // Escaped percentage sign.
593 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000594 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000595 // Generate an unique ID.
596 Result += llvm::utostr(AsmCounter);
597 } else if (isdigit(EscapedChar)) {
598 // %n - Assembler operand n
599 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000600 unsigned long n = strtoul(Start, &End, 10);
601 if (Start == End) {
602 // FIXME: This should be caught during Sema.
603 assert(0 && "Missing operand!");
604 } else if (n >= NumOperands) {
605 // FIXME: This should be caught during Sema.
606 assert(0 && "Operand number out of range!");
607 }
608
609 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000610 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000611 } else if (isalpha(EscapedChar)) {
612 char *End;
613
614 unsigned long n = strtoul(Start + 1, &End, 10);
615 if (Start == End) {
616 // FIXME: This should be caught during Sema.
617 assert(0 && "Missing operand!");
618 } else if (n >= NumOperands) {
619 // FIXME: This should be caught during Sema.
620 assert(0 && "Operand number out of range!");
621 }
622
623 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000624 Start = End - 1;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000625 } else {
626 assert(0 && "Unhandled asm escaped character!");
627 }
628 }
629 Start++;
630 }
631
632 return Result;
633}
634
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000635static std::string SimplifyConstraint(const char* Constraint,
636 TargetInfo &Target) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000637 std::string Result;
638
639 while (*Constraint) {
640 switch (*Constraint) {
641 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000642 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000643 break;
644 // Ignore these
645 case '*':
646 case '?':
647 case '!':
648 break;
649 case 'g':
650 Result += "imr";
651 break;
652 }
653
654 Constraint++;
655 }
656
657 return Result;
658}
659
660void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
661 std::string AsmString =
662 ConvertAsmString(std::string(S.getAsmString()->getStrData(),
663 S.getAsmString()->getByteLength()).c_str(),
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000664 S.getNumOutputs() + S.getNumInputs(), S.isSimple());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000665
666 std::string Constraints;
667
668 llvm::Value *ResultAddr = 0;
669 const llvm::Type *ResultType = llvm::Type::VoidTy;
670
671 std::vector<const llvm::Type*> ArgTypes;
672 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000673
674 // Keep track of inout constraints.
675 std::string InOutConstraints;
676 std::vector<llvm::Value*> InOutArgs;
677 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000678
679 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
680 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
681 S.getOutputConstraint(i)->getByteLength());
682
683 TargetInfo::ConstraintInfo Info;
684 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
685 Info);
686 assert(result && "Failed to parse output constraint");
687
688 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000689 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000690
691 LValue Dest = EmitLValue(S.getOutputExpr(i));
692 const llvm::Type *DestValueType =
693 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
694
695 // If the first output operand is not a memory dest, we'll
696 // make it the return value.
697 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000698 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000699 ResultAddr = Dest.getAddress();
700 ResultType = DestValueType;
701 Constraints += "=" + OutputConstraint;
702 } else {
703 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000704 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000705 if (i != 0)
706 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000707 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000708 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000709 }
710
711 if (Info & TargetInfo::CI_ReadWrite) {
712 // FIXME: This code should be shared with the code that handles inputs.
713 InOutConstraints += ',';
714
715 const Expr *InputExpr = S.getOutputExpr(i);
716 llvm::Value *Arg;
717 if ((Info & TargetInfo::CI_AllowsRegister) ||
718 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000719 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000720 Arg = EmitScalarExpr(InputExpr);
721 } else {
Dan Gohmand79a7262008-05-22 22:12:56 +0000722 assert(0 && "FIXME: Implement passing multiple-value types as inputs");
Anders Carlssonf39a4212008-02-05 20:01:53 +0000723 }
724 } else {
725 LValue Dest = EmitLValue(InputExpr);
726 Arg = Dest.getAddress();
727 InOutConstraints += '*';
728 }
729
730 InOutArgTypes.push_back(Arg->getType());
731 InOutArgs.push_back(Arg);
732 InOutConstraints += OutputConstraint;
733 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000734 }
735
736 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
737
738 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
739 const Expr *InputExpr = S.getInputExpr(i);
740
741 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
742 S.getInputConstraint(i)->getByteLength());
743
744 TargetInfo::ConstraintInfo Info;
745 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
746 NumConstraints,
747 Info);
748 assert(result && "Failed to parse input constraint");
749
750 if (i != 0 || S.getNumOutputs() > 0)
751 Constraints += ',';
752
753 // Simplify the input constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000754 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000755
756 llvm::Value *Arg;
757
758 if ((Info & TargetInfo::CI_AllowsRegister) ||
759 !(Info & TargetInfo::CI_AllowsMemory)) {
Dan Gohmand79a7262008-05-22 22:12:56 +0000760 if (ConvertType(InputExpr->getType())->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000761 Arg = EmitScalarExpr(InputExpr);
762 } else {
Dan Gohmand79a7262008-05-22 22:12:56 +0000763 assert(0 && "FIXME: Implement passing multiple-value types as inputs");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000764 }
765 } else {
766 LValue Dest = EmitLValue(InputExpr);
767 Arg = Dest.getAddress();
768 Constraints += '*';
769 }
770
771 ArgTypes.push_back(Arg->getType());
772 Args.push_back(Arg);
773 Constraints += InputConstraint;
774 }
775
Anders Carlssonf39a4212008-02-05 20:01:53 +0000776 // Append the "input" part of inout constraints last.
777 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
778 ArgTypes.push_back(InOutArgTypes[i]);
779 Args.push_back(InOutArgs[i]);
780 }
781 Constraints += InOutConstraints;
782
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000783 // Clobbers
784 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
785 std::string Clobber(S.getClobber(i)->getStrData(),
786 S.getClobber(i)->getByteLength());
787
788 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
789
Anders Carlssonea041752008-02-06 00:11:32 +0000790 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000791 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000792
793 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000794 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000795 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000796 }
797
798 // Add machine specific clobbers
799 if (const char *C = Target.getClobbers()) {
800 if (!Constraints.empty())
801 Constraints += ',';
802 Constraints += C;
803 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000804
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000805 const llvm::FunctionType *FTy =
806 llvm::FunctionType::get(ResultType, ArgTypes, false);
807
808 llvm::InlineAsm *IA =
809 llvm::InlineAsm::get(FTy, AsmString, Constraints,
810 S.isVolatile() || S.getNumOutputs() == 0);
811 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +0000812 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000813 Builder.CreateStore(Result, ResultAddr);
814}