blob: a70534d2ca3efc60ddf88fb0bae56e41d678e43e [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());
Devang Patel5a6fbcf2010-07-22 22:29:16 +000037 DI->UpdateLineDirectiveRegion(Builder);
Devang Patel4d939e62010-07-20 22:20:10 +000038 DI->EmitStopPoint(Builder);
Daniel Dunbar09124252008-11-12 08:21:33 +000039 }
40}
41
Reid Spencer5f016e22007-07-11 17:01:13 +000042void CodeGenFunction::EmitStmt(const Stmt *S) {
43 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000044
Daniel Dunbar09124252008-11-12 08:21:33 +000045 // Check if we can handle this without bothering to generate an
46 // insert point or debug info.
47 if (EmitSimpleStmt(S))
48 return;
49
Daniel Dunbard286f052009-07-19 06:58:07 +000050 // Check if we are generating unreachable code.
51 if (!HaveInsertPoint()) {
52 // If so, and the statement doesn't contain a label, then we do not need to
53 // generate actual code. This is safe because (1) the current point is
54 // unreachable, so we don't need to execute the code, and (2) we've already
55 // handled the statements which update internal data structures (like the
56 // local variable map) which could be used by subsequent statements.
57 if (!ContainsLabel(S)) {
58 // Verify that any decl statements were handled as simple, they may be in
59 // scope of subsequent reachable statements.
60 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
61 return;
62 }
63
64 // Otherwise, make a new block to hold the code.
65 EnsureInsertPoint();
66 }
67
Daniel Dunbar09124252008-11-12 08:21:33 +000068 // Generate a stoppoint if we are emitting debug info.
69 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000070
Reid Spencer5f016e22007-07-11 17:01:13 +000071 switch (S->getStmtClass()) {
72 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000073 // Must be an expression in a stmt context. Emit the value (to get
74 // side-effects) and ignore the result.
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000075 if (!isa<Expr>(S))
Daniel Dunbar488e9932008-08-16 00:56:44 +000076 ErrorUnsupported(S, "statement");
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000077
John McCall558d2ab2010-09-15 10:14:12 +000078 EmitAnyExpr(cast<Expr>(S), AggValueSlot::ignored(), true);
Mike Stump1eb44332009-09-09 15:08:12 +000079
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000080 // Expression emitters don't handle unreachable blocks yet, so look for one
81 // explicitly here. This handles the common case of a call to a noreturn
82 // function.
83 if (llvm::BasicBlock *CurBB = Builder.GetInsertBlock()) {
John McCallf1549f62010-07-06 01:34:17 +000084 if (CurBB->empty() && CurBB->use_empty()) {
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000085 CurBB->eraseFromParent();
86 Builder.ClearInsertionPoint();
87 }
Reid Spencer5f016e22007-07-11 17:01:13 +000088 }
89 break;
Mike Stump1eb44332009-09-09 15:08:12 +000090 case Stmt::IndirectGotoStmtClass:
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000091 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000092
93 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
94 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
95 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
96 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
Mike Stump1eb44332009-09-09 15:08:12 +000097
Reid Spencer5f016e22007-07-11 17:01:13 +000098 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +000099
Devang Patel51b09f22007-10-04 23:45:31 +0000100 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000101 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000102
103 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000104 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
Mike Stump1eb44332009-09-09 15:08:12 +0000105 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000106 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +0000107 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
108 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000109 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000110 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000111 break;
112 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000113 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000114 break;
115 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +0000116 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000117 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000118 case Stmt::ObjCForCollectionStmtClass:
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000119 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000120 break;
Anders Carlsson6815e942009-09-27 18:58:34 +0000121
122 case Stmt::CXXTryStmtClass:
123 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
124 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 }
126}
127
Daniel Dunbar09124252008-11-12 08:21:33 +0000128bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
129 switch (S->getStmtClass()) {
130 default: return false;
131 case Stmt::NullStmtClass: break;
132 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
Daniel Dunbard286f052009-07-19 06:58:07 +0000133 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbar09124252008-11-12 08:21:33 +0000134 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
135 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
136 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
137 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
138 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
139 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
140 }
141
142 return true;
143}
144
Chris Lattner33793202007-08-31 22:09:40 +0000145/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
146/// this captures the expression result of the last sub-statement and returns it
147/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000148RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
John McCall558d2ab2010-09-15 10:14:12 +0000149 AggValueSlot AggSlot) {
Chris Lattner7d22bf02009-03-05 08:04:57 +0000150 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
151 "LLVM IR generation of compound statement ('{}')");
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Anders Carlssone896d982009-02-13 08:11:52 +0000153 CGDebugInfo *DI = getDebugInfo();
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000154 if (DI) {
Devang Patelbbd9fa42009-10-06 18:36:08 +0000155 DI->setLocation(S.getLBracLoc());
Devang Patel4d939e62010-07-20 22:20:10 +0000156 DI->EmitRegionStart(Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000157 }
158
Anders Carlssonc71c8452009-02-07 23:50:39 +0000159 // Keep track of the current cleanup stack depth.
John McCallf1549f62010-07-06 01:34:17 +0000160 RunCleanupsScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000161
Chris Lattner33793202007-08-31 22:09:40 +0000162 for (CompoundStmt::const_body_iterator I = S.body_begin(),
163 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000164 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000165
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000166 if (DI) {
Devang Patelcd9199e2010-04-13 00:08:43 +0000167 DI->setLocation(S.getRBracLoc());
Devang Patel4d939e62010-07-20 22:20:10 +0000168 DI->EmitRegionEnd(Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000169 }
170
Anders Carlsson17d28a32008-12-12 05:52:00 +0000171 RValue RV;
Mike Stump1eb44332009-09-09 15:08:12 +0000172 if (!GetLast)
Anders Carlsson17d28a32008-12-12 05:52:00 +0000173 RV = RValue::get(0);
174 else {
Mike Stump1eb44332009-09-09 15:08:12 +0000175 // We have to special case labels here. They are statements, but when put
Anders Carlsson17d28a32008-12-12 05:52:00 +0000176 // at the end of a statement expression, they yield the value of their
177 // subexpression. Handle this by walking through all labels we encounter,
178 // emitting them before we evaluate the subexpr.
179 const Stmt *LastStmt = S.body_back();
180 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
181 EmitLabel(*LS);
182 LastStmt = LS->getSubStmt();
183 }
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Anders Carlsson17d28a32008-12-12 05:52:00 +0000185 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000186
John McCall558d2ab2010-09-15 10:14:12 +0000187 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggSlot);
Anders Carlsson17d28a32008-12-12 05:52:00 +0000188 }
189
Anders Carlsson17d28a32008-12-12 05:52:00 +0000190 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000191}
192
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000193void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
194 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000196 // If there is a cleanup stack, then we it isn't worth trying to
197 // simplify this block (we would need to remove it from the scope map
198 // and cleanup entry).
John McCallf1549f62010-07-06 01:34:17 +0000199 if (!EHStack.empty())
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000200 return;
201
202 // Can only simplify direct branches.
203 if (!BI || !BI->isUnconditional())
204 return;
205
206 BB->replaceAllUsesWith(BI->getSuccessor(0));
207 BI->eraseFromParent();
208 BB->eraseFromParent();
209}
210
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000211void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
John McCall548ce5e2010-04-21 11:18:06 +0000212 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
213
Daniel Dunbard57a8712008-11-11 09:41:28 +0000214 // Fall out of the current block (if necessary).
215 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000216
217 if (IsFinished && BB->use_empty()) {
218 delete BB;
219 return;
220 }
221
John McCall839cbaa2010-04-21 10:29:06 +0000222 // Place the block after the current block, if possible, or else at
223 // the end of the function.
John McCall548ce5e2010-04-21 11:18:06 +0000224 if (CurBB && CurBB->getParent())
225 CurFn->getBasicBlockList().insertAfter(CurBB, BB);
John McCall839cbaa2010-04-21 10:29:06 +0000226 else
227 CurFn->getBasicBlockList().push_back(BB);
Reid Spencer5f016e22007-07-11 17:01:13 +0000228 Builder.SetInsertPoint(BB);
229}
230
Daniel Dunbard57a8712008-11-11 09:41:28 +0000231void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
232 // Emit a branch from the current block to the target one if this
233 // was a real block. If this was just a fall-through block after a
234 // terminator, don't emit it.
235 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
236
237 if (!CurBB || CurBB->getTerminator()) {
238 // If there is no insert point or the previous block is already
239 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000240 } else {
241 // Otherwise, create a fall-through branch.
242 Builder.CreateBr(Target);
243 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000244
245 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000246}
247
John McCallf1549f62010-07-06 01:34:17 +0000248CodeGenFunction::JumpDest
249CodeGenFunction::getJumpDestForLabel(const LabelStmt *S) {
250 JumpDest &Dest = LabelMap[S];
John McCallff8e1152010-07-23 21:56:41 +0000251 if (Dest.isValid()) return Dest;
John McCallf1549f62010-07-06 01:34:17 +0000252
253 // Create, but don't insert, the new block.
John McCallff8e1152010-07-23 21:56:41 +0000254 Dest = JumpDest(createBasicBlock(S->getName()),
255 EHScopeStack::stable_iterator::invalid(),
256 NextCleanupDestIndex++);
John McCallf1549f62010-07-06 01:34:17 +0000257 return Dest;
258}
259
Mike Stumpec9771d2009-02-08 09:22:19 +0000260void CodeGenFunction::EmitLabel(const LabelStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000261 JumpDest &Dest = LabelMap[&S];
262
John McCallff8e1152010-07-23 21:56:41 +0000263 // If we didn't need a forward reference to this label, just go
John McCallf1549f62010-07-06 01:34:17 +0000264 // ahead and create a destination at the current scope.
John McCallff8e1152010-07-23 21:56:41 +0000265 if (!Dest.isValid()) {
John McCallf1549f62010-07-06 01:34:17 +0000266 Dest = getJumpDestInCurrentScope(S.getName());
267
268 // Otherwise, we need to give this label a target depth and remove
269 // it from the branch-fixups list.
270 } else {
John McCallff8e1152010-07-23 21:56:41 +0000271 assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
272 Dest = JumpDest(Dest.getBlock(),
273 EHStack.stable_begin(),
274 Dest.getDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000275
John McCallff8e1152010-07-23 21:56:41 +0000276 ResolveBranchFixups(Dest.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000277 }
278
John McCallff8e1152010-07-23 21:56:41 +0000279 EmitBlock(Dest.getBlock());
Chris Lattner91d723d2008-07-26 20:23:23 +0000280}
281
282
283void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
284 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000285 EmitStmt(S.getSubStmt());
286}
287
288void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000289 // If this code is reachable then emit a stop point (if generating
290 // debug info). We have to do this ourselves because we are on the
291 // "simple" statement path.
292 if (HaveInsertPoint())
293 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000294
John McCallf1549f62010-07-06 01:34:17 +0000295 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000296}
297
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000298
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000299void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Chris Lattner49c952f2009-11-06 18:10:47 +0000300 // Ensure that we have an i8* for our PHI node.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000301 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
302 llvm::Type::getInt8PtrTy(VMContext),
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000303 "addr");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000304 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
305
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000306
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000307 // Get the basic block for the indirect goto.
308 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
309
310 // The first instruction in the block has to be the PHI for the switch dest,
311 // add an entry for this branch.
312 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
313
314 EmitBranch(IndGotoBB);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000315}
316
Chris Lattner62b72f62008-11-11 07:24:28 +0000317void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000318 // C99 6.8.4.1: The first substatement is executed if the expression compares
319 // unequal to 0. The condition must be a scalar type.
John McCallf1549f62010-07-06 01:34:17 +0000320 RunCleanupsScope ConditionScope(*this);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000321
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000322 if (S.getConditionVariable())
Douglas Gregor01234bb2009-11-24 16:43:22 +0000323 EmitLocalBlockVarDecl(*S.getConditionVariable());
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Chris Lattner9bc47e22008-11-12 07:46:33 +0000325 // If the condition constant folds and can be elided, try to avoid emitting
326 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000327 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000328 // Figure out which block (then or else) is executed.
329 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000330 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000331 std::swap(Executed, Skipped);
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Chris Lattner62b72f62008-11-11 07:24:28 +0000333 // If the skipped block has no labels in it, just emit the executed block.
334 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000335 if (!ContainsLabel(Skipped)) {
Douglas Gregor01234bb2009-11-24 16:43:22 +0000336 if (Executed) {
John McCallf1549f62010-07-06 01:34:17 +0000337 RunCleanupsScope ExecutedScope(*this);
Chris Lattner62b72f62008-11-11 07:24:28 +0000338 EmitStmt(Executed);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000339 }
Chris Lattner62b72f62008-11-11 07:24:28 +0000340 return;
341 }
342 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000343
344 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
345 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000346 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
347 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
348 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000349 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000350 ElseBlock = createBasicBlock("if.else");
351 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 // Emit the 'then' code.
Douglas Gregor01234bb2009-11-24 16:43:22 +0000354 EmitBlock(ThenBlock);
355 {
John McCallf1549f62010-07-06 01:34:17 +0000356 RunCleanupsScope ThenScope(*this);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000357 EmitStmt(S.getThen());
358 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000359 EmitBranch(ContBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 // Emit the 'else' code if present.
362 if (const Stmt *Else = S.getElse()) {
363 EmitBlock(ElseBlock);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000364 {
John McCallf1549f62010-07-06 01:34:17 +0000365 RunCleanupsScope ElseScope(*this);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000366 EmitStmt(Else);
367 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000368 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 }
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000372 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000373}
374
375void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000376 // Emit the header for the loop, which will also become
377 // the continue target.
378 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
John McCallff8e1152010-07-23 21:56:41 +0000379 EmitBlock(LoopHeader.getBlock());
Mike Stump72cac2c2009-02-07 18:08:12 +0000380
John McCallf1549f62010-07-06 01:34:17 +0000381 // Create an exit block for when the condition fails, which will
382 // also become the break target.
383 JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
Mike Stump72cac2c2009-02-07 18:08:12 +0000384
385 // Store the blocks to use for break and continue.
John McCallf1549f62010-07-06 01:34:17 +0000386 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Douglas Gregor5656e142009-11-24 21:15:44 +0000388 // C++ [stmt.while]p2:
389 // When the condition of a while statement is a declaration, the
390 // scope of the variable that is declared extends from its point
391 // of declaration (3.3.2) to the end of the while statement.
392 // [...]
393 // The object created in a condition is destroyed and created
394 // with each iteration of the loop.
John McCallf1549f62010-07-06 01:34:17 +0000395 RunCleanupsScope ConditionScope(*this);
Douglas Gregor5656e142009-11-24 21:15:44 +0000396
John McCallf1549f62010-07-06 01:34:17 +0000397 if (S.getConditionVariable())
Douglas Gregor5656e142009-11-24 21:15:44 +0000398 EmitLocalBlockVarDecl(*S.getConditionVariable());
Douglas Gregor5656e142009-11-24 21:15:44 +0000399
Mike Stump16b16202009-02-07 17:18:33 +0000400 // Evaluate the conditional in the while header. C99 6.8.5.1: The
401 // evaluation of the controlling expression takes place before each
402 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Douglas Gregor5656e142009-11-24 21:15:44 +0000404
Devang Patel2c30d8f2007-10-09 20:51:27 +0000405 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000407 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000408 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel2c30d8f2007-10-09 20:51:27 +0000409 if (C->isOne())
410 EmitBoolCondBranch = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 // As long as the condition is true, go to the loop body.
John McCallf1549f62010-07-06 01:34:17 +0000413 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
414 if (EmitBoolCondBranch) {
John McCallff8e1152010-07-23 21:56:41 +0000415 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
John McCallf1549f62010-07-06 01:34:17 +0000416 if (ConditionScope.requiresCleanups())
417 ExitBlock = createBasicBlock("while.exit");
418
419 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
420
John McCallff8e1152010-07-23 21:56:41 +0000421 if (ExitBlock != LoopExit.getBlock()) {
John McCallf1549f62010-07-06 01:34:17 +0000422 EmitBlock(ExitBlock);
423 EmitBranchThroughCleanup(LoopExit);
424 }
425 }
Douglas Gregor5656e142009-11-24 21:15:44 +0000426
John McCallf1549f62010-07-06 01:34:17 +0000427 // Emit the loop body. We have to emit this in a cleanup scope
428 // because it might be a singleton DeclStmt.
Douglas Gregor5656e142009-11-24 21:15:44 +0000429 {
John McCallf1549f62010-07-06 01:34:17 +0000430 RunCleanupsScope BodyScope(*this);
Douglas Gregor5656e142009-11-24 21:15:44 +0000431 EmitBlock(LoopBody);
432 EmitStmt(S.getBody());
433 }
Chris Lattnerda138702007-07-16 21:28:45 +0000434
Mike Stump1eb44332009-09-09 15:08:12 +0000435 BreakContinueStack.pop_back();
436
John McCallf1549f62010-07-06 01:34:17 +0000437 // Immediately force cleanup.
438 ConditionScope.ForceCleanup();
Douglas Gregor5656e142009-11-24 21:15:44 +0000439
John McCallf1549f62010-07-06 01:34:17 +0000440 // Branch to the loop header again.
John McCallff8e1152010-07-23 21:56:41 +0000441 EmitBranch(LoopHeader.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Reid Spencer5f016e22007-07-11 17:01:13 +0000443 // Emit the exit block.
John McCallff8e1152010-07-23 21:56:41 +0000444 EmitBlock(LoopExit.getBlock(), true);
Douglas Gregor5656e142009-11-24 21:15:44 +0000445
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000446 // The LoopHeader typically is just a branch if we skipped emitting
447 // a branch, try to erase it.
John McCallf1549f62010-07-06 01:34:17 +0000448 if (!EmitBoolCondBranch)
John McCallff8e1152010-07-23 21:56:41 +0000449 SimplifyForwardingBlocks(LoopHeader.getBlock());
Reid Spencer5f016e22007-07-11 17:01:13 +0000450}
451
452void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000453 JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
454 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Chris Lattnerda138702007-07-16 21:28:45 +0000456 // Store the blocks to use for break and continue.
John McCallf1549f62010-07-06 01:34:17 +0000457 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
Mike Stump1eb44332009-09-09 15:08:12 +0000458
John McCallf1549f62010-07-06 01:34:17 +0000459 // Emit the body of the loop.
460 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
461 EmitBlock(LoopBody);
462 {
463 RunCleanupsScope BodyScope(*this);
464 EmitStmt(S.getBody());
465 }
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Anders Carlssone4b6d342009-02-10 05:52:02 +0000467 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000468
John McCallff8e1152010-07-23 21:56:41 +0000469 EmitBlock(LoopCond.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
472 // after each execution of the loop body."
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 // Evaluate the conditional in the while header.
475 // C99 6.8.5p2/p4: The first substatement is executed if the expression
476 // compares unequal to 0. The condition must be a scalar type.
477 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000478
479 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
480 // to correctly handle break/continue though.
481 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000482 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel05f6e6b2007-10-09 20:33:39 +0000483 if (C->isZero())
484 EmitBoolCondBranch = false;
485
Reid Spencer5f016e22007-07-11 17:01:13 +0000486 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000487 if (EmitBoolCondBranch)
John McCallff8e1152010-07-23 21:56:41 +0000488 Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 // Emit the exit block.
John McCallff8e1152010-07-23 21:56:41 +0000491 EmitBlock(LoopExit.getBlock());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000492
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000493 // The DoCond block typically is just a branch if we skipped
494 // emitting a branch, try to erase it.
495 if (!EmitBoolCondBranch)
John McCallff8e1152010-07-23 21:56:41 +0000496 SimplifyForwardingBlocks(LoopCond.getBlock());
Reid Spencer5f016e22007-07-11 17:01:13 +0000497}
498
499void CodeGenFunction::EmitForStmt(const ForStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000500 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
501
502 RunCleanupsScope ForScope(*this);
Chris Lattnerda138702007-07-16 21:28:45 +0000503
Devang Patel0554e0e2010-08-25 00:28:56 +0000504 CGDebugInfo *DI = getDebugInfo();
505 if (DI) {
506 DI->setLocation(S.getSourceRange().getBegin());
507 DI->EmitRegionStart(Builder);
508 }
509
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 // Evaluate the first part before the loop.
511 if (S.getInit())
512 EmitStmt(S.getInit());
513
514 // Start the loop with a block that tests the condition.
John McCallf1549f62010-07-06 01:34:17 +0000515 // If there's an increment, the continue scope will be overwritten
516 // later.
517 JumpDest Continue = getJumpDestInCurrentScope("for.cond");
John McCallff8e1152010-07-23 21:56:41 +0000518 llvm::BasicBlock *CondBlock = Continue.getBlock();
Reid Spencer5f016e22007-07-11 17:01:13 +0000519 EmitBlock(CondBlock);
520
Douglas Gregord9752062009-11-25 01:51:31 +0000521 // Create a cleanup scope for the condition variable cleanups.
John McCallf1549f62010-07-06 01:34:17 +0000522 RunCleanupsScope ConditionScope(*this);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000523
Douglas Gregord9752062009-11-25 01:51:31 +0000524 llvm::Value *BoolCondVal = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000525 if (S.getCond()) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000526 // If the for statement has a condition scope, emit the local variable
527 // declaration.
John McCallff8e1152010-07-23 21:56:41 +0000528 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Douglas Gregord9752062009-11-25 01:51:31 +0000529 if (S.getConditionVariable()) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000530 EmitLocalBlockVarDecl(*S.getConditionVariable());
Douglas Gregord9752062009-11-25 01:51:31 +0000531 }
John McCallf1549f62010-07-06 01:34:17 +0000532
533 // If there are any cleanups between here and the loop-exit scope,
534 // create a block to stage a loop exit along.
535 if (ForScope.requiresCleanups())
536 ExitBlock = createBasicBlock("for.cond.cleanup");
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000537
Reid Spencer5f016e22007-07-11 17:01:13 +0000538 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000539 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Chris Lattner31a09842008-11-12 08:04:58 +0000541 // C99 6.8.5p2/p4: The first substatement is executed if the expression
542 // compares unequal to 0. The condition must be a scalar type.
Douglas Gregord9752062009-11-25 01:51:31 +0000543 BoolCondVal = EvaluateExprAsBool(S.getCond());
John McCallf1549f62010-07-06 01:34:17 +0000544 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
545
John McCallff8e1152010-07-23 21:56:41 +0000546 if (ExitBlock != LoopExit.getBlock()) {
John McCallf1549f62010-07-06 01:34:17 +0000547 EmitBlock(ExitBlock);
548 EmitBranchThroughCleanup(LoopExit);
549 }
Mike Stump1eb44332009-09-09 15:08:12 +0000550
551 EmitBlock(ForBody);
Reid Spencer5f016e22007-07-11 17:01:13 +0000552 } else {
553 // Treat it as a non-zero constant. Don't even create a new block for the
554 // body, just fall into it.
555 }
556
Mike Stump1eb44332009-09-09 15:08:12 +0000557 // If the for loop doesn't have an increment we can just use the
John McCallf1549f62010-07-06 01:34:17 +0000558 // condition as the continue block. Otherwise we'll need to create
559 // a block for it (in the current scope, i.e. in the scope of the
560 // condition), and that we will become our continue block.
Chris Lattnerda138702007-07-16 21:28:45 +0000561 if (S.getInc())
John McCallf1549f62010-07-06 01:34:17 +0000562 Continue = getJumpDestInCurrentScope("for.inc");
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Chris Lattnerda138702007-07-16 21:28:45 +0000564 // Store the blocks to use for break and continue.
John McCallf1549f62010-07-06 01:34:17 +0000565 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Mike Stump3e9da662009-02-07 23:02:10 +0000566
Douglas Gregord9752062009-11-25 01:51:31 +0000567 {
568 // Create a separate cleanup scope for the body, in case it is not
569 // a compound statement.
John McCallf1549f62010-07-06 01:34:17 +0000570 RunCleanupsScope BodyScope(*this);
Douglas Gregord9752062009-11-25 01:51:31 +0000571 EmitStmt(S.getBody());
572 }
Chris Lattnerda138702007-07-16 21:28:45 +0000573
Reid Spencer5f016e22007-07-11 17:01:13 +0000574 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000575 if (S.getInc()) {
John McCallff8e1152010-07-23 21:56:41 +0000576 EmitBlock(Continue.getBlock());
Chris Lattner883f6a72007-08-11 00:04:45 +0000577 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000578 }
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Douglas Gregor45d3fe12010-05-21 18:36:48 +0000580 BreakContinueStack.pop_back();
Douglas Gregord9752062009-11-25 01:51:31 +0000581
John McCallf1549f62010-07-06 01:34:17 +0000582 ConditionScope.ForceCleanup();
583 EmitBranch(CondBlock);
584
585 ForScope.ForceCleanup();
586
Devang Patelbbd9fa42009-10-06 18:36:08 +0000587 if (DI) {
588 DI->setLocation(S.getSourceRange().getEnd());
Devang Patel4d939e62010-07-20 22:20:10 +0000589 DI->EmitRegionEnd(Builder);
Devang Patelbbd9fa42009-10-06 18:36:08 +0000590 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000591
Chris Lattnerda138702007-07-16 21:28:45 +0000592 // Emit the fall-through block.
John McCallff8e1152010-07-23 21:56:41 +0000593 EmitBlock(LoopExit.getBlock(), true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000594}
595
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000596void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
597 if (RV.isScalar()) {
598 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
599 } else if (RV.isAggregate()) {
600 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
601 } else {
602 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
603 }
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000604 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000605}
606
Reid Spencer5f016e22007-07-11 17:01:13 +0000607/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
608/// if the function returns void, or may be missing one if the function returns
609/// non-void. Fun stuff :).
610void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000611 // Emit the result value, even if unused, to evalute the side effects.
612 const Expr *RV = S.getRetValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000614 // FIXME: Clean this up by using an LValue for ReturnTemp,
615 // EmitStoreThroughLValue, and EmitAnyExpr.
Douglas Gregord86c4772010-05-15 06:46:45 +0000616 if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable() &&
617 !Target.useGlobalsForAutomaticVariables()) {
618 // Apply the named return value optimization for this return statement,
619 // which means doing nothing: the appropriate result has already been
620 // constructed into the NRVO variable.
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000621
622 // If there is an NRVO flag for this variable, set it to 1 into indicate
623 // that the cleanup code should not destroy the variable.
624 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()]) {
625 const llvm::Type *BoolTy = llvm::Type::getInt1Ty(VMContext);
626 llvm::Value *One = llvm::ConstantInt::get(BoolTy, 1);
627 Builder.CreateStore(One, NRVOFlag);
628 }
Douglas Gregord86c4772010-05-15 06:46:45 +0000629 } else if (!ReturnValue) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000630 // Make sure not to return anything, but evaluate the expression
631 // for side effects.
632 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000633 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000634 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000635 // Do nothing (return value is left uninitialized)
Eli Friedmand54b6ac2009-05-27 04:56:12 +0000636 } else if (FnRetTy->isReferenceType()) {
637 // If this function returns a reference, take the address of the expression
638 // rather than the value.
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000639 RValue Result = EmitReferenceBindingToExpr(RV, /*InitializedDecl=*/0);
Douglas Gregor33fd1fc2010-03-24 23:14:04 +0000640 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
Chris Lattner4b0029d2007-08-26 07:14:44 +0000641 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000642 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000643 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000644 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 } else {
John McCall558d2ab2010-09-15 10:14:12 +0000646 EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, false, true));
Reid Spencer5f016e22007-07-11 17:01:13 +0000647 }
Eli Friedman144ac612008-05-22 01:22:33 +0000648
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000649 EmitBranchThroughCleanup(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000650}
651
652void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Daniel Dunbar25b6ebf2009-07-19 07:03:11 +0000653 // As long as debug info is modeled with instructions, we have to ensure we
654 // have a place to insert here and write the stop point here.
655 if (getDebugInfo()) {
656 EnsureInsertPoint();
657 EmitStopPoint(&S);
658 }
659
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000660 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
661 I != E; ++I)
662 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000663}
Chris Lattnerda138702007-07-16 21:28:45 +0000664
Daniel Dunbar09124252008-11-12 08:21:33 +0000665void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000666 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
667
Daniel Dunbar09124252008-11-12 08:21:33 +0000668 // If this code is reachable then emit a stop point (if generating
669 // debug info). We have to do this ourselves because we are on the
670 // "simple" statement path.
671 if (HaveInsertPoint())
672 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000673
John McCallf1549f62010-07-06 01:34:17 +0000674 JumpDest Block = BreakContinueStack.back().BreakBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000675 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000676}
677
Daniel Dunbar09124252008-11-12 08:21:33 +0000678void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000679 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
680
Daniel Dunbar09124252008-11-12 08:21:33 +0000681 // If this code is reachable then emit a stop point (if generating
682 // debug info). We have to do this ourselves because we are on the
683 // "simple" statement path.
684 if (HaveInsertPoint())
685 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000686
John McCallf1549f62010-07-06 01:34:17 +0000687 JumpDest Block = BreakContinueStack.back().ContinueBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000688 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000689}
Devang Patel51b09f22007-10-04 23:45:31 +0000690
Devang Patelc049e4f2007-10-08 20:57:48 +0000691/// EmitCaseStmtRange - If case statement range is not too big then
692/// add multiple cases to switch instruction, one for each value within
693/// the range. If range is too big then emit "if" condition check.
694void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000695 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000696
Anders Carlsson51fe9962008-11-22 21:04:56 +0000697 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
698 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000699
Daniel Dunbar16f23572008-07-25 01:11:38 +0000700 // Emit the code for this case. We do this first to make sure it is
701 // properly chained from our predecessor before generating the
702 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000703 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000704 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
705 EmitStmt(S.getSubStmt());
706
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000707 // If range is empty, do nothing.
708 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
709 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000710
711 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000712 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000713 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
714 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000715 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000716 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, LHS), CaseDest);
Devang Patel2d79d0f2007-10-05 20:54:07 +0000717 LHS++;
718 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000719 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000720 }
721
Daniel Dunbar16f23572008-07-25 01:11:38 +0000722 // The range is too big. Emit "if" condition into a new block,
723 // making sure to save and restore the current insertion point.
724 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000725
Daniel Dunbar16f23572008-07-25 01:11:38 +0000726 // Push this test onto the chain of range checks (which terminates
727 // in the default basic block). The switch's default will be changed
728 // to the top of this chain after switch emission is complete.
729 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000730 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000731
Daniel Dunbar16f23572008-07-25 01:11:38 +0000732 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
733 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000734
735 // Emit range check.
Mike Stump1eb44332009-09-09 15:08:12 +0000736 llvm::Value *Diff =
737 Builder.CreateSub(SwitchInsn->getCondition(),
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000738 llvm::ConstantInt::get(VMContext, LHS), "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000739 llvm::Value *Cond =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000740 Builder.CreateICmpULE(Diff,
741 llvm::ConstantInt::get(VMContext, Range), "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000742 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
743
Daniel Dunbar16f23572008-07-25 01:11:38 +0000744 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000745 if (RestoreBB)
746 Builder.SetInsertPoint(RestoreBB);
747 else
748 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000749}
750
751void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
752 if (S.getRHS()) {
753 EmitCaseStmtRange(S);
754 return;
755 }
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000757 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000758 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000759 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000760 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Chris Lattner5512f282009-03-04 04:46:18 +0000762 // Recursively emitting the statement is acceptable, but is not wonderful for
763 // code where we have many case statements nested together, i.e.:
764 // case 1:
765 // case 2:
766 // case 3: etc.
767 // Handling this recursively will create a new block for each case statement
768 // that falls through to the next case which is IR intensive. It also causes
769 // deep recursion which can run into stack depth limitations. Handle
770 // sequential non-range case statements specially.
771 const CaseStmt *CurCase = &S;
772 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
773
774 // Otherwise, iteratively add consequtive cases to this switch stmt.
775 while (NextCase && NextCase->getRHS() == 0) {
776 CurCase = NextCase;
777 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000778 SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
Chris Lattner5512f282009-03-04 04:46:18 +0000779
780 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
781 }
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Chris Lattner5512f282009-03-04 04:46:18 +0000783 // Normal default recursion for non-cases.
784 EmitStmt(CurCase->getSubStmt());
Devang Patel51b09f22007-10-04 23:45:31 +0000785}
786
787void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000788 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Mike Stump1eb44332009-09-09 15:08:12 +0000789 assert(DefaultBlock->empty() &&
Daniel Dunbar55e87422008-11-11 02:29:29 +0000790 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000791 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000792 EmitStmt(S.getSubStmt());
793}
794
795void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000796 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
797
798 RunCleanupsScope ConditionScope(*this);
Douglas Gregord3d53012009-11-24 17:07:59 +0000799
800 if (S.getConditionVariable())
801 EmitLocalBlockVarDecl(*S.getConditionVariable());
802
Devang Patel51b09f22007-10-04 23:45:31 +0000803 llvm::Value *CondV = EmitScalarExpr(S.getCond());
804
805 // Handle nested switch statements.
806 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000807 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000808
Daniel Dunbar16f23572008-07-25 01:11:38 +0000809 // Create basic block to hold stuff that comes after switch
810 // statement. We also need to create a default block now so that
811 // explicit case ranges tests can have a place to jump to on
812 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000813 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000814 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
815 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000816
Daniel Dunbar09124252008-11-12 08:21:33 +0000817 // Clear the insertion point to indicate we are in unreachable code.
818 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000819
Devang Patele9b8c0a2007-10-30 20:59:40 +0000820 // All break statements jump to NextBlock. If BreakContinueStack is non empty
821 // then reuse last ContinueBlock.
John McCallf1549f62010-07-06 01:34:17 +0000822 JumpDest OuterContinue;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000823 if (!BreakContinueStack.empty())
John McCallf1549f62010-07-06 01:34:17 +0000824 OuterContinue = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000825
John McCallf1549f62010-07-06 01:34:17 +0000826 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
Devang Patel51b09f22007-10-04 23:45:31 +0000827
828 // Emit switch body.
829 EmitStmt(S.getBody());
Mike Stump1eb44332009-09-09 15:08:12 +0000830
Anders Carlssone4b6d342009-02-10 05:52:02 +0000831 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +0000832
Daniel Dunbar16f23572008-07-25 01:11:38 +0000833 // Update the default block in case explicit case range tests have
834 // been chained on top.
835 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000836
John McCallf1549f62010-07-06 01:34:17 +0000837 // If a default was never emitted:
Daniel Dunbar16f23572008-07-25 01:11:38 +0000838 if (!DefaultBlock->getParent()) {
John McCallf1549f62010-07-06 01:34:17 +0000839 // If we have cleanups, emit the default block so that there's a
840 // place to jump through the cleanups from.
841 if (ConditionScope.requiresCleanups()) {
842 EmitBlock(DefaultBlock);
843
844 // Otherwise, just forward the default block to the switch end.
845 } else {
John McCallff8e1152010-07-23 21:56:41 +0000846 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000847 delete DefaultBlock;
848 }
Daniel Dunbar16f23572008-07-25 01:11:38 +0000849 }
Devang Patel51b09f22007-10-04 23:45:31 +0000850
John McCallff8e1152010-07-23 21:56:41 +0000851 ConditionScope.ForceCleanup();
852
Daniel Dunbar16f23572008-07-25 01:11:38 +0000853 // Emit continuation.
John McCallff8e1152010-07-23 21:56:41 +0000854 EmitBlock(SwitchExit.getBlock(), true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000855
Devang Patel51b09f22007-10-04 23:45:31 +0000856 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000857 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000858}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000859
Chris Lattner2819fa82009-04-26 17:57:12 +0000860static std::string
Daniel Dunbar444be732009-11-13 05:51:54 +0000861SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
Chris Lattner2819fa82009-04-26 17:57:12 +0000862 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000863 std::string Result;
John Thompsonef44e112010-08-10 19:20:14 +0000864 std::string tmp;
Mike Stump1eb44332009-09-09 15:08:12 +0000865
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000866 while (*Constraint) {
867 switch (*Constraint) {
868 default:
John Thompsonef44e112010-08-10 19:20:14 +0000869 tmp = Target.convertConstraint(*Constraint);
870 if (Result.find(tmp) == std::string::npos) // Combine unique constraints
871 Result += tmp;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000872 break;
873 // Ignore these
874 case '*':
875 case '?':
876 case '!':
John Thompsonef44e112010-08-10 19:20:14 +0000877 case '=': // Will see this and the following in mult-alt constraints.
878 case '+':
879 break;
Eli Friedmana7e68452010-08-22 01:00:03 +0000880 case ',': // FIXME - Until the back-end properly supports
881 return Result; // multiple alternative constraints, we stop here.
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000882 break;
883 case 'g':
884 Result += "imr";
885 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000886 case '[': {
Chris Lattner2819fa82009-04-26 17:57:12 +0000887 assert(OutCons &&
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000888 "Must pass output names to constraints with a symbolic name");
889 unsigned Index;
Mike Stump1eb44332009-09-09 15:08:12 +0000890 bool result = Target.resolveSymbolicName(Constraint,
Chris Lattner2819fa82009-04-26 17:57:12 +0000891 &(*OutCons)[0],
892 OutCons->size(), Index);
Chris Lattner53637652009-01-21 07:35:26 +0000893 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000894 Result += llvm::utostr(Index);
895 break;
896 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000897 }
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000899 Constraint++;
900 }
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000902 return Result;
903}
904
Eli Friedman6d7cfd72010-07-16 00:55:21 +0000905llvm::Value*
906CodeGenFunction::EmitAsmInputLValue(const AsmStmt &S,
907 const TargetInfo::ConstraintInfo &Info,
908 LValue InputValue, QualType InputType,
909 std::string &ConstraintStr) {
Anders Carlsson63471722009-01-11 19:32:54 +0000910 llvm::Value *Arg;
Mike Stump1eb44332009-09-09 15:08:12 +0000911 if (Info.allowsRegister() || !Info.allowsMemory()) {
Eli Friedman6d7cfd72010-07-16 00:55:21 +0000912 if (!CodeGenFunction::hasAggregateLLVMType(InputType)) {
913 Arg = EmitLoadOfLValue(InputValue, InputType).getScalarVal();
Anders Carlsson63471722009-01-11 19:32:54 +0000914 } else {
Eli Friedman6d7cfd72010-07-16 00:55:21 +0000915 const llvm::Type *Ty = ConvertType(InputType);
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000916 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
917 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
Owen Anderson0032b272009-08-13 21:57:51 +0000918 Ty = llvm::IntegerType::get(VMContext, Size);
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000919 Ty = llvm::PointerType::getUnqual(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Eli Friedman6d7cfd72010-07-16 00:55:21 +0000921 Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
922 Ty));
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000923 } else {
Eli Friedman6d7cfd72010-07-16 00:55:21 +0000924 Arg = InputValue.getAddress();
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000925 ConstraintStr += '*';
926 }
Anders Carlsson63471722009-01-11 19:32:54 +0000927 }
928 } else {
Eli Friedman6d7cfd72010-07-16 00:55:21 +0000929 Arg = InputValue.getAddress();
Anders Carlsson63471722009-01-11 19:32:54 +0000930 ConstraintStr += '*';
931 }
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Anders Carlsson63471722009-01-11 19:32:54 +0000933 return Arg;
934}
935
Eli Friedman6d7cfd72010-07-16 00:55:21 +0000936llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
937 const TargetInfo::ConstraintInfo &Info,
938 const Expr *InputExpr,
939 std::string &ConstraintStr) {
940 if (Info.allowsRegister() || !Info.allowsMemory())
941 if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType()))
942 return EmitScalarExpr(InputExpr);
943
944 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
945 LValue Dest = EmitLValue(InputExpr);
946 return EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(), ConstraintStr);
947}
948
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000949void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Chris Lattner458cd9c2009-03-10 23:21:44 +0000950 // Analyze the asm string to decompose it into its pieces. We know that Sema
951 // has already done this, so it is guaranteed to be successful.
952 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +0000953 unsigned DiagOffs;
954 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Chris Lattner458cd9c2009-03-10 23:21:44 +0000956 // Assemble the pieces into the final asm string.
957 std::string AsmString;
958 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
959 if (Pieces[i].isString())
960 AsmString += Pieces[i].getString();
961 else if (Pieces[i].getModifier() == '\0')
962 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
963 else
964 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
965 Pieces[i].getModifier() + '}';
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000966 }
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Chris Lattner481fef92009-05-03 07:05:00 +0000968 // Get all the output and input constraints together.
969 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
970 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
971
Mike Stump1eb44332009-09-09 15:08:12 +0000972 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +0000973 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
974 S.getOutputName(i));
Chris Lattnerb9922592010-03-03 21:52:23 +0000975 bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid;
976 assert(IsValid && "Failed to parse output constraint");
Chris Lattner481fef92009-05-03 07:05:00 +0000977 OutputConstraintInfos.push_back(Info);
Mike Stump1eb44332009-09-09 15:08:12 +0000978 }
979
Chris Lattner481fef92009-05-03 07:05:00 +0000980 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
981 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
982 S.getInputName(i));
Chris Lattnerb9922592010-03-03 21:52:23 +0000983 bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(),
984 S.getNumOutputs(), Info);
985 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
Chris Lattner481fef92009-05-03 07:05:00 +0000986 InputConstraintInfos.push_back(Info);
987 }
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000989 std::string Constraints;
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Chris Lattnerede9d902009-05-03 07:53:25 +0000991 std::vector<LValue> ResultRegDests;
992 std::vector<QualType> ResultRegQualTys;
Chris Lattnera077b5c2009-05-03 08:21:20 +0000993 std::vector<const llvm::Type *> ResultRegTypes;
994 std::vector<const llvm::Type *> ResultTruncRegTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000995 std::vector<const llvm::Type*> ArgTypes;
996 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000997
998 // Keep track of inout constraints.
999 std::string InOutConstraints;
1000 std::vector<llvm::Value*> InOutArgs;
1001 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +00001002
Mike Stump1eb44332009-09-09 15:08:12 +00001003 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +00001004 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
Anders Carlsson03eb5432009-01-27 20:38:24 +00001005
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001006 // Simplify the output constraint.
Chris Lattner481fef92009-05-03 07:05:00 +00001007 std::string OutputConstraint(S.getOutputConstraint(i));
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +00001008 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Chris Lattner810f6d52009-03-13 17:38:01 +00001010 const Expr *OutExpr = S.getOutputExpr(i);
1011 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Chris Lattner810f6d52009-03-13 17:38:01 +00001013 LValue Dest = EmitLValue(OutExpr);
Chris Lattnerede9d902009-05-03 07:53:25 +00001014 if (!Constraints.empty())
Anders Carlssonbad3a942009-05-01 00:16:04 +00001015 Constraints += ',';
1016
Chris Lattnera077b5c2009-05-03 08:21:20 +00001017 // If this is a register output, then make the inline asm return it
1018 // by-value. If this is a memory result, return the value by-reference.
Chris Lattnerede9d902009-05-03 07:53:25 +00001019 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
Chris Lattnera077b5c2009-05-03 08:21:20 +00001020 Constraints += "=" + OutputConstraint;
Chris Lattnerede9d902009-05-03 07:53:25 +00001021 ResultRegQualTys.push_back(OutExpr->getType());
1022 ResultRegDests.push_back(Dest);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001023 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1024 ResultTruncRegTypes.push_back(ResultRegTypes.back());
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Chris Lattnera077b5c2009-05-03 08:21:20 +00001026 // If this output is tied to an input, and if the input is larger, then
1027 // we need to set the actual result type of the inline asm node to be the
1028 // same as the input type.
1029 if (Info.hasMatchingInput()) {
Chris Lattnerebfc9852009-05-03 08:38:58 +00001030 unsigned InputNo;
1031 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1032 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
Chris Lattneraab64d02010-04-23 17:27:29 +00001033 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
Chris Lattnera077b5c2009-05-03 08:21:20 +00001034 break;
Chris Lattnerebfc9852009-05-03 08:38:58 +00001035 }
1036 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Chris Lattnera077b5c2009-05-03 08:21:20 +00001038 QualType InputTy = S.getInputExpr(InputNo)->getType();
Chris Lattneraab64d02010-04-23 17:27:29 +00001039 QualType OutputType = OutExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Chris Lattnera077b5c2009-05-03 08:21:20 +00001041 uint64_t InputSize = getContext().getTypeSize(InputTy);
Chris Lattneraab64d02010-04-23 17:27:29 +00001042 if (getContext().getTypeSize(OutputType) < InputSize) {
1043 // Form the asm to return the value as a larger integer or fp type.
1044 ResultRegTypes.back() = ConvertType(InputTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001045 }
1046 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001047 } else {
1048 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +00001049 Args.push_back(Dest.getAddress());
Anders Carlssonf39a4212008-02-05 20:01:53 +00001050 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001051 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001052 }
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Chris Lattner44def072009-04-26 07:16:29 +00001054 if (Info.isReadWrite()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +00001055 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +00001056
Anders Carlssonfca93612009-08-04 18:18:36 +00001057 const Expr *InputExpr = S.getOutputExpr(i);
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001058 llvm::Value *Arg = EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(),
1059 InOutConstraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001060
Chris Lattner44def072009-04-26 07:16:29 +00001061 if (Info.allowsRegister())
Anders Carlsson9f2505b2009-01-11 21:23:27 +00001062 InOutConstraints += llvm::utostr(i);
1063 else
1064 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +00001065
Anders Carlssonfca93612009-08-04 18:18:36 +00001066 InOutArgTypes.push_back(Arg->getType());
1067 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001068 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001069 }
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001071 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001073 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1074 const Expr *InputExpr = S.getInputExpr(i);
1075
Chris Lattner481fef92009-05-03 07:05:00 +00001076 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1077
Chris Lattnerede9d902009-05-03 07:53:25 +00001078 if (!Constraints.empty())
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001079 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001081 // Simplify the input constraint.
Chris Lattner481fef92009-05-03 07:05:00 +00001082 std::string InputConstraint(S.getInputConstraint(i));
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001083 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
Chris Lattner2819fa82009-04-26 17:57:12 +00001084 &OutputConstraintInfos);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001085
Anders Carlsson63471722009-01-11 19:32:54 +00001086 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Chris Lattner4df4ee02009-05-03 07:27:51 +00001088 // If this input argument is tied to a larger output result, extend the
1089 // input to be the same size as the output. The LLVM backend wants to see
1090 // the input and output of a matching constraint be the same size. Note
1091 // that GCC does not define what the top bits are here. We use zext because
1092 // that is usually cheaper, but LLVM IR should really get an anyext someday.
1093 if (Info.hasTiedOperand()) {
1094 unsigned Output = Info.getTiedOperand();
Chris Lattneraab64d02010-04-23 17:27:29 +00001095 QualType OutputType = S.getOutputExpr(Output)->getType();
Chris Lattner4df4ee02009-05-03 07:27:51 +00001096 QualType InputTy = InputExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Chris Lattneraab64d02010-04-23 17:27:29 +00001098 if (getContext().getTypeSize(OutputType) >
Chris Lattner4df4ee02009-05-03 07:27:51 +00001099 getContext().getTypeSize(InputTy)) {
1100 // Use ptrtoint as appropriate so that we can do our extension.
1101 if (isa<llvm::PointerType>(Arg->getType()))
Chris Lattner77b89b82010-06-27 07:15:29 +00001102 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
Chris Lattneraab64d02010-04-23 17:27:29 +00001103 const llvm::Type *OutputTy = ConvertType(OutputType);
1104 if (isa<llvm::IntegerType>(OutputTy))
1105 Arg = Builder.CreateZExt(Arg, OutputTy);
1106 else
1107 Arg = Builder.CreateFPExt(Arg, OutputTy);
Chris Lattner4df4ee02009-05-03 07:27:51 +00001108 }
1109 }
Mike Stump1eb44332009-09-09 15:08:12 +00001110
1111
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001112 ArgTypes.push_back(Arg->getType());
1113 Args.push_back(Arg);
1114 Constraints += InputConstraint;
1115 }
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Anders Carlssonf39a4212008-02-05 20:01:53 +00001117 // Append the "input" part of inout constraints last.
1118 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1119 ArgTypes.push_back(InOutArgTypes[i]);
1120 Args.push_back(InOutArgs[i]);
1121 }
1122 Constraints += InOutConstraints;
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001124 // Clobbers
1125 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
Anders Carlsson83c021c2010-01-30 19:12:25 +00001126 llvm::StringRef Clobber = S.getClobber(i)->getString();
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001127
Anders Carlsson83c021c2010-01-30 19:12:25 +00001128 Clobber = Target.getNormalizedGCCRegisterName(Clobber);
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Anders Carlssonea041752008-02-06 00:11:32 +00001130 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001131 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Anders Carlssonea041752008-02-06 00:11:32 +00001133 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001134 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001135 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001136 }
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001138 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +00001139 std::string MachineClobbers = Target.getClobbers();
1140 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001141 if (!Constraints.empty())
1142 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00001143 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001144 }
Anders Carlssonbad3a942009-05-01 00:16:04 +00001145
1146 const llvm::Type *ResultType;
Chris Lattnera077b5c2009-05-03 08:21:20 +00001147 if (ResultRegTypes.empty())
Owen Anderson0032b272009-08-13 21:57:51 +00001148 ResultType = llvm::Type::getVoidTy(VMContext);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001149 else if (ResultRegTypes.size() == 1)
1150 ResultType = ResultRegTypes[0];
Anders Carlssonbad3a942009-05-01 00:16:04 +00001151 else
Owen Anderson47a434f2009-08-05 23:18:46 +00001152 ResultType = llvm::StructType::get(VMContext, ResultRegTypes);
Mike Stump1eb44332009-09-09 15:08:12 +00001153
1154 const llvm::FunctionType *FTy =
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001155 llvm::FunctionType::get(ResultType, ArgTypes, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001156
1157 llvm::InlineAsm *IA =
1158 llvm::InlineAsm::get(FTy, AsmString, Constraints,
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001159 S.isVolatile() || S.getNumOutputs() == 0);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001160 llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end());
Anders Carlssonbc0822b2009-03-02 19:58:15 +00001161 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Chris Lattnerfc1a9c32010-04-07 05:46:54 +00001163 // Slap the source location of the inline asm into a !srcloc metadata on the
1164 // call.
1165 unsigned LocID = S.getAsmString()->getLocStart().getRawEncoding();
1166 llvm::Value *LocIDC =
Chris Lattner77b89b82010-06-27 07:15:29 +00001167 llvm::ConstantInt::get(Int32Ty, LocID);
Chris Lattnerfc1a9c32010-04-07 05:46:54 +00001168 Result->setMetadata("srcloc", llvm::MDNode::get(VMContext, &LocIDC, 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Chris Lattnera077b5c2009-05-03 08:21:20 +00001170 // Extract all of the register value results from the asm.
1171 std::vector<llvm::Value*> RegResults;
1172 if (ResultRegTypes.size() == 1) {
1173 RegResults.push_back(Result);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001174 } else {
Chris Lattnera077b5c2009-05-03 08:21:20 +00001175 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
Anders Carlssonbad3a942009-05-01 00:16:04 +00001176 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
Chris Lattnera077b5c2009-05-03 08:21:20 +00001177 RegResults.push_back(Tmp);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001178 }
1179 }
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Chris Lattnera077b5c2009-05-03 08:21:20 +00001181 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1182 llvm::Value *Tmp = RegResults[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Chris Lattnera077b5c2009-05-03 08:21:20 +00001184 // If the result type of the LLVM IR asm doesn't match the result type of
1185 // the expression, do the conversion.
1186 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1187 const llvm::Type *TruncTy = ResultTruncRegTypes[i];
Chris Lattneraab64d02010-04-23 17:27:29 +00001188
1189 // Truncate the integer result to the right size, note that TruncTy can be
1190 // a pointer.
1191 if (TruncTy->isFloatingPointTy())
1192 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00001193 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
Chris Lattneraab64d02010-04-23 17:27:29 +00001194 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
1195 Tmp = Builder.CreateTrunc(Tmp, llvm::IntegerType::get(VMContext,
1196 (unsigned)ResSize));
Chris Lattnera077b5c2009-05-03 08:21:20 +00001197 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00001198 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
1199 uint64_t TmpSize =CGM.getTargetData().getTypeSizeInBits(Tmp->getType());
1200 Tmp = Builder.CreatePtrToInt(Tmp, llvm::IntegerType::get(VMContext,
1201 (unsigned)TmpSize));
1202 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1203 } else if (TruncTy->isIntegerTy()) {
1204 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001205 }
1206 }
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Chris Lattnera077b5c2009-05-03 08:21:20 +00001208 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i],
1209 ResultRegQualTys[i]);
1210 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001211}