blob: 0999947881fe6a30dd77e35f3d60cef4b31f8bb3 [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"
Chris Lattner7d22bf02009-03-05 08:04:57 +000018#include "clang/Basic/PrettyStackTrace.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000020#include "llvm/ADT/StringExtras.h"
Anders Carlsson17d28a32008-12-12 05:52:00 +000021#include "llvm/InlineAsm.h"
22#include "llvm/Intrinsics.h"
Anders Carlssonebaae2a2009-01-12 02:22:13 +000023#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25using namespace CodeGen;
26
27//===----------------------------------------------------------------------===//
28// Statement Emission
29//===----------------------------------------------------------------------===//
30
Daniel Dunbar09124252008-11-12 08:21:33 +000031void CodeGenFunction::EmitStopPoint(const Stmt *S) {
Anders Carlssone896d982009-02-13 08:11:52 +000032 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar09124252008-11-12 08:21:33 +000033 DI->setLocation(S->getLocStart());
34 DI->EmitStopPoint(CurFn, Builder);
35 }
36}
37
Reid Spencer5f016e22007-07-11 17:01:13 +000038void CodeGenFunction::EmitStmt(const Stmt *S) {
39 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000040
Daniel Dunbar09124252008-11-12 08:21:33 +000041 // Check if we can handle this without bothering to generate an
42 // insert point or debug info.
43 if (EmitSimpleStmt(S))
44 return;
45
Daniel Dunbard286f052009-07-19 06:58:07 +000046 // Check if we are generating unreachable code.
47 if (!HaveInsertPoint()) {
48 // If so, and the statement doesn't contain a label, then we do not need to
49 // generate actual code. This is safe because (1) the current point is
50 // unreachable, so we don't need to execute the code, and (2) we've already
51 // handled the statements which update internal data structures (like the
52 // local variable map) which could be used by subsequent statements.
53 if (!ContainsLabel(S)) {
54 // Verify that any decl statements were handled as simple, they may be in
55 // scope of subsequent reachable statements.
56 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
57 return;
58 }
59
60 // Otherwise, make a new block to hold the code.
61 EnsureInsertPoint();
62 }
63
Daniel Dunbar09124252008-11-12 08:21:33 +000064 // Generate a stoppoint if we are emitting debug info.
65 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000066
Reid Spencer5f016e22007-07-11 17:01:13 +000067 switch (S->getStmtClass()) {
68 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000069 // Must be an expression in a stmt context. Emit the value (to get
70 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000071 if (const Expr *E = dyn_cast<Expr>(S)) {
Mike Stump49d1cd52009-05-26 22:03:21 +000072 EmitAnyExpr(E, 0, false, true);
Reid Spencer5f016e22007-07-11 17:01:13 +000073 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000074 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000075 }
76 break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000077 case Stmt::IndirectGotoStmtClass:
78 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000079
80 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
81 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
82 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
83 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
84
85 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +000086
Devang Patel51b09f22007-10-04 23:45:31 +000087 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000088 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000089
90 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000091 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
92 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000093 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +000094 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
95 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000096 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000097 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +000098 break;
99 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000100 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000101 break;
102 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +0000103 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000104 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000105 case Stmt::ObjCForCollectionStmtClass:
106 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000107 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000108 }
109}
110
Daniel Dunbar09124252008-11-12 08:21:33 +0000111bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
112 switch (S->getStmtClass()) {
113 default: return false;
114 case Stmt::NullStmtClass: break;
115 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
Daniel Dunbard286f052009-07-19 06:58:07 +0000116 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbar09124252008-11-12 08:21:33 +0000117 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
118 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
119 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
120 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
121 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
122 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
123 }
124
125 return true;
126}
127
Chris Lattner33793202007-08-31 22:09:40 +0000128/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
129/// this captures the expression result of the last sub-statement and returns it
130/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000131RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
132 llvm::Value *AggLoc, bool isAggVol) {
Chris Lattner7d22bf02009-03-05 08:04:57 +0000133 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
134 "LLVM IR generation of compound statement ('{}')");
135
Anders Carlssone896d982009-02-13 08:11:52 +0000136 CGDebugInfo *DI = getDebugInfo();
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000137 if (DI) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000138 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000139 DI->setLocation(S.getLBracLoc());
Chris Lattnerdcd808c2009-05-04 18:27:04 +0000140 // FIXME: The llvm backend is currently not ready to deal with region_end
141 // for block scoping. In the presence of always_inline functions it gets so
142 // confused that it doesn't emit any debug info. Just disable this for now.
143 //DI->EmitRegionStart(CurFn, Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000144 }
145
Anders Carlssonc71c8452009-02-07 23:50:39 +0000146 // Keep track of the current cleanup stack depth.
147 size_t CleanupStackDepth = CleanupEntries.size();
Anders Carlsson74331892009-02-09 20:23:40 +0000148 bool OldDidCallStackSave = DidCallStackSave;
Anders Carlsson66b41512009-02-22 18:44:21 +0000149 DidCallStackSave = false;
Anders Carlsson74331892009-02-09 20:23:40 +0000150
Chris Lattner33793202007-08-31 22:09:40 +0000151 for (CompoundStmt::const_body_iterator I = S.body_begin(),
152 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000154
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000155 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000156 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000157 DI->setLocation(S.getRBracLoc());
Chris Lattnerdcd808c2009-05-04 18:27:04 +0000158
159 // FIXME: The llvm backend is currently not ready to deal with region_end
160 // for block scoping. In the presence of always_inline functions it gets so
161 // confused that it doesn't emit any debug info. Just disable this for now.
162 //DI->EmitRegionEnd(CurFn, Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000163 }
164
Anders Carlsson17d28a32008-12-12 05:52:00 +0000165 RValue RV;
166 if (!GetLast)
167 RV = RValue::get(0);
168 else {
169 // We have to special case labels here. They are statements, but when put
170 // at the end of a statement expression, they yield the value of their
171 // subexpression. Handle this by walking through all labels we encounter,
172 // emitting them before we evaluate the subexpr.
173 const Stmt *LastStmt = S.body_back();
174 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
175 EmitLabel(*LS);
176 LastStmt = LS->getSubStmt();
177 }
Chris Lattner9b655512007-08-31 22:49:20 +0000178
Anders Carlsson17d28a32008-12-12 05:52:00 +0000179 EnsureInsertPoint();
180
181 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
182 }
183
Anders Carlsson74331892009-02-09 20:23:40 +0000184 DidCallStackSave = OldDidCallStackSave;
185
Anders Carlssonc71c8452009-02-07 23:50:39 +0000186 EmitCleanupBlocks(CleanupStackDepth);
187
Anders Carlsson17d28a32008-12-12 05:52:00 +0000188 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000189}
190
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000191void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
192 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
193
194 // If there is a cleanup stack, then we it isn't worth trying to
195 // simplify this block (we would need to remove it from the scope map
196 // and cleanup entry).
197 if (!CleanupEntries.empty())
198 return;
199
200 // Can only simplify direct branches.
201 if (!BI || !BI->isUnconditional())
202 return;
203
204 BB->replaceAllUsesWith(BI->getSuccessor(0));
205 BI->eraseFromParent();
206 BB->eraseFromParent();
207}
208
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000209void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000210 // Fall out of the current block (if necessary).
211 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000212
213 if (IsFinished && BB->use_empty()) {
214 delete BB;
215 return;
216 }
217
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000218 // If necessary, associate the block with the cleanup stack size.
219 if (!CleanupEntries.empty()) {
Anders Carlsson22ab8d82009-02-10 22:50:24 +0000220 // Check if the basic block has already been inserted.
221 BlockScopeMap::iterator I = BlockScopes.find(BB);
222 if (I != BlockScopes.end()) {
223 assert(I->second == CleanupEntries.size() - 1);
224 } else {
225 BlockScopes[BB] = CleanupEntries.size() - 1;
226 CleanupEntries.back().Blocks.push_back(BB);
227 }
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000228 }
229
Reid Spencer5f016e22007-07-11 17:01:13 +0000230 CurFn->getBasicBlockList().push_back(BB);
231 Builder.SetInsertPoint(BB);
232}
233
Daniel Dunbard57a8712008-11-11 09:41:28 +0000234void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
235 // Emit a branch from the current block to the target one if this
236 // was a real block. If this was just a fall-through block after a
237 // terminator, don't emit it.
238 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
239
240 if (!CurBB || CurBB->getTerminator()) {
241 // If there is no insert point or the previous block is already
242 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000243 } else {
244 // Otherwise, create a fall-through branch.
245 Builder.CreateBr(Target);
246 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000247
248 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000249}
250
Mike Stumpec9771d2009-02-08 09:22:19 +0000251void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Anders Carlssonfa1f7562009-02-10 06:07:49 +0000252 EmitBlock(getBasicBlockForLabel(&S));
Chris Lattner91d723d2008-07-26 20:23:23 +0000253}
254
255
256void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
257 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000258 EmitStmt(S.getSubStmt());
259}
260
261void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000262 // If this code is reachable then emit a stop point (if generating
263 // debug info). We have to do this ourselves because we are on the
264 // "simple" statement path.
265 if (HaveInsertPoint())
266 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000267
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000268 EmitBranchThroughCleanup(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000269}
270
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000271void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
272 // Emit initial switch which will be patched up later by
273 // EmitIndirectSwitches(). We need a default dest, so we use the
274 // current BB, but this is overwritten.
275 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
276 llvm::Type::Int32Ty,
277 "addr");
278 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
279 IndirectSwitches.push_back(I);
280
Daniel Dunbara448fb22008-11-11 23:11:34 +0000281 // Clear the insertion point to indicate we are in unreachable code.
282 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000283}
284
Chris Lattner62b72f62008-11-11 07:24:28 +0000285void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000286 // C99 6.8.4.1: The first substatement is executed if the expression compares
287 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000288
Chris Lattner9bc47e22008-11-12 07:46:33 +0000289 // If the condition constant folds and can be elided, try to avoid emitting
290 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000291 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000292 // Figure out which block (then or else) is executed.
293 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000294 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000295 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000296
Chris Lattner62b72f62008-11-11 07:24:28 +0000297 // If the skipped block has no labels in it, just emit the executed block.
298 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000299 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000300 if (Executed)
301 EmitStmt(Executed);
302 return;
303 }
304 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000305
306 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
307 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000308 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
309 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
310 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000312 ElseBlock = createBasicBlock("if.else");
313 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000314
315 // Emit the 'then' code.
316 EmitBlock(ThenBlock);
317 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000318 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000319
320 // Emit the 'else' code if present.
321 if (const Stmt *Else = S.getElse()) {
322 EmitBlock(ElseBlock);
323 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000324 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000325 }
326
327 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000328 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000329}
330
331void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000332 // Emit the header for the loop, insert it, which will create an uncond br to
333 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000334 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 EmitBlock(LoopHeader);
Mike Stump72cac2c2009-02-07 18:08:12 +0000336
337 // Create an exit block for when the condition fails, create a block for the
338 // body of the loop.
339 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
340 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
341
342 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000343 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000344
Mike Stump16b16202009-02-07 17:18:33 +0000345 // Evaluate the conditional in the while header. C99 6.8.5.1: The
346 // evaluation of the controlling expression takes place before each
347 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000349
350 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000351 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000352 bool EmitBoolCondBranch = true;
353 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
354 if (C->isOne())
355 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000356
Reid Spencer5f016e22007-07-11 17:01:13 +0000357 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000358 if (EmitBoolCondBranch)
359 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000360
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 // Emit the loop body.
362 EmitBlock(LoopBody);
363 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000364
Anders Carlssone4b6d342009-02-10 05:52:02 +0000365 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000366
367 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000368 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000369
370 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000371 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000372
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000373 // The LoopHeader typically is just a branch if we skipped emitting
374 // a branch, try to erase it.
375 if (!EmitBoolCondBranch)
376 SimplifyForwardingBlocks(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000377}
378
379void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000380 // Emit the body for the loop, insert it, which will create an uncond br to
381 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000382 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
383 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000384 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000385
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000386 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattnerda138702007-07-16 21:28:45 +0000387
388 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000389 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000390
391 // Emit the body of the loop into the block.
392 EmitStmt(S.getBody());
393
Anders Carlssone4b6d342009-02-10 05:52:02 +0000394 BreakContinueStack.pop_back();
Chris Lattnerda138702007-07-16 21:28:45 +0000395
396 EmitBlock(DoCond);
397
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
399 // after each execution of the loop body."
400
401 // Evaluate the conditional in the while header.
402 // C99 6.8.5p2/p4: The first substatement is executed if the expression
403 // compares unequal to 0. The condition must be a scalar type.
404 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000405
406 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
407 // to correctly handle break/continue though.
408 bool EmitBoolCondBranch = true;
409 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
410 if (C->isZero())
411 EmitBoolCondBranch = false;
412
Reid Spencer5f016e22007-07-11 17:01:13 +0000413 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000414 if (EmitBoolCondBranch)
415 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000416
417 // Emit the exit block.
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000418 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000419
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000420 // The DoCond block typically is just a branch if we skipped
421 // emitting a branch, try to erase it.
422 if (!EmitBoolCondBranch)
423 SimplifyForwardingBlocks(DoCond);
Reid Spencer5f016e22007-07-11 17:01:13 +0000424}
425
426void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000427 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
428 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000429
Reid Spencer5f016e22007-07-11 17:01:13 +0000430 // Evaluate the first part before the loop.
431 if (S.getInit())
432 EmitStmt(S.getInit());
433
434 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000435 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
436 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattnerda138702007-07-16 21:28:45 +0000437
Reid Spencer5f016e22007-07-11 17:01:13 +0000438 EmitBlock(CondBlock);
439
Mike Stump20926c62009-02-07 20:14:12 +0000440 // Evaluate the condition if present. If not, treat it as a
441 // non-zero-constant according to 6.8.5.3p2, aka, true.
Reid Spencer5f016e22007-07-11 17:01:13 +0000442 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000443 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000444 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner31a09842008-11-12 08:04:58 +0000445
446 // C99 6.8.5p2/p4: The first substatement is executed if the expression
447 // compares unequal to 0. The condition must be a scalar type.
448 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
449
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 EmitBlock(ForBody);
451 } else {
452 // Treat it as a non-zero constant. Don't even create a new block for the
453 // body, just fall into it.
454 }
455
Chris Lattnerda138702007-07-16 21:28:45 +0000456 // If the for loop doesn't have an increment we can just use the
457 // condition as the continue block.
458 llvm::BasicBlock *ContinueBlock;
459 if (S.getInc())
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000460 ContinueBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000461 else
462 ContinueBlock = CondBlock;
463
464 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000465 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
Mike Stump3e9da662009-02-07 23:02:10 +0000466
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 // If the condition is true, execute the body of the for stmt.
468 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000469
Anders Carlssone4b6d342009-02-10 05:52:02 +0000470 BreakContinueStack.pop_back();
Chris Lattnerda138702007-07-16 21:28:45 +0000471
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000473 if (S.getInc()) {
474 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000475 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000476 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000477
478 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000479 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000480
Chris Lattnerda138702007-07-16 21:28:45 +0000481 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000482 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000483}
484
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000485void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
486 if (RV.isScalar()) {
487 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
488 } else if (RV.isAggregate()) {
489 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
490 } else {
491 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
492 }
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000493 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000494}
495
Reid Spencer5f016e22007-07-11 17:01:13 +0000496/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
497/// if the function returns void, or may be missing one if the function returns
498/// non-void. Fun stuff :).
499void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 // Emit the result value, even if unused, to evalute the side effects.
501 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000502
503 // FIXME: Clean this up by using an LValue for ReturnTemp,
504 // EmitStoreThroughLValue, and EmitAnyExpr.
505 if (!ReturnValue) {
506 // Make sure not to return anything, but evaluate the expression
507 // for side effects.
508 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000509 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000511 // Do nothing (return value is left uninitialized)
Eli Friedmand54b6ac2009-05-27 04:56:12 +0000512 } else if (FnRetTy->isReferenceType()) {
513 // If this function returns a reference, take the address of the expression
514 // rather than the value.
515 Builder.CreateStore(EmitLValue(RV).getAddress(), ReturnValue);
Chris Lattner4b0029d2007-08-26 07:14:44 +0000516 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000517 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000518 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000519 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000521 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000522 }
Eli Friedman144ac612008-05-22 01:22:33 +0000523
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000524 EmitBranchThroughCleanup(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000525}
526
527void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000528 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
529 I != E; ++I)
530 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000531}
Chris Lattnerda138702007-07-16 21:28:45 +0000532
Daniel Dunbar09124252008-11-12 08:21:33 +0000533void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000534 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
535
Daniel Dunbar09124252008-11-12 08:21:33 +0000536 // If this code is reachable then emit a stop point (if generating
537 // debug info). We have to do this ourselves because we are on the
538 // "simple" statement path.
539 if (HaveInsertPoint())
540 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000541
Chris Lattnerda138702007-07-16 21:28:45 +0000542 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000543 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000544}
545
Daniel Dunbar09124252008-11-12 08:21:33 +0000546void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000547 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
548
Daniel Dunbar09124252008-11-12 08:21:33 +0000549 // If this code is reachable then emit a stop point (if generating
550 // debug info). We have to do this ourselves because we are on the
551 // "simple" statement path.
552 if (HaveInsertPoint())
553 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000554
Chris Lattnerda138702007-07-16 21:28:45 +0000555 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000556 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000557}
Devang Patel51b09f22007-10-04 23:45:31 +0000558
Devang Patelc049e4f2007-10-08 20:57:48 +0000559/// EmitCaseStmtRange - If case statement range is not too big then
560/// add multiple cases to switch instruction, one for each value within
561/// the range. If range is too big then emit "if" condition check.
562void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000563 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000564
Anders Carlsson51fe9962008-11-22 21:04:56 +0000565 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
566 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000567
Daniel Dunbar16f23572008-07-25 01:11:38 +0000568 // Emit the code for this case. We do this first to make sure it is
569 // properly chained from our predecessor before generating the
570 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000571 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000572 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
573 EmitStmt(S.getSubStmt());
574
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000575 // If range is empty, do nothing.
576 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
577 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000578
579 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000580 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000581 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
582 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000583 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Owen Anderson9cdd6372009-07-16 18:09:38 +0000584 SwitchInsn->addCase(VMContext.getConstantInt(LHS), CaseDest);
Devang Patel2d79d0f2007-10-05 20:54:07 +0000585 LHS++;
586 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000587 return;
588 }
589
Daniel Dunbar16f23572008-07-25 01:11:38 +0000590 // The range is too big. Emit "if" condition into a new block,
591 // making sure to save and restore the current insertion point.
592 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000593
Daniel Dunbar16f23572008-07-25 01:11:38 +0000594 // Push this test onto the chain of range checks (which terminates
595 // in the default basic block). The switch's default will be changed
596 // to the top of this chain after switch emission is complete.
597 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000598 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000599
Daniel Dunbar16f23572008-07-25 01:11:38 +0000600 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
601 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000602
603 // Emit range check.
604 llvm::Value *Diff =
Owen Anderson9cdd6372009-07-16 18:09:38 +0000605 Builder.CreateSub(SwitchInsn->getCondition(), VMContext.getConstantInt(LHS),
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000606 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000607 llvm::Value *Cond =
Owen Anderson9cdd6372009-07-16 18:09:38 +0000608 Builder.CreateICmpULE(Diff, VMContext.getConstantInt(Range), "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000609 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
610
Daniel Dunbar16f23572008-07-25 01:11:38 +0000611 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000612 if (RestoreBB)
613 Builder.SetInsertPoint(RestoreBB);
614 else
615 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000616}
617
618void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
619 if (S.getRHS()) {
620 EmitCaseStmtRange(S);
621 return;
622 }
623
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000624 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000625 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000626 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Owen Anderson9cdd6372009-07-16 18:09:38 +0000627 SwitchInsn->addCase(VMContext.getConstantInt(CaseVal), CaseDest);
Chris Lattner5512f282009-03-04 04:46:18 +0000628
629 // Recursively emitting the statement is acceptable, but is not wonderful for
630 // code where we have many case statements nested together, i.e.:
631 // case 1:
632 // case 2:
633 // case 3: etc.
634 // Handling this recursively will create a new block for each case statement
635 // that falls through to the next case which is IR intensive. It also causes
636 // deep recursion which can run into stack depth limitations. Handle
637 // sequential non-range case statements specially.
638 const CaseStmt *CurCase = &S;
639 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
640
641 // Otherwise, iteratively add consequtive cases to this switch stmt.
642 while (NextCase && NextCase->getRHS() == 0) {
643 CurCase = NextCase;
644 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
Owen Anderson9cdd6372009-07-16 18:09:38 +0000645 SwitchInsn->addCase(VMContext.getConstantInt(CaseVal), CaseDest);
Chris Lattner5512f282009-03-04 04:46:18 +0000646
647 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
648 }
649
650 // Normal default recursion for non-cases.
651 EmitStmt(CurCase->getSubStmt());
Devang Patel51b09f22007-10-04 23:45:31 +0000652}
653
654void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000655 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000656 assert(DefaultBlock->empty() &&
657 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000658 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000659 EmitStmt(S.getSubStmt());
660}
661
662void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
663 llvm::Value *CondV = EmitScalarExpr(S.getCond());
664
665 // Handle nested switch statements.
666 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000667 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000668
Daniel Dunbar16f23572008-07-25 01:11:38 +0000669 // Create basic block to hold stuff that comes after switch
670 // statement. We also need to create a default block now so that
671 // explicit case ranges tests can have a place to jump to on
672 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000673 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
674 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000675 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
676 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000677
Daniel Dunbar09124252008-11-12 08:21:33 +0000678 // Clear the insertion point to indicate we are in unreachable code.
679 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000680
Devang Patele9b8c0a2007-10-30 20:59:40 +0000681 // All break statements jump to NextBlock. If BreakContinueStack is non empty
682 // then reuse last ContinueBlock.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000683 llvm::BasicBlock *ContinueBlock = 0;
684 if (!BreakContinueStack.empty())
Devang Patel51b09f22007-10-04 23:45:31 +0000685 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000686
Mike Stump3e9da662009-02-07 23:02:10 +0000687 // Ensure any vlas created between there and here, are undone
Anders Carlssone4b6d342009-02-10 05:52:02 +0000688 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
Devang Patel51b09f22007-10-04 23:45:31 +0000689
690 // Emit switch body.
691 EmitStmt(S.getBody());
Anders Carlssone4b6d342009-02-10 05:52:02 +0000692
693 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +0000694
Daniel Dunbar16f23572008-07-25 01:11:38 +0000695 // Update the default block in case explicit case range tests have
696 // been chained on top.
697 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000698
Daniel Dunbar16f23572008-07-25 01:11:38 +0000699 // If a default was never emitted then reroute any jumps to it and
700 // discard.
701 if (!DefaultBlock->getParent()) {
702 DefaultBlock->replaceAllUsesWith(NextBlock);
703 delete DefaultBlock;
704 }
Devang Patel51b09f22007-10-04 23:45:31 +0000705
Daniel Dunbar16f23572008-07-25 01:11:38 +0000706 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000707 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000708
Devang Patel51b09f22007-10-04 23:45:31 +0000709 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000710 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000711}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000712
Chris Lattner2819fa82009-04-26 17:57:12 +0000713static std::string
714SimplifyConstraint(const char *Constraint, TargetInfo &Target,
715 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000716 std::string Result;
717
718 while (*Constraint) {
719 switch (*Constraint) {
720 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000721 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000722 break;
723 // Ignore these
724 case '*':
725 case '?':
726 case '!':
727 break;
728 case 'g':
729 Result += "imr";
730 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000731 case '[': {
Chris Lattner2819fa82009-04-26 17:57:12 +0000732 assert(OutCons &&
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000733 "Must pass output names to constraints with a symbolic name");
734 unsigned Index;
735 bool result = Target.resolveSymbolicName(Constraint,
Chris Lattner2819fa82009-04-26 17:57:12 +0000736 &(*OutCons)[0],
737 OutCons->size(), Index);
Chris Lattner53637652009-01-21 07:35:26 +0000738 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000739 Result += llvm::utostr(Index);
740 break;
741 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000742 }
743
744 Constraint++;
745 }
746
747 return Result;
748}
749
Anders Carlsson63471722009-01-11 19:32:54 +0000750llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
Daniel Dunbarb84e8a62009-05-04 06:56:16 +0000751 const TargetInfo::ConstraintInfo &Info,
Anders Carlsson63471722009-01-11 19:32:54 +0000752 const Expr *InputExpr,
Chris Lattner63c8b142009-03-10 05:39:21 +0000753 std::string &ConstraintStr) {
Anders Carlsson63471722009-01-11 19:32:54 +0000754 llvm::Value *Arg;
Chris Lattner44def072009-04-26 07:16:29 +0000755 if (Info.allowsRegister() || !Info.allowsMemory()) {
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000756 const llvm::Type *Ty = ConvertType(InputExpr->getType());
757
758 if (Ty->isSingleValueType()) {
Anders Carlsson63471722009-01-11 19:32:54 +0000759 Arg = EmitScalarExpr(InputExpr);
760 } else {
Chris Lattner810f6d52009-03-13 17:38:01 +0000761 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000762 LValue Dest = EmitLValue(InputExpr);
763
764 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
765 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
766 Ty = llvm::IntegerType::get(Size);
767 Ty = llvm::PointerType::getUnqual(Ty);
768
769 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
770 } else {
771 Arg = Dest.getAddress();
772 ConstraintStr += '*';
773 }
Anders Carlsson63471722009-01-11 19:32:54 +0000774 }
775 } else {
Chris Lattner810f6d52009-03-13 17:38:01 +0000776 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
Anders Carlsson63471722009-01-11 19:32:54 +0000777 LValue Dest = EmitLValue(InputExpr);
778 Arg = Dest.getAddress();
779 ConstraintStr += '*';
780 }
781
782 return Arg;
783}
784
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000785void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Chris Lattner458cd9c2009-03-10 23:21:44 +0000786 // Analyze the asm string to decompose it into its pieces. We know that Sema
787 // has already done this, so it is guaranteed to be successful.
788 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +0000789 unsigned DiagOffs;
790 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
Chris Lattner458cd9c2009-03-10 23:21:44 +0000791
792 // Assemble the pieces into the final asm string.
793 std::string AsmString;
794 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
795 if (Pieces[i].isString())
796 AsmString += Pieces[i].getString();
797 else if (Pieces[i].getModifier() == '\0')
798 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
799 else
800 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
801 Pieces[i].getModifier() + '}';
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000802 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000803
Chris Lattner481fef92009-05-03 07:05:00 +0000804 // Get all the output and input constraints together.
805 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
806 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
807
808 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
809 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
810 S.getOutputName(i));
811 bool result = Target.validateOutputConstraint(Info);
812 assert(result && "Failed to parse output constraint"); result=result;
813 OutputConstraintInfos.push_back(Info);
814 }
815
816 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
817 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
818 S.getInputName(i));
Jay Foadbeaaccd2009-05-21 09:52:38 +0000819 bool result = Target.validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattner481fef92009-05-03 07:05:00 +0000820 S.getNumOutputs(),
821 Info); result=result;
822 assert(result && "Failed to parse input constraint");
823 InputConstraintInfos.push_back(Info);
824 }
825
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000826 std::string Constraints;
827
Chris Lattnerede9d902009-05-03 07:53:25 +0000828 std::vector<LValue> ResultRegDests;
829 std::vector<QualType> ResultRegQualTys;
Chris Lattnera077b5c2009-05-03 08:21:20 +0000830 std::vector<const llvm::Type *> ResultRegTypes;
831 std::vector<const llvm::Type *> ResultTruncRegTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000832 std::vector<const llvm::Type*> ArgTypes;
833 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000834
835 // Keep track of inout constraints.
836 std::string InOutConstraints;
837 std::vector<llvm::Value*> InOutArgs;
838 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +0000839
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000840 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +0000841 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
Anders Carlsson03eb5432009-01-27 20:38:24 +0000842
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000843 // Simplify the output constraint.
Chris Lattner481fef92009-05-03 07:05:00 +0000844 std::string OutputConstraint(S.getOutputConstraint(i));
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000845 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000846
Chris Lattner810f6d52009-03-13 17:38:01 +0000847 const Expr *OutExpr = S.getOutputExpr(i);
848 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
849
850 LValue Dest = EmitLValue(OutExpr);
Chris Lattnerede9d902009-05-03 07:53:25 +0000851 if (!Constraints.empty())
Anders Carlssonbad3a942009-05-01 00:16:04 +0000852 Constraints += ',';
853
Chris Lattnera077b5c2009-05-03 08:21:20 +0000854 // If this is a register output, then make the inline asm return it
855 // by-value. If this is a memory result, return the value by-reference.
Chris Lattnerede9d902009-05-03 07:53:25 +0000856 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
Chris Lattnera077b5c2009-05-03 08:21:20 +0000857 Constraints += "=" + OutputConstraint;
Chris Lattnerede9d902009-05-03 07:53:25 +0000858 ResultRegQualTys.push_back(OutExpr->getType());
859 ResultRegDests.push_back(Dest);
Chris Lattnera077b5c2009-05-03 08:21:20 +0000860 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
861 ResultTruncRegTypes.push_back(ResultRegTypes.back());
862
863 // If this output is tied to an input, and if the input is larger, then
864 // we need to set the actual result type of the inline asm node to be the
865 // same as the input type.
866 if (Info.hasMatchingInput()) {
Chris Lattnerebfc9852009-05-03 08:38:58 +0000867 unsigned InputNo;
868 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
869 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
870 if (Input.hasTiedOperand() &&
Chris Lattner0bdaa5b2009-05-03 09:05:53 +0000871 Input.getTiedOperand() == i)
Chris Lattnera077b5c2009-05-03 08:21:20 +0000872 break;
Chris Lattnerebfc9852009-05-03 08:38:58 +0000873 }
874 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
Chris Lattnera077b5c2009-05-03 08:21:20 +0000875
876 QualType InputTy = S.getInputExpr(InputNo)->getType();
877 QualType OutputTy = OutExpr->getType();
878
879 uint64_t InputSize = getContext().getTypeSize(InputTy);
880 if (getContext().getTypeSize(OutputTy) < InputSize) {
881 // Form the asm to return the value as a larger integer type.
882 ResultRegTypes.back() = llvm::IntegerType::get((unsigned)InputSize);
883 }
884 }
885
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000886 } else {
887 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000888 Args.push_back(Dest.getAddress());
Anders Carlssonf39a4212008-02-05 20:01:53 +0000889 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000890 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000891 }
892
Chris Lattner44def072009-04-26 07:16:29 +0000893 if (Info.isReadWrite()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000894 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +0000895
Anders Carlssonf39a4212008-02-05 20:01:53 +0000896 const Expr *InputExpr = S.getOutputExpr(i);
Anders Carlsson63471722009-01-11 19:32:54 +0000897 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Anders Carlssonf39a4212008-02-05 20:01:53 +0000898
Chris Lattner44def072009-04-26 07:16:29 +0000899 if (Info.allowsRegister())
Anders Carlsson9f2505b2009-01-11 21:23:27 +0000900 InOutConstraints += llvm::utostr(i);
901 else
902 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +0000903
Anders Carlssonf39a4212008-02-05 20:01:53 +0000904 InOutArgTypes.push_back(Arg->getType());
905 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +0000906 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000907 }
908
909 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
910
911 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
912 const Expr *InputExpr = S.getInputExpr(i);
913
Chris Lattner481fef92009-05-03 07:05:00 +0000914 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
915
Chris Lattnerede9d902009-05-03 07:53:25 +0000916 if (!Constraints.empty())
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000917 Constraints += ',';
918
919 // Simplify the input constraint.
Chris Lattner481fef92009-05-03 07:05:00 +0000920 std::string InputConstraint(S.getInputConstraint(i));
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000921 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
Chris Lattner2819fa82009-04-26 17:57:12 +0000922 &OutputConstraintInfos);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000923
Anders Carlsson63471722009-01-11 19:32:54 +0000924 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000925
Chris Lattner4df4ee02009-05-03 07:27:51 +0000926 // If this input argument is tied to a larger output result, extend the
927 // input to be the same size as the output. The LLVM backend wants to see
928 // the input and output of a matching constraint be the same size. Note
929 // that GCC does not define what the top bits are here. We use zext because
930 // that is usually cheaper, but LLVM IR should really get an anyext someday.
931 if (Info.hasTiedOperand()) {
932 unsigned Output = Info.getTiedOperand();
933 QualType OutputTy = S.getOutputExpr(Output)->getType();
934 QualType InputTy = InputExpr->getType();
935
936 if (getContext().getTypeSize(OutputTy) >
937 getContext().getTypeSize(InputTy)) {
938 // Use ptrtoint as appropriate so that we can do our extension.
939 if (isa<llvm::PointerType>(Arg->getType()))
940 Arg = Builder.CreatePtrToInt(Arg,
941 llvm::IntegerType::get(LLVMPointerWidth));
942 unsigned OutputSize = (unsigned)getContext().getTypeSize(OutputTy);
943 Arg = Builder.CreateZExt(Arg, llvm::IntegerType::get(OutputSize));
944 }
945 }
946
947
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000948 ArgTypes.push_back(Arg->getType());
949 Args.push_back(Arg);
950 Constraints += InputConstraint;
951 }
952
Anders Carlssonf39a4212008-02-05 20:01:53 +0000953 // Append the "input" part of inout constraints last.
954 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
955 ArgTypes.push_back(InOutArgTypes[i]);
956 Args.push_back(InOutArgs[i]);
957 }
958 Constraints += InOutConstraints;
959
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000960 // Clobbers
961 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
962 std::string Clobber(S.getClobber(i)->getStrData(),
963 S.getClobber(i)->getByteLength());
964
965 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
966
Anders Carlssonea041752008-02-06 00:11:32 +0000967 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000968 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000969
970 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000971 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000972 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000973 }
974
975 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +0000976 std::string MachineClobbers = Target.getClobbers();
977 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000978 if (!Constraints.empty())
979 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +0000980 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000981 }
Anders Carlssonbad3a942009-05-01 00:16:04 +0000982
983 const llvm::Type *ResultType;
Chris Lattnera077b5c2009-05-03 08:21:20 +0000984 if (ResultRegTypes.empty())
Anders Carlssonbad3a942009-05-01 00:16:04 +0000985 ResultType = llvm::Type::VoidTy;
Chris Lattnera077b5c2009-05-03 08:21:20 +0000986 else if (ResultRegTypes.size() == 1)
987 ResultType = ResultRegTypes[0];
Anders Carlssonbad3a942009-05-01 00:16:04 +0000988 else
Chris Lattnera077b5c2009-05-03 08:21:20 +0000989 ResultType = llvm::StructType::get(ResultRegTypes);
Anders Carlssonbad3a942009-05-01 00:16:04 +0000990
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000991 const llvm::FunctionType *FTy =
992 llvm::FunctionType::get(ResultType, ArgTypes, false);
993
994 llvm::InlineAsm *IA =
995 llvm::InlineAsm::get(FTy, AsmString, Constraints,
996 S.isVolatile() || S.getNumOutputs() == 0);
Anders Carlssonbad3a942009-05-01 00:16:04 +0000997 llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end());
Anders Carlssonbc0822b2009-03-02 19:58:15 +0000998 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
999
Chris Lattnera077b5c2009-05-03 08:21:20 +00001000
1001 // Extract all of the register value results from the asm.
1002 std::vector<llvm::Value*> RegResults;
1003 if (ResultRegTypes.size() == 1) {
1004 RegResults.push_back(Result);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001005 } else {
Chris Lattnera077b5c2009-05-03 08:21:20 +00001006 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
Anders Carlssonbad3a942009-05-01 00:16:04 +00001007 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
Chris Lattnera077b5c2009-05-03 08:21:20 +00001008 RegResults.push_back(Tmp);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001009 }
1010 }
Chris Lattnera077b5c2009-05-03 08:21:20 +00001011
1012 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1013 llvm::Value *Tmp = RegResults[i];
1014
1015 // If the result type of the LLVM IR asm doesn't match the result type of
1016 // the expression, do the conversion.
1017 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1018 const llvm::Type *TruncTy = ResultTruncRegTypes[i];
1019 // Truncate the integer result to the right size, note that
1020 // ResultTruncRegTypes can be a pointer.
1021 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
1022 Tmp = Builder.CreateTrunc(Tmp, llvm::IntegerType::get((unsigned)ResSize));
1023
1024 if (Tmp->getType() != TruncTy) {
1025 assert(isa<llvm::PointerType>(TruncTy));
1026 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
1027 }
1028 }
1029
1030 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i],
1031 ResultRegQualTys[i]);
1032 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001033}