blob: f51a899e7ffacfe1a1d69ce6962657bd36e86245 [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()) {
Devang Patel60e4fd92010-05-12 00:39:34 +000033 if (isa<DeclStmt>(S))
34 DI->setLocation(S->getLocEnd());
35 else
36 DI->setLocation(S->getLocStart());
Daniel Dunbar09124252008-11-12 08:21:33 +000037 DI->EmitStopPoint(CurFn, Builder);
38 }
39}
40
Reid Spencer5f016e22007-07-11 17:01:13 +000041void CodeGenFunction::EmitStmt(const Stmt *S) {
42 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000043
Daniel Dunbar09124252008-11-12 08:21:33 +000044 // Check if we can handle this without bothering to generate an
45 // insert point or debug info.
46 if (EmitSimpleStmt(S))
47 return;
48
Daniel Dunbard286f052009-07-19 06:58:07 +000049 // Check if we are generating unreachable code.
50 if (!HaveInsertPoint()) {
51 // If so, and the statement doesn't contain a label, then we do not need to
52 // generate actual code. This is safe because (1) the current point is
53 // unreachable, so we don't need to execute the code, and (2) we've already
54 // handled the statements which update internal data structures (like the
55 // local variable map) which could be used by subsequent statements.
56 if (!ContainsLabel(S)) {
57 // Verify that any decl statements were handled as simple, they may be in
58 // scope of subsequent reachable statements.
59 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
60 return;
61 }
62
63 // Otherwise, make a new block to hold the code.
64 EnsureInsertPoint();
65 }
66
Daniel Dunbar09124252008-11-12 08:21:33 +000067 // Generate a stoppoint if we are emitting debug info.
68 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000069
Reid Spencer5f016e22007-07-11 17:01:13 +000070 switch (S->getStmtClass()) {
71 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000072 // Must be an expression in a stmt context. Emit the value (to get
73 // side-effects) and ignore the result.
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000074 if (!isa<Expr>(S))
Daniel Dunbar488e9932008-08-16 00:56:44 +000075 ErrorUnsupported(S, "statement");
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000076
77 EmitAnyExpr(cast<Expr>(S), 0, false, true);
Mike Stump1eb44332009-09-09 15:08:12 +000078
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000079 // Expression emitters don't handle unreachable blocks yet, so look for one
80 // explicitly here. This handles the common case of a call to a noreturn
81 // function.
82 if (llvm::BasicBlock *CurBB = Builder.GetInsertBlock()) {
83 if (CurBB->empty() && CurBB->use_empty()) {
84 CurBB->eraseFromParent();
85 Builder.ClearInsertionPoint();
86 }
Reid Spencer5f016e22007-07-11 17:01:13 +000087 }
88 break;
Mike Stump1eb44332009-09-09 15:08:12 +000089 case Stmt::IndirectGotoStmtClass:
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000090 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000091
92 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
93 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
94 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
95 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Reid Spencer5f016e22007-07-11 17:01:13 +000097 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +000098
Devang Patel51b09f22007-10-04 23:45:31 +000099 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000100 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000101
102 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000103 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
Mike Stump1eb44332009-09-09 15:08:12 +0000104 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000105 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +0000106 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
107 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000108 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000109 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000110 break;
111 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000112 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000113 break;
114 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +0000115 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000116 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000117 case Stmt::ObjCForCollectionStmtClass:
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000118 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000119 break;
Anders Carlsson6815e942009-09-27 18:58:34 +0000120
121 case Stmt::CXXTryStmtClass:
122 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
123 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000124 }
125}
126
Daniel Dunbar09124252008-11-12 08:21:33 +0000127bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
128 switch (S->getStmtClass()) {
129 default: return false;
130 case Stmt::NullStmtClass: break;
131 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
Daniel Dunbard286f052009-07-19 06:58:07 +0000132 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbar09124252008-11-12 08:21:33 +0000133 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
134 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
135 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
136 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
137 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
138 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
139 }
140
141 return true;
142}
143
Chris Lattner33793202007-08-31 22:09:40 +0000144/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
145/// this captures the expression result of the last sub-statement and returns it
146/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000147RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
148 llvm::Value *AggLoc, bool isAggVol) {
Chris Lattner7d22bf02009-03-05 08:04:57 +0000149 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
150 "LLVM IR generation of compound statement ('{}')");
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Anders Carlssone896d982009-02-13 08:11:52 +0000152 CGDebugInfo *DI = getDebugInfo();
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000153 if (DI) {
Devang Patelbbd9fa42009-10-06 18:36:08 +0000154 DI->setLocation(S.getLBracLoc());
155 DI->EmitRegionStart(CurFn, Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000156 }
157
Anders Carlssonc71c8452009-02-07 23:50:39 +0000158 // Keep track of the current cleanup stack depth.
Douglas Gregor01234bb2009-11-24 16:43:22 +0000159 CleanupScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000160
Chris Lattner33793202007-08-31 22:09:40 +0000161 for (CompoundStmt::const_body_iterator I = S.body_begin(),
162 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000163 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000164
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000165 if (DI) {
Devang Patelcd9199e2010-04-13 00:08:43 +0000166 DI->setLocation(S.getRBracLoc());
Devang Patelbbd9fa42009-10-06 18:36:08 +0000167 DI->EmitRegionEnd(CurFn, Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000168 }
169
Anders Carlsson17d28a32008-12-12 05:52:00 +0000170 RValue RV;
Mike Stump1eb44332009-09-09 15:08:12 +0000171 if (!GetLast)
Anders Carlsson17d28a32008-12-12 05:52:00 +0000172 RV = RValue::get(0);
173 else {
Mike Stump1eb44332009-09-09 15:08:12 +0000174 // We have to special case labels here. They are statements, but when put
Anders Carlsson17d28a32008-12-12 05:52:00 +0000175 // at the end of a statement expression, they yield the value of their
176 // subexpression. Handle this by walking through all labels we encounter,
177 // emitting them before we evaluate the subexpr.
178 const Stmt *LastStmt = S.body_back();
179 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
180 EmitLabel(*LS);
181 LastStmt = LS->getSubStmt();
182 }
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Anders Carlsson17d28a32008-12-12 05:52:00 +0000184 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Anders Carlsson17d28a32008-12-12 05:52:00 +0000186 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
187 }
188
Anders Carlsson17d28a32008-12-12 05:52:00 +0000189 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000190}
191
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000192void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
193 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000195 // If there is a cleanup stack, then we it isn't worth trying to
196 // simplify this block (we would need to remove it from the scope map
197 // and cleanup entry).
198 if (!CleanupEntries.empty())
199 return;
200
201 // Can only simplify direct branches.
202 if (!BI || !BI->isUnconditional())
203 return;
204
205 BB->replaceAllUsesWith(BI->getSuccessor(0));
206 BI->eraseFromParent();
207 BB->eraseFromParent();
208}
209
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000210void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
John McCall548ce5e2010-04-21 11:18:06 +0000211 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
212
Daniel Dunbard57a8712008-11-11 09:41:28 +0000213 // Fall out of the current block (if necessary).
214 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000215
216 if (IsFinished && BB->use_empty()) {
217 delete BB;
218 return;
219 }
220
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000221 // If necessary, associate the block with the cleanup stack size.
222 if (!CleanupEntries.empty()) {
Anders Carlsson22ab8d82009-02-10 22:50:24 +0000223 // Check if the basic block has already been inserted.
224 BlockScopeMap::iterator I = BlockScopes.find(BB);
225 if (I != BlockScopes.end()) {
226 assert(I->second == CleanupEntries.size() - 1);
227 } else {
228 BlockScopes[BB] = CleanupEntries.size() - 1;
229 CleanupEntries.back().Blocks.push_back(BB);
230 }
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000231 }
Mike Stump1eb44332009-09-09 15:08:12 +0000232
John McCall839cbaa2010-04-21 10:29:06 +0000233 // Place the block after the current block, if possible, or else at
234 // the end of the function.
John McCall548ce5e2010-04-21 11:18:06 +0000235 if (CurBB && CurBB->getParent())
236 CurFn->getBasicBlockList().insertAfter(CurBB, BB);
John McCall839cbaa2010-04-21 10:29:06 +0000237 else
238 CurFn->getBasicBlockList().push_back(BB);
Reid Spencer5f016e22007-07-11 17:01:13 +0000239 Builder.SetInsertPoint(BB);
240}
241
Daniel Dunbard57a8712008-11-11 09:41:28 +0000242void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
243 // Emit a branch from the current block to the target one if this
244 // was a real block. If this was just a fall-through block after a
245 // terminator, don't emit it.
246 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
247
248 if (!CurBB || CurBB->getTerminator()) {
249 // If there is no insert point or the previous block is already
250 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000251 } else {
252 // Otherwise, create a fall-through branch.
253 Builder.CreateBr(Target);
254 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000255
256 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000257}
258
Mike Stumpec9771d2009-02-08 09:22:19 +0000259void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Anders Carlssonfa1f7562009-02-10 06:07:49 +0000260 EmitBlock(getBasicBlockForLabel(&S));
Chris Lattner91d723d2008-07-26 20:23:23 +0000261}
262
263
264void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
265 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000266 EmitStmt(S.getSubStmt());
267}
268
269void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000270 // If this code is reachable then emit a stop point (if generating
271 // debug info). We have to do this ourselves because we are on the
272 // "simple" statement path.
273 if (HaveInsertPoint())
274 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000275
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000276 EmitBranchThroughCleanup(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000277}
278
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000279
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000280void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Chris Lattner49c952f2009-11-06 18:10:47 +0000281 // Ensure that we have an i8* for our PHI node.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000282 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
283 llvm::Type::getInt8PtrTy(VMContext),
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000284 "addr");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000285 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
286
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000287
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000288 // Get the basic block for the indirect goto.
289 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
290
291 // The first instruction in the block has to be the PHI for the switch dest,
292 // add an entry for this branch.
293 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
294
295 EmitBranch(IndGotoBB);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000296}
297
Chris Lattner62b72f62008-11-11 07:24:28 +0000298void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000299 // C99 6.8.4.1: The first substatement is executed if the expression compares
300 // unequal to 0. The condition must be a scalar type.
Douglas Gregor01234bb2009-11-24 16:43:22 +0000301 CleanupScope ConditionScope(*this);
302
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000303 if (S.getConditionVariable())
Douglas Gregor01234bb2009-11-24 16:43:22 +0000304 EmitLocalBlockVarDecl(*S.getConditionVariable());
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Chris Lattner9bc47e22008-11-12 07:46:33 +0000306 // If the condition constant folds and can be elided, try to avoid emitting
307 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000308 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000309 // Figure out which block (then or else) is executed.
310 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000311 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000312 std::swap(Executed, Skipped);
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Chris Lattner62b72f62008-11-11 07:24:28 +0000314 // If the skipped block has no labels in it, just emit the executed block.
315 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000316 if (!ContainsLabel(Skipped)) {
Douglas Gregor01234bb2009-11-24 16:43:22 +0000317 if (Executed) {
318 CleanupScope ExecutedScope(*this);
Chris Lattner62b72f62008-11-11 07:24:28 +0000319 EmitStmt(Executed);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000320 }
Chris Lattner62b72f62008-11-11 07:24:28 +0000321 return;
322 }
323 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000324
325 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
326 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000327 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
328 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
329 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000330 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000331 ElseBlock = createBasicBlock("if.else");
332 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 // Emit the 'then' code.
Douglas Gregor01234bb2009-11-24 16:43:22 +0000335 EmitBlock(ThenBlock);
336 {
337 CleanupScope ThenScope(*this);
338 EmitStmt(S.getThen());
339 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000340 EmitBranch(ContBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Reid Spencer5f016e22007-07-11 17:01:13 +0000342 // Emit the 'else' code if present.
343 if (const Stmt *Else = S.getElse()) {
344 EmitBlock(ElseBlock);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000345 {
346 CleanupScope ElseScope(*this);
347 EmitStmt(Else);
348 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000349 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 }
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000353 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000354}
355
356void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000357 // Emit the header for the loop, insert it, which will create an uncond br to
358 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000359 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000360 EmitBlock(LoopHeader);
Mike Stump72cac2c2009-02-07 18:08:12 +0000361
362 // Create an exit block for when the condition fails, create a block for the
363 // body of the loop.
364 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
365 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
Douglas Gregor5656e142009-11-24 21:15:44 +0000366 llvm::BasicBlock *CleanupBlock = 0;
367 llvm::BasicBlock *EffectiveExitBlock = ExitBlock;
Mike Stump72cac2c2009-02-07 18:08:12 +0000368
369 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000370 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Douglas Gregor5656e142009-11-24 21:15:44 +0000372 // C++ [stmt.while]p2:
373 // When the condition of a while statement is a declaration, the
374 // scope of the variable that is declared extends from its point
375 // of declaration (3.3.2) to the end of the while statement.
376 // [...]
377 // The object created in a condition is destroyed and created
378 // with each iteration of the loop.
379 CleanupScope ConditionScope(*this);
380
381 if (S.getConditionVariable()) {
382 EmitLocalBlockVarDecl(*S.getConditionVariable());
383
384 // If this condition variable requires cleanups, create a basic
385 // block to handle those cleanups.
386 if (ConditionScope.requiresCleanups()) {
387 CleanupBlock = createBasicBlock("while.cleanup");
388 EffectiveExitBlock = CleanupBlock;
389 }
390 }
391
Mike Stump16b16202009-02-07 17:18:33 +0000392 // Evaluate the conditional in the while header. C99 6.8.5.1: The
393 // evaluation of the controlling expression takes place before each
394 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Douglas Gregor5656e142009-11-24 21:15:44 +0000396
Devang Patel2c30d8f2007-10-09 20:51:27 +0000397 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000399 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000400 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel2c30d8f2007-10-09 20:51:27 +0000401 if (C->isOne())
402 EmitBoolCondBranch = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000405 if (EmitBoolCondBranch)
Douglas Gregor5656e142009-11-24 21:15:44 +0000406 Builder.CreateCondBr(BoolCondVal, LoopBody, EffectiveExitBlock);
407
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 // Emit the loop body.
Douglas Gregor5656e142009-11-24 21:15:44 +0000409 {
410 CleanupScope BodyScope(*this);
411 EmitBlock(LoopBody);
412 EmitStmt(S.getBody());
413 }
Chris Lattnerda138702007-07-16 21:28:45 +0000414
Mike Stump1eb44332009-09-09 15:08:12 +0000415 BreakContinueStack.pop_back();
416
Douglas Gregor5656e142009-11-24 21:15:44 +0000417 if (CleanupBlock) {
418 // If we have a cleanup block, jump there to perform cleanups
419 // before looping.
420 EmitBranch(CleanupBlock);
421
422 // Emit the cleanup block, performing cleanups for the condition
423 // and then jumping to either the loop header or the exit block.
424 EmitBlock(CleanupBlock);
425 ConditionScope.ForceCleanup();
426 Builder.CreateCondBr(BoolCondVal, LoopHeader, ExitBlock);
427 } else {
428 // Cycle to the condition.
429 EmitBranch(LoopHeader);
430 }
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Reid Spencer5f016e22007-07-11 17:01:13 +0000432 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000433 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000434
Douglas Gregor5656e142009-11-24 21:15:44 +0000435
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000436 // The LoopHeader typically is just a branch if we skipped emitting
437 // a branch, try to erase it.
Douglas Gregor5656e142009-11-24 21:15:44 +0000438 if (!EmitBoolCondBranch && !CleanupBlock)
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000439 SimplifyForwardingBlocks(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000440}
441
442void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000443 // Emit the body for the loop, insert it, which will create an uncond br to
444 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000445 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
446 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000447 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000448
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000449 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Chris Lattnerda138702007-07-16 21:28:45 +0000451 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000452 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Mike Stump1eb44332009-09-09 15:08:12 +0000453
Reid Spencer5f016e22007-07-11 17:01:13 +0000454 // Emit the body of the loop into the block.
455 EmitStmt(S.getBody());
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Anders Carlssone4b6d342009-02-10 05:52:02 +0000457 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Chris Lattnerda138702007-07-16 21:28:45 +0000459 EmitBlock(DoCond);
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Reid Spencer5f016e22007-07-11 17:01:13 +0000461 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
462 // after each execution of the loop body."
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Reid Spencer5f016e22007-07-11 17:01:13 +0000464 // Evaluate the conditional in the while header.
465 // C99 6.8.5p2/p4: The first substatement is executed if the expression
466 // compares unequal to 0. The condition must be a scalar type.
467 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000468
469 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
470 // to correctly handle break/continue though.
471 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000472 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel05f6e6b2007-10-09 20:33:39 +0000473 if (C->isZero())
474 EmitBoolCondBranch = false;
475
Reid Spencer5f016e22007-07-11 17:01:13 +0000476 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000477 if (EmitBoolCondBranch)
478 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Reid Spencer5f016e22007-07-11 17:01:13 +0000480 // Emit the exit block.
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000481 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000482
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000483 // The DoCond block typically is just a branch if we skipped
484 // emitting a branch, try to erase it.
485 if (!EmitBoolCondBranch)
486 SimplifyForwardingBlocks(DoCond);
Reid Spencer5f016e22007-07-11 17:01:13 +0000487}
488
489void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
491 // which contains a continue/break?
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000492 CleanupScope ForScope(*this);
Chris Lattnerda138702007-07-16 21:28:45 +0000493
Reid Spencer5f016e22007-07-11 17:01:13 +0000494 // Evaluate the first part before the loop.
495 if (S.getInit())
496 EmitStmt(S.getInit());
497
498 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000499 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
500 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Douglas Gregord9752062009-11-25 01:51:31 +0000501 llvm::BasicBlock *IncBlock = 0;
502 llvm::BasicBlock *CondCleanup = 0;
503 llvm::BasicBlock *EffectiveExitBlock = AfterFor;
Reid Spencer5f016e22007-07-11 17:01:13 +0000504 EmitBlock(CondBlock);
505
Douglas Gregord9752062009-11-25 01:51:31 +0000506 // Create a cleanup scope for the condition variable cleanups.
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000507 CleanupScope ConditionScope(*this);
508
Douglas Gregord9752062009-11-25 01:51:31 +0000509 llvm::Value *BoolCondVal = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 if (S.getCond()) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000511 // If the for statement has a condition scope, emit the local variable
512 // declaration.
Douglas Gregord9752062009-11-25 01:51:31 +0000513 if (S.getConditionVariable()) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000514 EmitLocalBlockVarDecl(*S.getConditionVariable());
Douglas Gregord9752062009-11-25 01:51:31 +0000515
516 if (ConditionScope.requiresCleanups()) {
517 CondCleanup = createBasicBlock("for.cond.cleanup");
518 EffectiveExitBlock = CondCleanup;
519 }
520 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000521
Reid Spencer5f016e22007-07-11 17:01:13 +0000522 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000523 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Chris Lattner31a09842008-11-12 08:04:58 +0000525 // C99 6.8.5p2/p4: The first substatement is executed if the expression
526 // compares unequal to 0. The condition must be a scalar type.
Douglas Gregord9752062009-11-25 01:51:31 +0000527 BoolCondVal = EvaluateExprAsBool(S.getCond());
528 Builder.CreateCondBr(BoolCondVal, ForBody, EffectiveExitBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000529
530 EmitBlock(ForBody);
Reid Spencer5f016e22007-07-11 17:01:13 +0000531 } else {
532 // Treat it as a non-zero constant. Don't even create a new block for the
533 // body, just fall into it.
534 }
535
Mike Stump1eb44332009-09-09 15:08:12 +0000536 // If the for loop doesn't have an increment we can just use the
Chris Lattnerda138702007-07-16 21:28:45 +0000537 // condition as the continue block.
538 llvm::BasicBlock *ContinueBlock;
539 if (S.getInc())
Douglas Gregord9752062009-11-25 01:51:31 +0000540 ContinueBlock = IncBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000541 else
Mike Stump1eb44332009-09-09 15:08:12 +0000542 ContinueBlock = CondBlock;
543
Chris Lattnerda138702007-07-16 21:28:45 +0000544 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000545 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
Mike Stump3e9da662009-02-07 23:02:10 +0000546
Reid Spencer5f016e22007-07-11 17:01:13 +0000547 // If the condition is true, execute the body of the for stmt.
Devang Patelbbd9fa42009-10-06 18:36:08 +0000548 CGDebugInfo *DI = getDebugInfo();
549 if (DI) {
550 DI->setLocation(S.getSourceRange().getBegin());
551 DI->EmitRegionStart(CurFn, Builder);
552 }
Douglas Gregord9752062009-11-25 01:51:31 +0000553
554 {
555 // Create a separate cleanup scope for the body, in case it is not
556 // a compound statement.
557 CleanupScope BodyScope(*this);
558 EmitStmt(S.getBody());
559 }
Chris Lattnerda138702007-07-16 21:28:45 +0000560
Anders Carlssone4b6d342009-02-10 05:52:02 +0000561 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Reid Spencer5f016e22007-07-11 17:01:13 +0000563 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000564 if (S.getInc()) {
Douglas Gregord9752062009-11-25 01:51:31 +0000565 EmitBlock(IncBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000566 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000567 }
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 // Finally, branch back up to the condition for the next iteration.
Douglas Gregord9752062009-11-25 01:51:31 +0000570 if (CondCleanup) {
571 // Branch to the cleanup block.
572 EmitBranch(CondCleanup);
573
574 // Emit the cleanup block, which branches back to the loop body or
575 // outside of the for statement once it is done.
576 EmitBlock(CondCleanup);
577 ConditionScope.ForceCleanup();
578 Builder.CreateCondBr(BoolCondVal, CondBlock, AfterFor);
579 } else
580 EmitBranch(CondBlock);
Devang Patelbbd9fa42009-10-06 18:36:08 +0000581 if (DI) {
582 DI->setLocation(S.getSourceRange().getEnd());
583 DI->EmitRegionEnd(CurFn, Builder);
584 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000585
Chris Lattnerda138702007-07-16 21:28:45 +0000586 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000587 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000588}
589
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000590void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
591 if (RV.isScalar()) {
592 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
593 } else if (RV.isAggregate()) {
594 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
595 } else {
596 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
597 }
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000598 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000599}
600
Reid Spencer5f016e22007-07-11 17:01:13 +0000601/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
602/// if the function returns void, or may be missing one if the function returns
603/// non-void. Fun stuff :).
604void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000605 // Emit the result value, even if unused, to evalute the side effects.
606 const Expr *RV = S.getRetValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000608 // FIXME: Clean this up by using an LValue for ReturnTemp,
609 // EmitStoreThroughLValue, and EmitAnyExpr.
Douglas Gregord86c4772010-05-15 06:46:45 +0000610 if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable() &&
611 !Target.useGlobalsForAutomaticVariables()) {
612 // Apply the named return value optimization for this return statement,
613 // which means doing nothing: the appropriate result has already been
614 // constructed into the NRVO variable.
615 } else if (!ReturnValue) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000616 // Make sure not to return anything, but evaluate the expression
617 // for side effects.
618 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000619 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000620 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000621 // Do nothing (return value is left uninitialized)
Eli Friedmand54b6ac2009-05-27 04:56:12 +0000622 } else if (FnRetTy->isReferenceType()) {
623 // If this function returns a reference, take the address of the expression
624 // rather than the value.
Douglas Gregor33fd1fc2010-03-24 23:14:04 +0000625 RValue Result = EmitReferenceBindingToExpr(RV, false);
626 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
Chris Lattner4b0029d2007-08-26 07:14:44 +0000627 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000628 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000629 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000630 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000631 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000632 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000633 }
Eli Friedman144ac612008-05-22 01:22:33 +0000634
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000635 EmitBranchThroughCleanup(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000636}
637
638void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Daniel Dunbar25b6ebf2009-07-19 07:03:11 +0000639 // As long as debug info is modeled with instructions, we have to ensure we
640 // have a place to insert here and write the stop point here.
641 if (getDebugInfo()) {
642 EnsureInsertPoint();
643 EmitStopPoint(&S);
644 }
645
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000646 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
647 I != E; ++I)
648 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000649}
Chris Lattnerda138702007-07-16 21:28:45 +0000650
Daniel Dunbar09124252008-11-12 08:21:33 +0000651void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000652 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
653
Daniel Dunbar09124252008-11-12 08:21:33 +0000654 // If this code is reachable then emit a stop point (if generating
655 // debug info). We have to do this ourselves because we are on the
656 // "simple" statement path.
657 if (HaveInsertPoint())
658 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000659
Chris Lattnerda138702007-07-16 21:28:45 +0000660 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000661 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000662}
663
Daniel Dunbar09124252008-11-12 08:21:33 +0000664void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000665 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
666
Daniel Dunbar09124252008-11-12 08:21:33 +0000667 // If this code is reachable then emit a stop point (if generating
668 // debug info). We have to do this ourselves because we are on the
669 // "simple" statement path.
670 if (HaveInsertPoint())
671 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000672
Chris Lattnerda138702007-07-16 21:28:45 +0000673 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000674 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000675}
Devang Patel51b09f22007-10-04 23:45:31 +0000676
Devang Patelc049e4f2007-10-08 20:57:48 +0000677/// EmitCaseStmtRange - If case statement range is not too big then
678/// add multiple cases to switch instruction, one for each value within
679/// the range. If range is too big then emit "if" condition check.
680void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000681 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000682
Anders Carlsson51fe9962008-11-22 21:04:56 +0000683 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
684 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000685
Daniel Dunbar16f23572008-07-25 01:11:38 +0000686 // Emit the code for this case. We do this first to make sure it is
687 // properly chained from our predecessor before generating the
688 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000689 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000690 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
691 EmitStmt(S.getSubStmt());
692
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000693 // If range is empty, do nothing.
694 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
695 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000696
697 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000698 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000699 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
700 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000701 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000702 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, LHS), CaseDest);
Devang Patel2d79d0f2007-10-05 20:54:07 +0000703 LHS++;
704 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000705 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000706 }
707
Daniel Dunbar16f23572008-07-25 01:11:38 +0000708 // The range is too big. Emit "if" condition into a new block,
709 // making sure to save and restore the current insertion point.
710 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000711
Daniel Dunbar16f23572008-07-25 01:11:38 +0000712 // Push this test onto the chain of range checks (which terminates
713 // in the default basic block). The switch's default will be changed
714 // to the top of this chain after switch emission is complete.
715 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000716 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000717
Daniel Dunbar16f23572008-07-25 01:11:38 +0000718 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
719 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000720
721 // Emit range check.
Mike Stump1eb44332009-09-09 15:08:12 +0000722 llvm::Value *Diff =
723 Builder.CreateSub(SwitchInsn->getCondition(),
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000724 llvm::ConstantInt::get(VMContext, LHS), "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000725 llvm::Value *Cond =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000726 Builder.CreateICmpULE(Diff,
727 llvm::ConstantInt::get(VMContext, Range), "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000728 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
729
Daniel Dunbar16f23572008-07-25 01:11:38 +0000730 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000731 if (RestoreBB)
732 Builder.SetInsertPoint(RestoreBB);
733 else
734 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000735}
736
737void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
738 if (S.getRHS()) {
739 EmitCaseStmtRange(S);
740 return;
741 }
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000743 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000744 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000745 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000746 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Chris Lattner5512f282009-03-04 04:46:18 +0000748 // Recursively emitting the statement is acceptable, but is not wonderful for
749 // code where we have many case statements nested together, i.e.:
750 // case 1:
751 // case 2:
752 // case 3: etc.
753 // Handling this recursively will create a new block for each case statement
754 // that falls through to the next case which is IR intensive. It also causes
755 // deep recursion which can run into stack depth limitations. Handle
756 // sequential non-range case statements specially.
757 const CaseStmt *CurCase = &S;
758 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
759
760 // Otherwise, iteratively add consequtive cases to this switch stmt.
761 while (NextCase && NextCase->getRHS() == 0) {
762 CurCase = NextCase;
763 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000764 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
Chris Lattner5512f282009-03-04 04:46:18 +0000765
766 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
767 }
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Chris Lattner5512f282009-03-04 04:46:18 +0000769 // Normal default recursion for non-cases.
770 EmitStmt(CurCase->getSubStmt());
Devang Patel51b09f22007-10-04 23:45:31 +0000771}
772
773void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000774 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Mike Stump1eb44332009-09-09 15:08:12 +0000775 assert(DefaultBlock->empty() &&
Daniel Dunbar55e87422008-11-11 02:29:29 +0000776 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000777 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000778 EmitStmt(S.getSubStmt());
779}
780
781void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
Douglas Gregord3d53012009-11-24 17:07:59 +0000782 CleanupScope ConditionScope(*this);
783
784 if (S.getConditionVariable())
785 EmitLocalBlockVarDecl(*S.getConditionVariable());
786
Devang Patel51b09f22007-10-04 23:45:31 +0000787 llvm::Value *CondV = EmitScalarExpr(S.getCond());
788
789 // Handle nested switch statements.
790 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000791 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000792
Daniel Dunbar16f23572008-07-25 01:11:38 +0000793 // Create basic block to hold stuff that comes after switch
794 // statement. We also need to create a default block now so that
795 // explicit case ranges tests can have a place to jump to on
796 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000797 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
798 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000799 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
800 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000801
Daniel Dunbar09124252008-11-12 08:21:33 +0000802 // Clear the insertion point to indicate we are in unreachable code.
803 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000804
Devang Patele9b8c0a2007-10-30 20:59:40 +0000805 // All break statements jump to NextBlock. If BreakContinueStack is non empty
806 // then reuse last ContinueBlock.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000807 llvm::BasicBlock *ContinueBlock = 0;
808 if (!BreakContinueStack.empty())
Devang Patel51b09f22007-10-04 23:45:31 +0000809 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000810
Mike Stump3e9da662009-02-07 23:02:10 +0000811 // Ensure any vlas created between there and here, are undone
Anders Carlssone4b6d342009-02-10 05:52:02 +0000812 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
Devang Patel51b09f22007-10-04 23:45:31 +0000813
814 // Emit switch body.
815 EmitStmt(S.getBody());
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Anders Carlssone4b6d342009-02-10 05:52:02 +0000817 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +0000818
Daniel Dunbar16f23572008-07-25 01:11:38 +0000819 // Update the default block in case explicit case range tests have
820 // been chained on top.
821 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Daniel Dunbar16f23572008-07-25 01:11:38 +0000823 // If a default was never emitted then reroute any jumps to it and
824 // discard.
825 if (!DefaultBlock->getParent()) {
826 DefaultBlock->replaceAllUsesWith(NextBlock);
827 delete DefaultBlock;
828 }
Devang Patel51b09f22007-10-04 23:45:31 +0000829
Daniel Dunbar16f23572008-07-25 01:11:38 +0000830 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000831 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000832
Devang Patel51b09f22007-10-04 23:45:31 +0000833 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000834 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000835}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000836
Chris Lattner2819fa82009-04-26 17:57:12 +0000837static std::string
Daniel Dunbar444be732009-11-13 05:51:54 +0000838SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
Chris Lattner2819fa82009-04-26 17:57:12 +0000839 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000840 std::string Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000842 while (*Constraint) {
843 switch (*Constraint) {
844 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000845 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000846 break;
847 // Ignore these
848 case '*':
849 case '?':
850 case '!':
851 break;
852 case 'g':
853 Result += "imr";
854 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000855 case '[': {
Chris Lattner2819fa82009-04-26 17:57:12 +0000856 assert(OutCons &&
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000857 "Must pass output names to constraints with a symbolic name");
858 unsigned Index;
Mike Stump1eb44332009-09-09 15:08:12 +0000859 bool result = Target.resolveSymbolicName(Constraint,
Chris Lattner2819fa82009-04-26 17:57:12 +0000860 &(*OutCons)[0],
861 OutCons->size(), Index);
Chris Lattner53637652009-01-21 07:35:26 +0000862 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000863 Result += llvm::utostr(Index);
864 break;
865 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000866 }
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000868 Constraint++;
869 }
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000871 return Result;
872}
873
Anders Carlsson63471722009-01-11 19:32:54 +0000874llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
Daniel Dunbarb84e8a62009-05-04 06:56:16 +0000875 const TargetInfo::ConstraintInfo &Info,
Anders Carlsson63471722009-01-11 19:32:54 +0000876 const Expr *InputExpr,
Chris Lattner63c8b142009-03-10 05:39:21 +0000877 std::string &ConstraintStr) {
Anders Carlsson63471722009-01-11 19:32:54 +0000878 llvm::Value *Arg;
Mike Stump1eb44332009-09-09 15:08:12 +0000879 if (Info.allowsRegister() || !Info.allowsMemory()) {
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000880 if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType())) {
Anders Carlsson63471722009-01-11 19:32:54 +0000881 Arg = EmitScalarExpr(InputExpr);
882 } else {
Chris Lattner810f6d52009-03-13 17:38:01 +0000883 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000884 LValue Dest = EmitLValue(InputExpr);
885
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000886 const llvm::Type *Ty = ConvertType(InputExpr->getType());
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000887 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
888 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
Owen Anderson0032b272009-08-13 21:57:51 +0000889 Ty = llvm::IntegerType::get(VMContext, Size);
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000890 Ty = llvm::PointerType::getUnqual(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000892 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
893 } else {
894 Arg = Dest.getAddress();
895 ConstraintStr += '*';
896 }
Anders Carlsson63471722009-01-11 19:32:54 +0000897 }
898 } else {
Chris Lattner810f6d52009-03-13 17:38:01 +0000899 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
Anders Carlsson63471722009-01-11 19:32:54 +0000900 LValue Dest = EmitLValue(InputExpr);
901 Arg = Dest.getAddress();
902 ConstraintStr += '*';
903 }
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Anders Carlsson63471722009-01-11 19:32:54 +0000905 return Arg;
906}
907
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000908void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Chris Lattner458cd9c2009-03-10 23:21:44 +0000909 // Analyze the asm string to decompose it into its pieces. We know that Sema
910 // has already done this, so it is guaranteed to be successful.
911 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +0000912 unsigned DiagOffs;
913 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
Mike Stump1eb44332009-09-09 15:08:12 +0000914
Chris Lattner458cd9c2009-03-10 23:21:44 +0000915 // Assemble the pieces into the final asm string.
916 std::string AsmString;
917 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
918 if (Pieces[i].isString())
919 AsmString += Pieces[i].getString();
920 else if (Pieces[i].getModifier() == '\0')
921 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
922 else
923 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
924 Pieces[i].getModifier() + '}';
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000925 }
Mike Stump1eb44332009-09-09 15:08:12 +0000926
Chris Lattner481fef92009-05-03 07:05:00 +0000927 // Get all the output and input constraints together.
928 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
929 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
930
Mike Stump1eb44332009-09-09 15:08:12 +0000931 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +0000932 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
933 S.getOutputName(i));
Chris Lattnerb9922592010-03-03 21:52:23 +0000934 bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid;
935 assert(IsValid && "Failed to parse output constraint");
Chris Lattner481fef92009-05-03 07:05:00 +0000936 OutputConstraintInfos.push_back(Info);
Mike Stump1eb44332009-09-09 15:08:12 +0000937 }
938
Chris Lattner481fef92009-05-03 07:05:00 +0000939 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
940 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
941 S.getInputName(i));
Chris Lattnerb9922592010-03-03 21:52:23 +0000942 bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(),
943 S.getNumOutputs(), Info);
944 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
Chris Lattner481fef92009-05-03 07:05:00 +0000945 InputConstraintInfos.push_back(Info);
946 }
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000948 std::string Constraints;
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Chris Lattnerede9d902009-05-03 07:53:25 +0000950 std::vector<LValue> ResultRegDests;
951 std::vector<QualType> ResultRegQualTys;
Chris Lattnera077b5c2009-05-03 08:21:20 +0000952 std::vector<const llvm::Type *> ResultRegTypes;
953 std::vector<const llvm::Type *> ResultTruncRegTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000954 std::vector<const llvm::Type*> ArgTypes;
955 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000956
957 // Keep track of inout constraints.
958 std::string InOutConstraints;
959 std::vector<llvm::Value*> InOutArgs;
960 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +0000961
Mike Stump1eb44332009-09-09 15:08:12 +0000962 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +0000963 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
Anders Carlsson03eb5432009-01-27 20:38:24 +0000964
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000965 // Simplify the output constraint.
Chris Lattner481fef92009-05-03 07:05:00 +0000966 std::string OutputConstraint(S.getOutputConstraint(i));
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000967 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Chris Lattner810f6d52009-03-13 17:38:01 +0000969 const Expr *OutExpr = S.getOutputExpr(i);
970 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Chris Lattner810f6d52009-03-13 17:38:01 +0000972 LValue Dest = EmitLValue(OutExpr);
Chris Lattnerede9d902009-05-03 07:53:25 +0000973 if (!Constraints.empty())
Anders Carlssonbad3a942009-05-01 00:16:04 +0000974 Constraints += ',';
975
Chris Lattnera077b5c2009-05-03 08:21:20 +0000976 // If this is a register output, then make the inline asm return it
977 // by-value. If this is a memory result, return the value by-reference.
Chris Lattnerede9d902009-05-03 07:53:25 +0000978 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
Chris Lattnera077b5c2009-05-03 08:21:20 +0000979 Constraints += "=" + OutputConstraint;
Chris Lattnerede9d902009-05-03 07:53:25 +0000980 ResultRegQualTys.push_back(OutExpr->getType());
981 ResultRegDests.push_back(Dest);
Chris Lattnera077b5c2009-05-03 08:21:20 +0000982 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
983 ResultTruncRegTypes.push_back(ResultRegTypes.back());
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Chris Lattnera077b5c2009-05-03 08:21:20 +0000985 // If this output is tied to an input, and if the input is larger, then
986 // we need to set the actual result type of the inline asm node to be the
987 // same as the input type.
988 if (Info.hasMatchingInput()) {
Chris Lattnerebfc9852009-05-03 08:38:58 +0000989 unsigned InputNo;
990 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
991 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
Chris Lattneraab64d02010-04-23 17:27:29 +0000992 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
Chris Lattnera077b5c2009-05-03 08:21:20 +0000993 break;
Chris Lattnerebfc9852009-05-03 08:38:58 +0000994 }
995 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Chris Lattnera077b5c2009-05-03 08:21:20 +0000997 QualType InputTy = S.getInputExpr(InputNo)->getType();
Chris Lattneraab64d02010-04-23 17:27:29 +0000998 QualType OutputType = OutExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Chris Lattnera077b5c2009-05-03 08:21:20 +00001000 uint64_t InputSize = getContext().getTypeSize(InputTy);
Chris Lattneraab64d02010-04-23 17:27:29 +00001001 if (getContext().getTypeSize(OutputType) < InputSize) {
1002 // Form the asm to return the value as a larger integer or fp type.
1003 ResultRegTypes.back() = ConvertType(InputTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001004 }
1005 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001006 } else {
1007 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +00001008 Args.push_back(Dest.getAddress());
Anders Carlssonf39a4212008-02-05 20:01:53 +00001009 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001010 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001011 }
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Chris Lattner44def072009-04-26 07:16:29 +00001013 if (Info.isReadWrite()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +00001014 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +00001015
Anders Carlssonfca93612009-08-04 18:18:36 +00001016 const Expr *InputExpr = S.getOutputExpr(i);
1017 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Chris Lattner44def072009-04-26 07:16:29 +00001019 if (Info.allowsRegister())
Anders Carlsson9f2505b2009-01-11 21:23:27 +00001020 InOutConstraints += llvm::utostr(i);
1021 else
1022 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +00001023
Anders Carlssonfca93612009-08-04 18:18:36 +00001024 InOutArgTypes.push_back(Arg->getType());
1025 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001026 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001027 }
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001029 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001031 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1032 const Expr *InputExpr = S.getInputExpr(i);
1033
Chris Lattner481fef92009-05-03 07:05:00 +00001034 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1035
Chris Lattnerede9d902009-05-03 07:53:25 +00001036 if (!Constraints.empty())
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001037 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001038
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001039 // Simplify the input constraint.
Chris Lattner481fef92009-05-03 07:05:00 +00001040 std::string InputConstraint(S.getInputConstraint(i));
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001041 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
Chris Lattner2819fa82009-04-26 17:57:12 +00001042 &OutputConstraintInfos);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001043
Anders Carlsson63471722009-01-11 19:32:54 +00001044 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Chris Lattner4df4ee02009-05-03 07:27:51 +00001046 // If this input argument is tied to a larger output result, extend the
1047 // input to be the same size as the output. The LLVM backend wants to see
1048 // the input and output of a matching constraint be the same size. Note
1049 // that GCC does not define what the top bits are here. We use zext because
1050 // that is usually cheaper, but LLVM IR should really get an anyext someday.
1051 if (Info.hasTiedOperand()) {
1052 unsigned Output = Info.getTiedOperand();
Chris Lattneraab64d02010-04-23 17:27:29 +00001053 QualType OutputType = S.getOutputExpr(Output)->getType();
Chris Lattner4df4ee02009-05-03 07:27:51 +00001054 QualType InputTy = InputExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Chris Lattneraab64d02010-04-23 17:27:29 +00001056 if (getContext().getTypeSize(OutputType) >
Chris Lattner4df4ee02009-05-03 07:27:51 +00001057 getContext().getTypeSize(InputTy)) {
1058 // Use ptrtoint as appropriate so that we can do our extension.
1059 if (isa<llvm::PointerType>(Arg->getType()))
1060 Arg = Builder.CreatePtrToInt(Arg,
Chris Lattnerfc1a9c32010-04-07 05:46:54 +00001061 llvm::IntegerType::get(VMContext, LLVMPointerWidth));
Chris Lattneraab64d02010-04-23 17:27:29 +00001062 const llvm::Type *OutputTy = ConvertType(OutputType);
1063 if (isa<llvm::IntegerType>(OutputTy))
1064 Arg = Builder.CreateZExt(Arg, OutputTy);
1065 else
1066 Arg = Builder.CreateFPExt(Arg, OutputTy);
Chris Lattner4df4ee02009-05-03 07:27:51 +00001067 }
1068 }
Mike Stump1eb44332009-09-09 15:08:12 +00001069
1070
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001071 ArgTypes.push_back(Arg->getType());
1072 Args.push_back(Arg);
1073 Constraints += InputConstraint;
1074 }
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Anders Carlssonf39a4212008-02-05 20:01:53 +00001076 // Append the "input" part of inout constraints last.
1077 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1078 ArgTypes.push_back(InOutArgTypes[i]);
1079 Args.push_back(InOutArgs[i]);
1080 }
1081 Constraints += InOutConstraints;
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001083 // Clobbers
1084 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
Anders Carlsson83c021c2010-01-30 19:12:25 +00001085 llvm::StringRef Clobber = S.getClobber(i)->getString();
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001086
Anders Carlsson83c021c2010-01-30 19:12:25 +00001087 Clobber = Target.getNormalizedGCCRegisterName(Clobber);
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Anders Carlssonea041752008-02-06 00:11:32 +00001089 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001090 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Anders Carlssonea041752008-02-06 00:11:32 +00001092 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001093 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001094 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001095 }
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001097 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +00001098 std::string MachineClobbers = Target.getClobbers();
1099 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001100 if (!Constraints.empty())
1101 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00001102 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001103 }
Anders Carlssonbad3a942009-05-01 00:16:04 +00001104
1105 const llvm::Type *ResultType;
Chris Lattnera077b5c2009-05-03 08:21:20 +00001106 if (ResultRegTypes.empty())
Owen Anderson0032b272009-08-13 21:57:51 +00001107 ResultType = llvm::Type::getVoidTy(VMContext);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001108 else if (ResultRegTypes.size() == 1)
1109 ResultType = ResultRegTypes[0];
Anders Carlssonbad3a942009-05-01 00:16:04 +00001110 else
Owen Anderson47a434f2009-08-05 23:18:46 +00001111 ResultType = llvm::StructType::get(VMContext, ResultRegTypes);
Mike Stump1eb44332009-09-09 15:08:12 +00001112
1113 const llvm::FunctionType *FTy =
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001114 llvm::FunctionType::get(ResultType, ArgTypes, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001115
1116 llvm::InlineAsm *IA =
1117 llvm::InlineAsm::get(FTy, AsmString, Constraints,
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001118 S.isVolatile() || S.getNumOutputs() == 0);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001119 llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end());
Anders Carlssonbc0822b2009-03-02 19:58:15 +00001120 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Chris Lattnerfc1a9c32010-04-07 05:46:54 +00001122 // Slap the source location of the inline asm into a !srcloc metadata on the
1123 // call.
1124 unsigned LocID = S.getAsmString()->getLocStart().getRawEncoding();
1125 llvm::Value *LocIDC =
1126 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LocID);
1127 Result->setMetadata("srcloc", llvm::MDNode::get(VMContext, &LocIDC, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Chris Lattnera077b5c2009-05-03 08:21:20 +00001129 // Extract all of the register value results from the asm.
1130 std::vector<llvm::Value*> RegResults;
1131 if (ResultRegTypes.size() == 1) {
1132 RegResults.push_back(Result);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001133 } else {
Chris Lattnera077b5c2009-05-03 08:21:20 +00001134 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
Anders Carlssonbad3a942009-05-01 00:16:04 +00001135 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
Chris Lattnera077b5c2009-05-03 08:21:20 +00001136 RegResults.push_back(Tmp);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001137 }
1138 }
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Chris Lattnera077b5c2009-05-03 08:21:20 +00001140 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1141 llvm::Value *Tmp = RegResults[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Chris Lattnera077b5c2009-05-03 08:21:20 +00001143 // If the result type of the LLVM IR asm doesn't match the result type of
1144 // the expression, do the conversion.
1145 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1146 const llvm::Type *TruncTy = ResultTruncRegTypes[i];
Chris Lattneraab64d02010-04-23 17:27:29 +00001147
1148 // Truncate the integer result to the right size, note that TruncTy can be
1149 // a pointer.
1150 if (TruncTy->isFloatingPointTy())
1151 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00001152 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
Chris Lattneraab64d02010-04-23 17:27:29 +00001153 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
1154 Tmp = Builder.CreateTrunc(Tmp, llvm::IntegerType::get(VMContext,
1155 (unsigned)ResSize));
Chris Lattnera077b5c2009-05-03 08:21:20 +00001156 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00001157 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
1158 uint64_t TmpSize =CGM.getTargetData().getTypeSizeInBits(Tmp->getType());
1159 Tmp = Builder.CreatePtrToInt(Tmp, llvm::IntegerType::get(VMContext,
1160 (unsigned)TmpSize));
1161 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1162 } else if (TruncTy->isIntegerTy()) {
1163 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001164 }
1165 }
Mike Stump1eb44332009-09-09 15:08:12 +00001166
Chris Lattnera077b5c2009-05-03 08:21:20 +00001167 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i],
1168 ResultRegQualTys[i]);
1169 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001170}