blob: bbd546261800d942c2ba452620140dd76d02b20f [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.
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000071 if (!isa<Expr>(S))
Daniel Dunbar488e9932008-08-16 00:56:44 +000072 ErrorUnsupported(S, "statement");
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000073
74 EmitAnyExpr(cast<Expr>(S), 0, false, true);
Mike Stump1eb44332009-09-09 15:08:12 +000075
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000076 // Expression emitters don't handle unreachable blocks yet, so look for one
77 // explicitly here. This handles the common case of a call to a noreturn
78 // function.
79 if (llvm::BasicBlock *CurBB = Builder.GetInsertBlock()) {
80 if (CurBB->empty() && CurBB->use_empty()) {
81 CurBB->eraseFromParent();
82 Builder.ClearInsertionPoint();
83 }
Reid Spencer5f016e22007-07-11 17:01:13 +000084 }
85 break;
Mike Stump1eb44332009-09-09 15:08:12 +000086 case Stmt::IndirectGotoStmtClass:
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000087 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000088
89 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
90 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
91 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
92 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
Mike Stump1eb44332009-09-09 15:08:12 +000093
Reid Spencer5f016e22007-07-11 17:01:13 +000094 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +000095
Devang Patel51b09f22007-10-04 23:45:31 +000096 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000097 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000098
99 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000100 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
Mike Stump1eb44332009-09-09 15:08:12 +0000101 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000102 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +0000103 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
104 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000105 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000106 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000107 break;
108 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000109 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000110 break;
111 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +0000112 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000113 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000114 case Stmt::ObjCForCollectionStmtClass:
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000115 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000116 break;
Anders Carlsson6815e942009-09-27 18:58:34 +0000117
118 case Stmt::CXXTryStmtClass:
119 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
120 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000121 }
122}
123
Daniel Dunbar09124252008-11-12 08:21:33 +0000124bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
125 switch (S->getStmtClass()) {
126 default: return false;
127 case Stmt::NullStmtClass: break;
128 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
Daniel Dunbard286f052009-07-19 06:58:07 +0000129 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbar09124252008-11-12 08:21:33 +0000130 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
131 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
132 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
133 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
134 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
135 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
136 }
137
138 return true;
139}
140
Chris Lattner33793202007-08-31 22:09:40 +0000141/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
142/// this captures the expression result of the last sub-statement and returns it
143/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000144RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
145 llvm::Value *AggLoc, bool isAggVol) {
Chris Lattner7d22bf02009-03-05 08:04:57 +0000146 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
147 "LLVM IR generation of compound statement ('{}')");
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Anders Carlssone896d982009-02-13 08:11:52 +0000149 CGDebugInfo *DI = getDebugInfo();
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000150 if (DI) {
Devang Patelbbd9fa42009-10-06 18:36:08 +0000151 DI->setLocation(S.getLBracLoc());
152 DI->EmitRegionStart(CurFn, Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000153 }
154
Anders Carlssonc71c8452009-02-07 23:50:39 +0000155 // Keep track of the current cleanup stack depth.
Douglas Gregor01234bb2009-11-24 16:43:22 +0000156 CleanupScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Chris Lattner33793202007-08-31 22:09:40 +0000158 for (CompoundStmt::const_body_iterator I = S.body_begin(),
159 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000160 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000161
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000162 if (DI) {
Devang Patelbbd9fa42009-10-06 18:36:08 +0000163 DI->setLocation(S.getLBracLoc());
164 DI->EmitRegionEnd(CurFn, Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000165 }
166
Anders Carlsson17d28a32008-12-12 05:52:00 +0000167 RValue RV;
Mike Stump1eb44332009-09-09 15:08:12 +0000168 if (!GetLast)
Anders Carlsson17d28a32008-12-12 05:52:00 +0000169 RV = RValue::get(0);
170 else {
Mike Stump1eb44332009-09-09 15:08:12 +0000171 // We have to special case labels here. They are statements, but when put
Anders Carlsson17d28a32008-12-12 05:52:00 +0000172 // at the end of a statement expression, they yield the value of their
173 // subexpression. Handle this by walking through all labels we encounter,
174 // emitting them before we evaluate the subexpr.
175 const Stmt *LastStmt = S.body_back();
176 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
177 EmitLabel(*LS);
178 LastStmt = LS->getSubStmt();
179 }
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Anders Carlsson17d28a32008-12-12 05:52:00 +0000181 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Anders Carlsson17d28a32008-12-12 05:52:00 +0000183 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
184 }
185
Anders Carlsson17d28a32008-12-12 05:52:00 +0000186 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000187}
188
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000189void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
190 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000192 // If there is a cleanup stack, then we it isn't worth trying to
193 // simplify this block (we would need to remove it from the scope map
194 // and cleanup entry).
195 if (!CleanupEntries.empty())
196 return;
197
198 // Can only simplify direct branches.
199 if (!BI || !BI->isUnconditional())
200 return;
201
202 BB->replaceAllUsesWith(BI->getSuccessor(0));
203 BI->eraseFromParent();
204 BB->eraseFromParent();
205}
206
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000207void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000208 // Fall out of the current block (if necessary).
209 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000210
211 if (IsFinished && BB->use_empty()) {
212 delete BB;
213 return;
214 }
215
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000216 // If necessary, associate the block with the cleanup stack size.
217 if (!CleanupEntries.empty()) {
Anders Carlsson22ab8d82009-02-10 22:50:24 +0000218 // Check if the basic block has already been inserted.
219 BlockScopeMap::iterator I = BlockScopes.find(BB);
220 if (I != BlockScopes.end()) {
221 assert(I->second == CleanupEntries.size() - 1);
222 } else {
223 BlockScopes[BB] = CleanupEntries.size() - 1;
224 CleanupEntries.back().Blocks.push_back(BB);
225 }
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000226 }
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Reid Spencer5f016e22007-07-11 17:01:13 +0000228 CurFn->getBasicBlockList().push_back(BB);
229 Builder.SetInsertPoint(BB);
230}
231
Daniel Dunbard57a8712008-11-11 09:41:28 +0000232void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
233 // Emit a branch from the current block to the target one if this
234 // was a real block. If this was just a fall-through block after a
235 // terminator, don't emit it.
236 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
237
238 if (!CurBB || CurBB->getTerminator()) {
239 // If there is no insert point or the previous block is already
240 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000241 } else {
242 // Otherwise, create a fall-through branch.
243 Builder.CreateBr(Target);
244 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000245
246 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000247}
248
Mike Stumpec9771d2009-02-08 09:22:19 +0000249void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Anders Carlssonfa1f7562009-02-10 06:07:49 +0000250 EmitBlock(getBasicBlockForLabel(&S));
Chris Lattner91d723d2008-07-26 20:23:23 +0000251}
252
253
254void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
255 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 EmitStmt(S.getSubStmt());
257}
258
259void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000260 // If this code is reachable then emit a stop point (if generating
261 // debug info). We have to do this ourselves because we are on the
262 // "simple" statement path.
263 if (HaveInsertPoint())
264 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000265
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000266 EmitBranchThroughCleanup(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000267}
268
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000269
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000270void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Chris Lattner49c952f2009-11-06 18:10:47 +0000271 // Ensure that we have an i8* for our PHI node.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000272 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
273 llvm::Type::getInt8PtrTy(VMContext),
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000274 "addr");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000275 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
276
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000277
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000278 // Get the basic block for the indirect goto.
279 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
280
281 // The first instruction in the block has to be the PHI for the switch dest,
282 // add an entry for this branch.
283 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
284
285 EmitBranch(IndGotoBB);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000286}
287
Chris Lattner62b72f62008-11-11 07:24:28 +0000288void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000289 // C99 6.8.4.1: The first substatement is executed if the expression compares
290 // unequal to 0. The condition must be a scalar type.
Douglas Gregor01234bb2009-11-24 16:43:22 +0000291 CleanupScope ConditionScope(*this);
292
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000293 if (S.getConditionVariable())
Douglas Gregor01234bb2009-11-24 16:43:22 +0000294 EmitLocalBlockVarDecl(*S.getConditionVariable());
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Chris Lattner9bc47e22008-11-12 07:46:33 +0000296 // If the condition constant folds and can be elided, try to avoid emitting
297 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000298 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000299 // Figure out which block (then or else) is executed.
300 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000301 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000302 std::swap(Executed, Skipped);
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Chris Lattner62b72f62008-11-11 07:24:28 +0000304 // If the skipped block has no labels in it, just emit the executed block.
305 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000306 if (!ContainsLabel(Skipped)) {
Douglas Gregor01234bb2009-11-24 16:43:22 +0000307 if (Executed) {
308 CleanupScope ExecutedScope(*this);
Chris Lattner62b72f62008-11-11 07:24:28 +0000309 EmitStmt(Executed);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000310 }
Chris Lattner62b72f62008-11-11 07:24:28 +0000311 return;
312 }
313 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000314
315 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
316 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000317 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
318 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
319 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000320 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000321 ElseBlock = createBasicBlock("if.else");
322 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 // Emit the 'then' code.
Douglas Gregor01234bb2009-11-24 16:43:22 +0000325 EmitBlock(ThenBlock);
326 {
327 CleanupScope ThenScope(*this);
328 EmitStmt(S.getThen());
329 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000330 EmitBranch(ContBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Reid Spencer5f016e22007-07-11 17:01:13 +0000332 // Emit the 'else' code if present.
333 if (const Stmt *Else = S.getElse()) {
334 EmitBlock(ElseBlock);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000335 {
336 CleanupScope ElseScope(*this);
337 EmitStmt(Else);
338 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000339 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 }
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Reid Spencer5f016e22007-07-11 17:01:13 +0000342 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000343 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000344}
345
346void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 // Emit the header for the loop, insert it, which will create an uncond br to
348 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000349 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 EmitBlock(LoopHeader);
Mike Stump72cac2c2009-02-07 18:08:12 +0000351
352 // Create an exit block for when the condition fails, create a block for the
353 // body of the loop.
354 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
355 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
Douglas Gregor5656e142009-11-24 21:15:44 +0000356 llvm::BasicBlock *CleanupBlock = 0;
357 llvm::BasicBlock *EffectiveExitBlock = ExitBlock;
Mike Stump72cac2c2009-02-07 18:08:12 +0000358
359 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000360 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Douglas Gregor5656e142009-11-24 21:15:44 +0000362 // C++ [stmt.while]p2:
363 // When the condition of a while statement is a declaration, the
364 // scope of the variable that is declared extends from its point
365 // of declaration (3.3.2) to the end of the while statement.
366 // [...]
367 // The object created in a condition is destroyed and created
368 // with each iteration of the loop.
369 CleanupScope ConditionScope(*this);
370
371 if (S.getConditionVariable()) {
372 EmitLocalBlockVarDecl(*S.getConditionVariable());
373
374 // If this condition variable requires cleanups, create a basic
375 // block to handle those cleanups.
376 if (ConditionScope.requiresCleanups()) {
377 CleanupBlock = createBasicBlock("while.cleanup");
378 EffectiveExitBlock = CleanupBlock;
379 }
380 }
381
Mike Stump16b16202009-02-07 17:18:33 +0000382 // Evaluate the conditional in the while header. C99 6.8.5.1: The
383 // evaluation of the controlling expression takes place before each
384 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000385 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Douglas Gregor5656e142009-11-24 21:15:44 +0000386
Devang Patel2c30d8f2007-10-09 20:51:27 +0000387 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000388 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000389 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000390 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel2c30d8f2007-10-09 20:51:27 +0000391 if (C->isOne())
392 EmitBoolCondBranch = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000395 if (EmitBoolCondBranch)
Douglas Gregor5656e142009-11-24 21:15:44 +0000396 Builder.CreateCondBr(BoolCondVal, LoopBody, EffectiveExitBlock);
397
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 // Emit the loop body.
Douglas Gregor5656e142009-11-24 21:15:44 +0000399 {
400 CleanupScope BodyScope(*this);
401 EmitBlock(LoopBody);
402 EmitStmt(S.getBody());
403 }
Chris Lattnerda138702007-07-16 21:28:45 +0000404
Mike Stump1eb44332009-09-09 15:08:12 +0000405 BreakContinueStack.pop_back();
406
Douglas Gregor5656e142009-11-24 21:15:44 +0000407 if (CleanupBlock) {
408 // If we have a cleanup block, jump there to perform cleanups
409 // before looping.
410 EmitBranch(CleanupBlock);
411
412 // Emit the cleanup block, performing cleanups for the condition
413 // and then jumping to either the loop header or the exit block.
414 EmitBlock(CleanupBlock);
415 ConditionScope.ForceCleanup();
416 Builder.CreateCondBr(BoolCondVal, LoopHeader, ExitBlock);
417 } else {
418 // Cycle to the condition.
419 EmitBranch(LoopHeader);
420 }
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000423 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000424
Douglas Gregor5656e142009-11-24 21:15:44 +0000425
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000426 // The LoopHeader typically is just a branch if we skipped emitting
427 // a branch, try to erase it.
Douglas Gregor5656e142009-11-24 21:15:44 +0000428 if (!EmitBoolCondBranch && !CleanupBlock)
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000429 SimplifyForwardingBlocks(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000430}
431
432void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 // Emit the body for the loop, insert it, which will create an uncond br to
434 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000435 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
436 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000437 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000438
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000439 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Chris Lattnerda138702007-07-16 21:28:45 +0000441 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000442 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Reid Spencer5f016e22007-07-11 17:01:13 +0000444 // Emit the body of the loop into the block.
445 EmitStmt(S.getBody());
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Anders Carlssone4b6d342009-02-10 05:52:02 +0000447 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Chris Lattnerda138702007-07-16 21:28:45 +0000449 EmitBlock(DoCond);
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
452 // after each execution of the loop body."
Mike Stump1eb44332009-09-09 15:08:12 +0000453
Reid Spencer5f016e22007-07-11 17:01:13 +0000454 // Evaluate the conditional in the while header.
455 // C99 6.8.5p2/p4: The first substatement is executed if the expression
456 // compares unequal to 0. The condition must be a scalar type.
457 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000458
459 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
460 // to correctly handle break/continue though.
461 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000462 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel05f6e6b2007-10-09 20:33:39 +0000463 if (C->isZero())
464 EmitBoolCondBranch = false;
465
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000467 if (EmitBoolCondBranch)
468 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 // Emit the exit block.
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000471 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000472
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000473 // The DoCond block typically is just a branch if we skipped
474 // emitting a branch, try to erase it.
475 if (!EmitBoolCondBranch)
476 SimplifyForwardingBlocks(DoCond);
Reid Spencer5f016e22007-07-11 17:01:13 +0000477}
478
479void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000480 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
481 // which contains a continue/break?
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000482 CleanupScope ForScope(*this);
Chris Lattnerda138702007-07-16 21:28:45 +0000483
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 // Evaluate the first part before the loop.
485 if (S.getInit())
486 EmitStmt(S.getInit());
487
488 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000489 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
490 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Douglas Gregord9752062009-11-25 01:51:31 +0000491 llvm::BasicBlock *IncBlock = 0;
492 llvm::BasicBlock *CondCleanup = 0;
493 llvm::BasicBlock *EffectiveExitBlock = AfterFor;
Reid Spencer5f016e22007-07-11 17:01:13 +0000494 EmitBlock(CondBlock);
495
Douglas Gregord9752062009-11-25 01:51:31 +0000496 // Create a cleanup scope for the condition variable cleanups.
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000497 CleanupScope ConditionScope(*this);
498
Douglas Gregord9752062009-11-25 01:51:31 +0000499 llvm::Value *BoolCondVal = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 if (S.getCond()) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000501 // If the for statement has a condition scope, emit the local variable
502 // declaration.
Douglas Gregord9752062009-11-25 01:51:31 +0000503 if (S.getConditionVariable()) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000504 EmitLocalBlockVarDecl(*S.getConditionVariable());
Douglas Gregord9752062009-11-25 01:51:31 +0000505
506 if (ConditionScope.requiresCleanups()) {
507 CondCleanup = createBasicBlock("for.cond.cleanup");
508 EffectiveExitBlock = CondCleanup;
509 }
510 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000511
Reid Spencer5f016e22007-07-11 17:01:13 +0000512 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000513 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Chris Lattner31a09842008-11-12 08:04:58 +0000515 // C99 6.8.5p2/p4: The first substatement is executed if the expression
516 // compares unequal to 0. The condition must be a scalar type.
Douglas Gregord9752062009-11-25 01:51:31 +0000517 BoolCondVal = EvaluateExprAsBool(S.getCond());
518 Builder.CreateCondBr(BoolCondVal, ForBody, EffectiveExitBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000519
520 EmitBlock(ForBody);
Reid Spencer5f016e22007-07-11 17:01:13 +0000521 } else {
522 // Treat it as a non-zero constant. Don't even create a new block for the
523 // body, just fall into it.
524 }
525
Mike Stump1eb44332009-09-09 15:08:12 +0000526 // If the for loop doesn't have an increment we can just use the
Chris Lattnerda138702007-07-16 21:28:45 +0000527 // condition as the continue block.
528 llvm::BasicBlock *ContinueBlock;
529 if (S.getInc())
Douglas Gregord9752062009-11-25 01:51:31 +0000530 ContinueBlock = IncBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000531 else
Mike Stump1eb44332009-09-09 15:08:12 +0000532 ContinueBlock = CondBlock;
533
Chris Lattnerda138702007-07-16 21:28:45 +0000534 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000535 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
Mike Stump3e9da662009-02-07 23:02:10 +0000536
Reid Spencer5f016e22007-07-11 17:01:13 +0000537 // If the condition is true, execute the body of the for stmt.
Devang Patelbbd9fa42009-10-06 18:36:08 +0000538 CGDebugInfo *DI = getDebugInfo();
539 if (DI) {
540 DI->setLocation(S.getSourceRange().getBegin());
541 DI->EmitRegionStart(CurFn, Builder);
542 }
Douglas Gregord9752062009-11-25 01:51:31 +0000543
544 {
545 // Create a separate cleanup scope for the body, in case it is not
546 // a compound statement.
547 CleanupScope BodyScope(*this);
548 EmitStmt(S.getBody());
549 }
Chris Lattnerda138702007-07-16 21:28:45 +0000550
Anders Carlssone4b6d342009-02-10 05:52:02 +0000551 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000554 if (S.getInc()) {
Douglas Gregord9752062009-11-25 01:51:31 +0000555 EmitBlock(IncBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000556 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000557 }
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 // Finally, branch back up to the condition for the next iteration.
Douglas Gregord9752062009-11-25 01:51:31 +0000560 if (CondCleanup) {
561 // Branch to the cleanup block.
562 EmitBranch(CondCleanup);
563
564 // Emit the cleanup block, which branches back to the loop body or
565 // outside of the for statement once it is done.
566 EmitBlock(CondCleanup);
567 ConditionScope.ForceCleanup();
568 Builder.CreateCondBr(BoolCondVal, CondBlock, AfterFor);
569 } else
570 EmitBranch(CondBlock);
Devang Patelbbd9fa42009-10-06 18:36:08 +0000571 if (DI) {
572 DI->setLocation(S.getSourceRange().getEnd());
573 DI->EmitRegionEnd(CurFn, Builder);
574 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000575
Chris Lattnerda138702007-07-16 21:28:45 +0000576 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000577 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000578}
579
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000580void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
581 if (RV.isScalar()) {
582 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
583 } else if (RV.isAggregate()) {
584 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
585 } else {
586 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
587 }
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000588 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000589}
590
Reid Spencer5f016e22007-07-11 17:01:13 +0000591/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
592/// if the function returns void, or may be missing one if the function returns
593/// non-void. Fun stuff :).
594void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 // Emit the result value, even if unused, to evalute the side effects.
596 const Expr *RV = S.getRetValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000597
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000598 // FIXME: Clean this up by using an LValue for ReturnTemp,
599 // EmitStoreThroughLValue, and EmitAnyExpr.
600 if (!ReturnValue) {
601 // Make sure not to return anything, but evaluate the expression
602 // for side effects.
603 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000604 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000605 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000606 // Do nothing (return value is left uninitialized)
Eli Friedmand54b6ac2009-05-27 04:56:12 +0000607 } else if (FnRetTy->isReferenceType()) {
608 // If this function returns a reference, take the address of the expression
609 // rather than the value.
610 Builder.CreateStore(EmitLValue(RV).getAddress(), ReturnValue);
Chris Lattner4b0029d2007-08-26 07:14:44 +0000611 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000612 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000613 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000614 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000615 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000616 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000617 }
Eli Friedman144ac612008-05-22 01:22:33 +0000618
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000619 EmitBranchThroughCleanup(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000620}
621
622void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Daniel Dunbar25b6ebf2009-07-19 07:03:11 +0000623 // As long as debug info is modeled with instructions, we have to ensure we
624 // have a place to insert here and write the stop point here.
625 if (getDebugInfo()) {
626 EnsureInsertPoint();
627 EmitStopPoint(&S);
628 }
629
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000630 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
631 I != E; ++I)
632 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000633}
Chris Lattnerda138702007-07-16 21:28:45 +0000634
Daniel Dunbar09124252008-11-12 08:21:33 +0000635void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000636 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
637
Daniel Dunbar09124252008-11-12 08:21:33 +0000638 // If this code is reachable then emit a stop point (if generating
639 // debug info). We have to do this ourselves because we are on the
640 // "simple" statement path.
641 if (HaveInsertPoint())
642 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000643
Chris Lattnerda138702007-07-16 21:28:45 +0000644 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000645 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000646}
647
Daniel Dunbar09124252008-11-12 08:21:33 +0000648void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000649 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
650
Daniel Dunbar09124252008-11-12 08:21:33 +0000651 // If this code is reachable then emit a stop point (if generating
652 // debug info). We have to do this ourselves because we are on the
653 // "simple" statement path.
654 if (HaveInsertPoint())
655 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000656
Chris Lattnerda138702007-07-16 21:28:45 +0000657 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000658 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000659}
Devang Patel51b09f22007-10-04 23:45:31 +0000660
Devang Patelc049e4f2007-10-08 20:57:48 +0000661/// EmitCaseStmtRange - If case statement range is not too big then
662/// add multiple cases to switch instruction, one for each value within
663/// the range. If range is too big then emit "if" condition check.
664void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000665 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000666
Anders Carlsson51fe9962008-11-22 21:04:56 +0000667 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
668 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000669
Daniel Dunbar16f23572008-07-25 01:11:38 +0000670 // Emit the code for this case. We do this first to make sure it is
671 // properly chained from our predecessor before generating the
672 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000673 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000674 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
675 EmitStmt(S.getSubStmt());
676
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000677 // If range is empty, do nothing.
678 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
679 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000680
681 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000682 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000683 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
684 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000685 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000686 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, LHS), CaseDest);
Devang Patel2d79d0f2007-10-05 20:54:07 +0000687 LHS++;
688 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000689 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000690 }
691
Daniel Dunbar16f23572008-07-25 01:11:38 +0000692 // The range is too big. Emit "if" condition into a new block,
693 // making sure to save and restore the current insertion point.
694 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000695
Daniel Dunbar16f23572008-07-25 01:11:38 +0000696 // Push this test onto the chain of range checks (which terminates
697 // in the default basic block). The switch's default will be changed
698 // to the top of this chain after switch emission is complete.
699 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000700 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000701
Daniel Dunbar16f23572008-07-25 01:11:38 +0000702 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
703 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000704
705 // Emit range check.
Mike Stump1eb44332009-09-09 15:08:12 +0000706 llvm::Value *Diff =
707 Builder.CreateSub(SwitchInsn->getCondition(),
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000708 llvm::ConstantInt::get(VMContext, LHS), "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000709 llvm::Value *Cond =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000710 Builder.CreateICmpULE(Diff,
711 llvm::ConstantInt::get(VMContext, Range), "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000712 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
713
Daniel Dunbar16f23572008-07-25 01:11:38 +0000714 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000715 if (RestoreBB)
716 Builder.SetInsertPoint(RestoreBB);
717 else
718 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000719}
720
721void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
722 if (S.getRHS()) {
723 EmitCaseStmtRange(S);
724 return;
725 }
Mike Stump1eb44332009-09-09 15:08:12 +0000726
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000727 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000728 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000729 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000730 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Chris Lattner5512f282009-03-04 04:46:18 +0000732 // Recursively emitting the statement is acceptable, but is not wonderful for
733 // code where we have many case statements nested together, i.e.:
734 // case 1:
735 // case 2:
736 // case 3: etc.
737 // Handling this recursively will create a new block for each case statement
738 // that falls through to the next case which is IR intensive. It also causes
739 // deep recursion which can run into stack depth limitations. Handle
740 // sequential non-range case statements specially.
741 const CaseStmt *CurCase = &S;
742 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
743
744 // Otherwise, iteratively add consequtive cases to this switch stmt.
745 while (NextCase && NextCase->getRHS() == 0) {
746 CurCase = NextCase;
747 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000748 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
Chris Lattner5512f282009-03-04 04:46:18 +0000749
750 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
751 }
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Chris Lattner5512f282009-03-04 04:46:18 +0000753 // Normal default recursion for non-cases.
754 EmitStmt(CurCase->getSubStmt());
Devang Patel51b09f22007-10-04 23:45:31 +0000755}
756
757void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000758 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Mike Stump1eb44332009-09-09 15:08:12 +0000759 assert(DefaultBlock->empty() &&
Daniel Dunbar55e87422008-11-11 02:29:29 +0000760 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000761 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000762 EmitStmt(S.getSubStmt());
763}
764
765void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
Douglas Gregord3d53012009-11-24 17:07:59 +0000766 CleanupScope ConditionScope(*this);
767
768 if (S.getConditionVariable())
769 EmitLocalBlockVarDecl(*S.getConditionVariable());
770
Devang Patel51b09f22007-10-04 23:45:31 +0000771 llvm::Value *CondV = EmitScalarExpr(S.getCond());
772
773 // Handle nested switch statements.
774 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000775 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000776
Daniel Dunbar16f23572008-07-25 01:11:38 +0000777 // Create basic block to hold stuff that comes after switch
778 // statement. We also need to create a default block now so that
779 // explicit case ranges tests can have a place to jump to on
780 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000781 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
782 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000783 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
784 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000785
Daniel Dunbar09124252008-11-12 08:21:33 +0000786 // Clear the insertion point to indicate we are in unreachable code.
787 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000788
Devang Patele9b8c0a2007-10-30 20:59:40 +0000789 // All break statements jump to NextBlock. If BreakContinueStack is non empty
790 // then reuse last ContinueBlock.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000791 llvm::BasicBlock *ContinueBlock = 0;
792 if (!BreakContinueStack.empty())
Devang Patel51b09f22007-10-04 23:45:31 +0000793 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000794
Mike Stump3e9da662009-02-07 23:02:10 +0000795 // Ensure any vlas created between there and here, are undone
Anders Carlssone4b6d342009-02-10 05:52:02 +0000796 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
Devang Patel51b09f22007-10-04 23:45:31 +0000797
798 // Emit switch body.
799 EmitStmt(S.getBody());
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Anders Carlssone4b6d342009-02-10 05:52:02 +0000801 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +0000802
Daniel Dunbar16f23572008-07-25 01:11:38 +0000803 // Update the default block in case explicit case range tests have
804 // been chained on top.
805 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Daniel Dunbar16f23572008-07-25 01:11:38 +0000807 // If a default was never emitted then reroute any jumps to it and
808 // discard.
809 if (!DefaultBlock->getParent()) {
810 DefaultBlock->replaceAllUsesWith(NextBlock);
811 delete DefaultBlock;
812 }
Devang Patel51b09f22007-10-04 23:45:31 +0000813
Daniel Dunbar16f23572008-07-25 01:11:38 +0000814 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000815 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000816
Devang Patel51b09f22007-10-04 23:45:31 +0000817 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000818 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000819}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000820
Chris Lattner2819fa82009-04-26 17:57:12 +0000821static std::string
Daniel Dunbar444be732009-11-13 05:51:54 +0000822SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
Chris Lattner2819fa82009-04-26 17:57:12 +0000823 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000824 std::string Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000826 while (*Constraint) {
827 switch (*Constraint) {
828 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000829 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000830 break;
831 // Ignore these
832 case '*':
833 case '?':
834 case '!':
835 break;
836 case 'g':
837 Result += "imr";
838 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000839 case '[': {
Chris Lattner2819fa82009-04-26 17:57:12 +0000840 assert(OutCons &&
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000841 "Must pass output names to constraints with a symbolic name");
842 unsigned Index;
Mike Stump1eb44332009-09-09 15:08:12 +0000843 bool result = Target.resolveSymbolicName(Constraint,
Chris Lattner2819fa82009-04-26 17:57:12 +0000844 &(*OutCons)[0],
845 OutCons->size(), Index);
Chris Lattner53637652009-01-21 07:35:26 +0000846 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000847 Result += llvm::utostr(Index);
848 break;
849 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000850 }
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000852 Constraint++;
853 }
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000855 return Result;
856}
857
Anders Carlsson63471722009-01-11 19:32:54 +0000858llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
Daniel Dunbarb84e8a62009-05-04 06:56:16 +0000859 const TargetInfo::ConstraintInfo &Info,
Anders Carlsson63471722009-01-11 19:32:54 +0000860 const Expr *InputExpr,
Chris Lattner63c8b142009-03-10 05:39:21 +0000861 std::string &ConstraintStr) {
Anders Carlsson63471722009-01-11 19:32:54 +0000862 llvm::Value *Arg;
Mike Stump1eb44332009-09-09 15:08:12 +0000863 if (Info.allowsRegister() || !Info.allowsMemory()) {
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000864 const llvm::Type *Ty = ConvertType(InputExpr->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000865
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000866 if (Ty->isSingleValueType()) {
Anders Carlsson63471722009-01-11 19:32:54 +0000867 Arg = EmitScalarExpr(InputExpr);
868 } else {
Chris Lattner810f6d52009-03-13 17:38:01 +0000869 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000870 LValue Dest = EmitLValue(InputExpr);
871
872 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
873 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
Owen Anderson0032b272009-08-13 21:57:51 +0000874 Ty = llvm::IntegerType::get(VMContext, Size);
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000875 Ty = llvm::PointerType::getUnqual(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000877 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
878 } else {
879 Arg = Dest.getAddress();
880 ConstraintStr += '*';
881 }
Anders Carlsson63471722009-01-11 19:32:54 +0000882 }
883 } else {
Chris Lattner810f6d52009-03-13 17:38:01 +0000884 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
Anders Carlsson63471722009-01-11 19:32:54 +0000885 LValue Dest = EmitLValue(InputExpr);
886 Arg = Dest.getAddress();
887 ConstraintStr += '*';
888 }
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Anders Carlsson63471722009-01-11 19:32:54 +0000890 return Arg;
891}
892
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000893void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Chris Lattner458cd9c2009-03-10 23:21:44 +0000894 // Analyze the asm string to decompose it into its pieces. We know that Sema
895 // has already done this, so it is guaranteed to be successful.
896 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +0000897 unsigned DiagOffs;
898 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Chris Lattner458cd9c2009-03-10 23:21:44 +0000900 // Assemble the pieces into the final asm string.
901 std::string AsmString;
902 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
903 if (Pieces[i].isString())
904 AsmString += Pieces[i].getString();
905 else if (Pieces[i].getModifier() == '\0')
906 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
907 else
908 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
909 Pieces[i].getModifier() + '}';
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000910 }
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Chris Lattner481fef92009-05-03 07:05:00 +0000912 // Get all the output and input constraints together.
913 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
914 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
915
Mike Stump1eb44332009-09-09 15:08:12 +0000916 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +0000917 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
918 S.getOutputName(i));
919 bool result = Target.validateOutputConstraint(Info);
920 assert(result && "Failed to parse output constraint"); result=result;
921 OutputConstraintInfos.push_back(Info);
Mike Stump1eb44332009-09-09 15:08:12 +0000922 }
923
Chris Lattner481fef92009-05-03 07:05:00 +0000924 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
925 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
926 S.getInputName(i));
Jay Foadbeaaccd2009-05-21 09:52:38 +0000927 bool result = Target.validateInputConstraint(OutputConstraintInfos.data(),
Chris Lattner481fef92009-05-03 07:05:00 +0000928 S.getNumOutputs(),
929 Info); result=result;
930 assert(result && "Failed to parse input constraint");
931 InputConstraintInfos.push_back(Info);
932 }
Mike Stump1eb44332009-09-09 15:08:12 +0000933
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000934 std::string Constraints;
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Chris Lattnerede9d902009-05-03 07:53:25 +0000936 std::vector<LValue> ResultRegDests;
937 std::vector<QualType> ResultRegQualTys;
Chris Lattnera077b5c2009-05-03 08:21:20 +0000938 std::vector<const llvm::Type *> ResultRegTypes;
939 std::vector<const llvm::Type *> ResultTruncRegTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000940 std::vector<const llvm::Type*> ArgTypes;
941 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000942
943 // Keep track of inout constraints.
944 std::string InOutConstraints;
945 std::vector<llvm::Value*> InOutArgs;
946 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +0000947
Mike Stump1eb44332009-09-09 15:08:12 +0000948 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +0000949 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
Anders Carlsson03eb5432009-01-27 20:38:24 +0000950
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000951 // Simplify the output constraint.
Chris Lattner481fef92009-05-03 07:05:00 +0000952 std::string OutputConstraint(S.getOutputConstraint(i));
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000953 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Chris Lattner810f6d52009-03-13 17:38:01 +0000955 const Expr *OutExpr = S.getOutputExpr(i);
956 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Chris Lattner810f6d52009-03-13 17:38:01 +0000958 LValue Dest = EmitLValue(OutExpr);
Chris Lattnerede9d902009-05-03 07:53:25 +0000959 if (!Constraints.empty())
Anders Carlssonbad3a942009-05-01 00:16:04 +0000960 Constraints += ',';
961
Chris Lattnera077b5c2009-05-03 08:21:20 +0000962 // If this is a register output, then make the inline asm return it
963 // by-value. If this is a memory result, return the value by-reference.
Chris Lattnerede9d902009-05-03 07:53:25 +0000964 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
Chris Lattnera077b5c2009-05-03 08:21:20 +0000965 Constraints += "=" + OutputConstraint;
Chris Lattnerede9d902009-05-03 07:53:25 +0000966 ResultRegQualTys.push_back(OutExpr->getType());
967 ResultRegDests.push_back(Dest);
Chris Lattnera077b5c2009-05-03 08:21:20 +0000968 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
969 ResultTruncRegTypes.push_back(ResultRegTypes.back());
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Chris Lattnera077b5c2009-05-03 08:21:20 +0000971 // If this output is tied to an input, and if the input is larger, then
972 // we need to set the actual result type of the inline asm node to be the
973 // same as the input type.
974 if (Info.hasMatchingInput()) {
Chris Lattnerebfc9852009-05-03 08:38:58 +0000975 unsigned InputNo;
976 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
977 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
978 if (Input.hasTiedOperand() &&
Chris Lattner0bdaa5b2009-05-03 09:05:53 +0000979 Input.getTiedOperand() == i)
Chris Lattnera077b5c2009-05-03 08:21:20 +0000980 break;
Chris Lattnerebfc9852009-05-03 08:38:58 +0000981 }
982 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Chris Lattnera077b5c2009-05-03 08:21:20 +0000984 QualType InputTy = S.getInputExpr(InputNo)->getType();
985 QualType OutputTy = OutExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Chris Lattnera077b5c2009-05-03 08:21:20 +0000987 uint64_t InputSize = getContext().getTypeSize(InputTy);
988 if (getContext().getTypeSize(OutputTy) < InputSize) {
989 // Form the asm to return the value as a larger integer type.
Owen Anderson0032b272009-08-13 21:57:51 +0000990 ResultRegTypes.back() = llvm::IntegerType::get(VMContext, (unsigned)InputSize);
Chris Lattnera077b5c2009-05-03 08:21:20 +0000991 }
992 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000993 } else {
994 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000995 Args.push_back(Dest.getAddress());
Anders Carlssonf39a4212008-02-05 20:01:53 +0000996 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000997 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000998 }
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Chris Lattner44def072009-04-26 07:16:29 +00001000 if (Info.isReadWrite()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +00001001 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +00001002
Anders Carlssonfca93612009-08-04 18:18:36 +00001003 const Expr *InputExpr = S.getOutputExpr(i);
1004 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Chris Lattner44def072009-04-26 07:16:29 +00001006 if (Info.allowsRegister())
Anders Carlsson9f2505b2009-01-11 21:23:27 +00001007 InOutConstraints += llvm::utostr(i);
1008 else
1009 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +00001010
Anders Carlssonfca93612009-08-04 18:18:36 +00001011 InOutArgTypes.push_back(Arg->getType());
1012 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001013 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001014 }
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001016 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001018 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1019 const Expr *InputExpr = S.getInputExpr(i);
1020
Chris Lattner481fef92009-05-03 07:05:00 +00001021 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1022
Chris Lattnerede9d902009-05-03 07:53:25 +00001023 if (!Constraints.empty())
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001024 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001026 // Simplify the input constraint.
Chris Lattner481fef92009-05-03 07:05:00 +00001027 std::string InputConstraint(S.getInputConstraint(i));
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001028 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
Chris Lattner2819fa82009-04-26 17:57:12 +00001029 &OutputConstraintInfos);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001030
Anders Carlsson63471722009-01-11 19:32:54 +00001031 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Chris Lattner4df4ee02009-05-03 07:27:51 +00001033 // If this input argument is tied to a larger output result, extend the
1034 // input to be the same size as the output. The LLVM backend wants to see
1035 // the input and output of a matching constraint be the same size. Note
1036 // that GCC does not define what the top bits are here. We use zext because
1037 // that is usually cheaper, but LLVM IR should really get an anyext someday.
1038 if (Info.hasTiedOperand()) {
1039 unsigned Output = Info.getTiedOperand();
1040 QualType OutputTy = S.getOutputExpr(Output)->getType();
1041 QualType InputTy = InputExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001042
Chris Lattner4df4ee02009-05-03 07:27:51 +00001043 if (getContext().getTypeSize(OutputTy) >
1044 getContext().getTypeSize(InputTy)) {
1045 // Use ptrtoint as appropriate so that we can do our extension.
1046 if (isa<llvm::PointerType>(Arg->getType()))
1047 Arg = Builder.CreatePtrToInt(Arg,
Owen Anderson0032b272009-08-13 21:57:51 +00001048 llvm::IntegerType::get(VMContext, LLVMPointerWidth));
Chris Lattner4df4ee02009-05-03 07:27:51 +00001049 unsigned OutputSize = (unsigned)getContext().getTypeSize(OutputTy);
Owen Anderson0032b272009-08-13 21:57:51 +00001050 Arg = Builder.CreateZExt(Arg, llvm::IntegerType::get(VMContext, OutputSize));
Chris Lattner4df4ee02009-05-03 07:27:51 +00001051 }
1052 }
Mike Stump1eb44332009-09-09 15:08:12 +00001053
1054
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001055 ArgTypes.push_back(Arg->getType());
1056 Args.push_back(Arg);
1057 Constraints += InputConstraint;
1058 }
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Anders Carlssonf39a4212008-02-05 20:01:53 +00001060 // Append the "input" part of inout constraints last.
1061 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1062 ArgTypes.push_back(InOutArgTypes[i]);
1063 Args.push_back(InOutArgs[i]);
1064 }
1065 Constraints += InOutConstraints;
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001067 // Clobbers
1068 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1069 std::string Clobber(S.getClobber(i)->getStrData(),
1070 S.getClobber(i)->getByteLength());
1071
1072 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Anders Carlssonea041752008-02-06 00:11:32 +00001074 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001075 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001076
Anders Carlssonea041752008-02-06 00:11:32 +00001077 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001078 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001079 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001080 }
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001082 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +00001083 std::string MachineClobbers = Target.getClobbers();
1084 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001085 if (!Constraints.empty())
1086 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00001087 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001088 }
Anders Carlssonbad3a942009-05-01 00:16:04 +00001089
1090 const llvm::Type *ResultType;
Chris Lattnera077b5c2009-05-03 08:21:20 +00001091 if (ResultRegTypes.empty())
Owen Anderson0032b272009-08-13 21:57:51 +00001092 ResultType = llvm::Type::getVoidTy(VMContext);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001093 else if (ResultRegTypes.size() == 1)
1094 ResultType = ResultRegTypes[0];
Anders Carlssonbad3a942009-05-01 00:16:04 +00001095 else
Owen Anderson47a434f2009-08-05 23:18:46 +00001096 ResultType = llvm::StructType::get(VMContext, ResultRegTypes);
Mike Stump1eb44332009-09-09 15:08:12 +00001097
1098 const llvm::FunctionType *FTy =
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001099 llvm::FunctionType::get(ResultType, ArgTypes, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001100
1101 llvm::InlineAsm *IA =
1102 llvm::InlineAsm::get(FTy, AsmString, Constraints,
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001103 S.isVolatile() || S.getNumOutputs() == 0);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001104 llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end());
Anders Carlssonbc0822b2009-03-02 19:58:15 +00001105 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
Mike Stump1eb44332009-09-09 15:08:12 +00001106
1107
Chris Lattnera077b5c2009-05-03 08:21:20 +00001108 // Extract all of the register value results from the asm.
1109 std::vector<llvm::Value*> RegResults;
1110 if (ResultRegTypes.size() == 1) {
1111 RegResults.push_back(Result);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001112 } else {
Chris Lattnera077b5c2009-05-03 08:21:20 +00001113 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
Anders Carlssonbad3a942009-05-01 00:16:04 +00001114 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
Chris Lattnera077b5c2009-05-03 08:21:20 +00001115 RegResults.push_back(Tmp);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001116 }
1117 }
Mike Stump1eb44332009-09-09 15:08:12 +00001118
Chris Lattnera077b5c2009-05-03 08:21:20 +00001119 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1120 llvm::Value *Tmp = RegResults[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Chris Lattnera077b5c2009-05-03 08:21:20 +00001122 // If the result type of the LLVM IR asm doesn't match the result type of
1123 // the expression, do the conversion.
1124 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1125 const llvm::Type *TruncTy = ResultTruncRegTypes[i];
1126 // Truncate the integer result to the right size, note that
1127 // ResultTruncRegTypes can be a pointer.
1128 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
Owen Anderson0032b272009-08-13 21:57:51 +00001129 Tmp = Builder.CreateTrunc(Tmp, llvm::IntegerType::get(VMContext, (unsigned)ResSize));
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Chris Lattnera077b5c2009-05-03 08:21:20 +00001131 if (Tmp->getType() != TruncTy) {
1132 assert(isa<llvm::PointerType>(TruncTy));
1133 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
1134 }
1135 }
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Chris Lattnera077b5c2009-05-03 08:21:20 +00001137 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i],
1138 ResultRegQualTys[i]);
1139 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001140}