blob: b8b2cd9f3e76c97a735eb8c624751707d5d23aa1 [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"
Peter Collingbourne4b93d662011-02-19 23:03:58 +000017#include "TargetInfo.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/StmtVisitor.h"
Chris Lattner7d22bf02009-03-05 08:04:57 +000019#include "clang/Basic/PrettyStackTrace.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000020#include "clang/Basic/TargetInfo.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000021#include "llvm/ADT/StringExtras.h"
Anders Carlsson17d28a32008-12-12 05:52:00 +000022#include "llvm/InlineAsm.h"
23#include "llvm/Intrinsics.h"
Anders Carlssonebaae2a2009-01-12 02:22:13 +000024#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025using namespace clang;
26using namespace CodeGen;
27
28//===----------------------------------------------------------------------===//
29// Statement Emission
30//===----------------------------------------------------------------------===//
31
Daniel Dunbar09124252008-11-12 08:21:33 +000032void CodeGenFunction::EmitStopPoint(const Stmt *S) {
Anders Carlssone896d982009-02-13 08:11:52 +000033 if (CGDebugInfo *DI = getDebugInfo()) {
Devang Patel60e4fd92010-05-12 00:39:34 +000034 if (isa<DeclStmt>(S))
35 DI->setLocation(S->getLocEnd());
36 else
37 DI->setLocation(S->getLocStart());
Devang Patel5a6fbcf2010-07-22 22:29:16 +000038 DI->UpdateLineDirectiveRegion(Builder);
Devang Patel4d939e62010-07-20 22:20:10 +000039 DI->EmitStopPoint(Builder);
Daniel Dunbar09124252008-11-12 08:21:33 +000040 }
41}
42
Reid Spencer5f016e22007-07-11 17:01:13 +000043void CodeGenFunction::EmitStmt(const Stmt *S) {
44 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000045
Daniel Dunbar09124252008-11-12 08:21:33 +000046 // Check if we can handle this without bothering to generate an
47 // insert point or debug info.
48 if (EmitSimpleStmt(S))
49 return;
50
Daniel Dunbard286f052009-07-19 06:58:07 +000051 // Check if we are generating unreachable code.
52 if (!HaveInsertPoint()) {
53 // If so, and the statement doesn't contain a label, then we do not need to
54 // generate actual code. This is safe because (1) the current point is
55 // unreachable, so we don't need to execute the code, and (2) we've already
56 // handled the statements which update internal data structures (like the
57 // local variable map) which could be used by subsequent statements.
58 if (!ContainsLabel(S)) {
59 // Verify that any decl statements were handled as simple, they may be in
60 // scope of subsequent reachable statements.
61 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
62 return;
63 }
64
65 // Otherwise, make a new block to hold the code.
66 EnsureInsertPoint();
67 }
68
Daniel Dunbar09124252008-11-12 08:21:33 +000069 // Generate a stoppoint if we are emitting debug info.
70 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000071
Reid Spencer5f016e22007-07-11 17:01:13 +000072 switch (S->getStmtClass()) {
John McCall2a416372010-12-05 02:00:02 +000073 case Stmt::NoStmtClass:
74 case Stmt::CXXCatchStmtClass:
John McCall2a416372010-12-05 02:00:02 +000075 llvm_unreachable("invalid statement class to emit generically");
76 case Stmt::NullStmtClass:
77 case Stmt::CompoundStmtClass:
78 case Stmt::DeclStmtClass:
79 case Stmt::LabelStmtClass:
80 case Stmt::GotoStmtClass:
81 case Stmt::BreakStmtClass:
82 case Stmt::ContinueStmtClass:
83 case Stmt::DefaultStmtClass:
84 case Stmt::CaseStmtClass:
85 llvm_unreachable("should have emitted these statements as simple");
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000086
John McCall2a416372010-12-05 02:00:02 +000087#define STMT(Type, Base)
88#define ABSTRACT_STMT(Op)
89#define EXPR(Type, Base) \
90 case Stmt::Type##Class:
91#include "clang/AST/StmtNodes.inc"
John McCallcd5b22e2011-01-12 03:41:02 +000092 {
93 // Remember the block we came in on.
94 llvm::BasicBlock *incoming = Builder.GetInsertBlock();
95 assert(incoming && "expression emission must have an insertion point");
96
John McCall2a416372010-12-05 02:00:02 +000097 EmitIgnoredExpr(cast<Expr>(S));
Mike Stump1eb44332009-09-09 15:08:12 +000098
John McCallcd5b22e2011-01-12 03:41:02 +000099 llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
100 assert(outgoing && "expression emission cleared block!");
101
102 // The expression emitters assume (reasonably!) that the insertion
103 // point is always set. To maintain that, the call-emission code
104 // for noreturn functions has to enter a new block with no
105 // predecessors. We want to kill that block and mark the current
106 // insertion point unreachable in the common case of a call like
107 // "exit();". Since expression emission doesn't otherwise create
108 // blocks with no predecessors, we can just test for that.
109 // However, we must be careful not to do this to our incoming
110 // block, because *statement* emission does sometimes create
111 // reachable blocks which will have no predecessors until later in
112 // the function. This occurs with, e.g., labels that are not
113 // reachable by fallthrough.
114 if (incoming != outgoing && outgoing->use_empty()) {
115 outgoing->eraseFromParent();
116 Builder.ClearInsertionPoint();
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 }
118 break;
John McCallcd5b22e2011-01-12 03:41:02 +0000119 }
John McCall2a416372010-12-05 02:00:02 +0000120
Mike Stump1eb44332009-09-09 15:08:12 +0000121 case Stmt::IndirectGotoStmtClass:
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000122 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000123
124 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
125 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
126 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
127 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
Mike Stump1eb44332009-09-09 15:08:12 +0000128
Reid Spencer5f016e22007-07-11 17:01:13 +0000129 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +0000130
Devang Patel51b09f22007-10-04 23:45:31 +0000131 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000132 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000133
134 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000135 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
Mike Stump1eb44332009-09-09 15:08:12 +0000136 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000137 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +0000138 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
139 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000140 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000141 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000142 break;
143 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000144 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000145 break;
146 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +0000147 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000148 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000149 case Stmt::ObjCForCollectionStmtClass:
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000150 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000151 break;
Anders Carlsson6815e942009-09-27 18:58:34 +0000152
153 case Stmt::CXXTryStmtClass:
154 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
155 break;
Richard Smithad762fc2011-04-14 22:09:26 +0000156 case Stmt::CXXForRangeStmtClass:
157 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
158 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 }
160}
161
Daniel Dunbar09124252008-11-12 08:21:33 +0000162bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
163 switch (S->getStmtClass()) {
164 default: return false;
165 case Stmt::NullStmtClass: break;
166 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
Daniel Dunbard286f052009-07-19 06:58:07 +0000167 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbar09124252008-11-12 08:21:33 +0000168 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
169 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
170 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
171 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
172 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
173 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
174 }
175
176 return true;
177}
178
Chris Lattner33793202007-08-31 22:09:40 +0000179/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
180/// this captures the expression result of the last sub-statement and returns it
181/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000182RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
John McCall558d2ab2010-09-15 10:14:12 +0000183 AggValueSlot AggSlot) {
Chris Lattner7d22bf02009-03-05 08:04:57 +0000184 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
185 "LLVM IR generation of compound statement ('{}')");
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Anders Carlssone896d982009-02-13 08:11:52 +0000187 CGDebugInfo *DI = getDebugInfo();
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000188 if (DI) {
Devang Patelbbd9fa42009-10-06 18:36:08 +0000189 DI->setLocation(S.getLBracLoc());
Devang Patel4d939e62010-07-20 22:20:10 +0000190 DI->EmitRegionStart(Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000191 }
192
Anders Carlssonc71c8452009-02-07 23:50:39 +0000193 // Keep track of the current cleanup stack depth.
John McCallf1549f62010-07-06 01:34:17 +0000194 RunCleanupsScope Scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Chris Lattner33793202007-08-31 22:09:40 +0000196 for (CompoundStmt::const_body_iterator I = S.body_begin(),
197 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000199
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000200 if (DI) {
Devang Patelcd9199e2010-04-13 00:08:43 +0000201 DI->setLocation(S.getRBracLoc());
Devang Patel4d939e62010-07-20 22:20:10 +0000202 DI->EmitRegionEnd(Builder);
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000203 }
204
Anders Carlsson17d28a32008-12-12 05:52:00 +0000205 RValue RV;
Mike Stump1eb44332009-09-09 15:08:12 +0000206 if (!GetLast)
Anders Carlsson17d28a32008-12-12 05:52:00 +0000207 RV = RValue::get(0);
208 else {
Mike Stump1eb44332009-09-09 15:08:12 +0000209 // We have to special case labels here. They are statements, but when put
Anders Carlsson17d28a32008-12-12 05:52:00 +0000210 // at the end of a statement expression, they yield the value of their
211 // subexpression. Handle this by walking through all labels we encounter,
212 // emitting them before we evaluate the subexpr.
213 const Stmt *LastStmt = S.body_back();
214 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000215 EmitLabel(LS->getDecl());
Anders Carlsson17d28a32008-12-12 05:52:00 +0000216 LastStmt = LS->getSubStmt();
217 }
Mike Stump1eb44332009-09-09 15:08:12 +0000218
Anders Carlsson17d28a32008-12-12 05:52:00 +0000219 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000220
John McCall558d2ab2010-09-15 10:14:12 +0000221 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggSlot);
Anders Carlsson17d28a32008-12-12 05:52:00 +0000222 }
223
Anders Carlsson17d28a32008-12-12 05:52:00 +0000224 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000225}
226
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000227void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
228 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
Mike Stump1eb44332009-09-09 15:08:12 +0000229
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000230 // If there is a cleanup stack, then we it isn't worth trying to
231 // simplify this block (we would need to remove it from the scope map
232 // and cleanup entry).
John McCallf1549f62010-07-06 01:34:17 +0000233 if (!EHStack.empty())
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000234 return;
235
236 // Can only simplify direct branches.
237 if (!BI || !BI->isUnconditional())
238 return;
239
240 BB->replaceAllUsesWith(BI->getSuccessor(0));
241 BI->eraseFromParent();
242 BB->eraseFromParent();
243}
244
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000245void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
John McCall548ce5e2010-04-21 11:18:06 +0000246 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
247
Daniel Dunbard57a8712008-11-11 09:41:28 +0000248 // Fall out of the current block (if necessary).
249 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000250
251 if (IsFinished && BB->use_empty()) {
252 delete BB;
253 return;
254 }
255
John McCall839cbaa2010-04-21 10:29:06 +0000256 // Place the block after the current block, if possible, or else at
257 // the end of the function.
John McCall548ce5e2010-04-21 11:18:06 +0000258 if (CurBB && CurBB->getParent())
259 CurFn->getBasicBlockList().insertAfter(CurBB, BB);
John McCall839cbaa2010-04-21 10:29:06 +0000260 else
261 CurFn->getBasicBlockList().push_back(BB);
Reid Spencer5f016e22007-07-11 17:01:13 +0000262 Builder.SetInsertPoint(BB);
263}
264
Daniel Dunbard57a8712008-11-11 09:41:28 +0000265void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
266 // Emit a branch from the current block to the target one if this
267 // was a real block. If this was just a fall-through block after a
268 // terminator, don't emit it.
269 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
270
271 if (!CurBB || CurBB->getTerminator()) {
272 // If there is no insert point or the previous block is already
273 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000274 } else {
275 // Otherwise, create a fall-through branch.
276 Builder.CreateBr(Target);
277 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000278
279 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000280}
281
John McCallf1549f62010-07-06 01:34:17 +0000282CodeGenFunction::JumpDest
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000283CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
284 JumpDest &Dest = LabelMap[D];
John McCallff8e1152010-07-23 21:56:41 +0000285 if (Dest.isValid()) return Dest;
John McCallf1549f62010-07-06 01:34:17 +0000286
287 // Create, but don't insert, the new block.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000288 Dest = JumpDest(createBasicBlock(D->getName()),
John McCallff8e1152010-07-23 21:56:41 +0000289 EHScopeStack::stable_iterator::invalid(),
290 NextCleanupDestIndex++);
John McCallf1549f62010-07-06 01:34:17 +0000291 return Dest;
292}
293
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000294void CodeGenFunction::EmitLabel(const LabelDecl *D) {
295 JumpDest &Dest = LabelMap[D];
John McCallf1549f62010-07-06 01:34:17 +0000296
John McCallff8e1152010-07-23 21:56:41 +0000297 // If we didn't need a forward reference to this label, just go
John McCallf1549f62010-07-06 01:34:17 +0000298 // ahead and create a destination at the current scope.
John McCallff8e1152010-07-23 21:56:41 +0000299 if (!Dest.isValid()) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000300 Dest = getJumpDestInCurrentScope(D->getName());
John McCallf1549f62010-07-06 01:34:17 +0000301
302 // Otherwise, we need to give this label a target depth and remove
303 // it from the branch-fixups list.
304 } else {
John McCallff8e1152010-07-23 21:56:41 +0000305 assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
306 Dest = JumpDest(Dest.getBlock(),
307 EHStack.stable_begin(),
308 Dest.getDestIndex());
John McCallf1549f62010-07-06 01:34:17 +0000309
John McCallff8e1152010-07-23 21:56:41 +0000310 ResolveBranchFixups(Dest.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000311 }
312
John McCallff8e1152010-07-23 21:56:41 +0000313 EmitBlock(Dest.getBlock());
Chris Lattner91d723d2008-07-26 20:23:23 +0000314}
315
316
317void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000318 EmitLabel(S.getDecl());
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 EmitStmt(S.getSubStmt());
320}
321
322void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000323 // If this code is reachable then emit a stop point (if generating
324 // debug info). We have to do this ourselves because we are on the
325 // "simple" statement path.
326 if (HaveInsertPoint())
327 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000328
John McCallf1549f62010-07-06 01:34:17 +0000329 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000330}
331
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000332
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000333void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000334 if (const LabelDecl *Target = S.getConstantTarget()) {
John McCall95c225d2010-10-28 08:53:48 +0000335 EmitBranchThroughCleanup(getJumpDestForLabel(Target));
336 return;
337 }
338
Chris Lattner49c952f2009-11-06 18:10:47 +0000339 // Ensure that we have an i8* for our PHI node.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000340 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
John McCalld16c2cf2011-02-08 08:22:06 +0000341 Int8PtrTy, "addr");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000342 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
343
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000344
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000345 // Get the basic block for the indirect goto.
346 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
347
348 // The first instruction in the block has to be the PHI for the switch dest,
349 // add an entry for this branch.
350 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
351
352 EmitBranch(IndGotoBB);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000353}
354
Chris Lattner62b72f62008-11-11 07:24:28 +0000355void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 // C99 6.8.4.1: The first substatement is executed if the expression compares
357 // unequal to 0. The condition must be a scalar type.
John McCallf1549f62010-07-06 01:34:17 +0000358 RunCleanupsScope ConditionScope(*this);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000359
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000360 if (S.getConditionVariable())
John McCallb6bbcc92010-10-15 04:57:14 +0000361 EmitAutoVarDecl(*S.getConditionVariable());
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Chris Lattner9bc47e22008-11-12 07:46:33 +0000363 // If the condition constant folds and can be elided, try to avoid emitting
364 // the condition and the dead arm of the if/else.
Chris Lattnerc2c90012011-02-27 23:02:32 +0000365 bool CondConstant;
366 if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000367 // Figure out which block (then or else) is executed.
Chris Lattnerc2c90012011-02-27 23:02:32 +0000368 const Stmt *Executed = S.getThen();
369 const Stmt *Skipped = S.getElse();
370 if (!CondConstant) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000371 std::swap(Executed, Skipped);
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Chris Lattner62b72f62008-11-11 07:24:28 +0000373 // If the skipped block has no labels in it, just emit the executed block.
374 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000375 if (!ContainsLabel(Skipped)) {
Douglas Gregor01234bb2009-11-24 16:43:22 +0000376 if (Executed) {
John McCallf1549f62010-07-06 01:34:17 +0000377 RunCleanupsScope ExecutedScope(*this);
Chris Lattner62b72f62008-11-11 07:24:28 +0000378 EmitStmt(Executed);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000379 }
Chris Lattner62b72f62008-11-11 07:24:28 +0000380 return;
381 }
382 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000383
384 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
385 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000386 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
387 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
388 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000390 ElseBlock = createBasicBlock("if.else");
391 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Reid Spencer5f016e22007-07-11 17:01:13 +0000393 // Emit the 'then' code.
Douglas Gregor01234bb2009-11-24 16:43:22 +0000394 EmitBlock(ThenBlock);
395 {
John McCallf1549f62010-07-06 01:34:17 +0000396 RunCleanupsScope ThenScope(*this);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000397 EmitStmt(S.getThen());
398 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000399 EmitBranch(ContBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 // Emit the 'else' code if present.
402 if (const Stmt *Else = S.getElse()) {
Devang Patelacd72362011-03-30 00:08:31 +0000403 // There is no need to emit line number for unconditional branch.
404 if (getDebugInfo())
405 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 EmitBlock(ElseBlock);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000407 {
John McCallf1549f62010-07-06 01:34:17 +0000408 RunCleanupsScope ElseScope(*this);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000409 EmitStmt(Else);
410 }
Devang Patelacd72362011-03-30 00:08:31 +0000411 // There is no need to emit line number for unconditional branch.
412 if (getDebugInfo())
413 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000414 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 }
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000418 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000419}
420
421void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000422 // Emit the header for the loop, which will also become
423 // the continue target.
424 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
John McCallff8e1152010-07-23 21:56:41 +0000425 EmitBlock(LoopHeader.getBlock());
Mike Stump72cac2c2009-02-07 18:08:12 +0000426
John McCallf1549f62010-07-06 01:34:17 +0000427 // Create an exit block for when the condition fails, which will
428 // also become the break target.
429 JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
Mike Stump72cac2c2009-02-07 18:08:12 +0000430
431 // Store the blocks to use for break and continue.
John McCallf1549f62010-07-06 01:34:17 +0000432 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Douglas Gregor5656e142009-11-24 21:15:44 +0000434 // C++ [stmt.while]p2:
435 // When the condition of a while statement is a declaration, the
436 // scope of the variable that is declared extends from its point
437 // of declaration (3.3.2) to the end of the while statement.
438 // [...]
439 // The object created in a condition is destroyed and created
440 // with each iteration of the loop.
John McCallf1549f62010-07-06 01:34:17 +0000441 RunCleanupsScope ConditionScope(*this);
Douglas Gregor5656e142009-11-24 21:15:44 +0000442
John McCallf1549f62010-07-06 01:34:17 +0000443 if (S.getConditionVariable())
John McCallb6bbcc92010-10-15 04:57:14 +0000444 EmitAutoVarDecl(*S.getConditionVariable());
Douglas Gregor5656e142009-11-24 21:15:44 +0000445
Mike Stump16b16202009-02-07 17:18:33 +0000446 // Evaluate the conditional in the while header. C99 6.8.5.1: The
447 // evaluation of the controlling expression takes place before each
448 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000449 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Douglas Gregor5656e142009-11-24 21:15:44 +0000450
Devang Patel2c30d8f2007-10-09 20:51:27 +0000451 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000452 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000453 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000454 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel2c30d8f2007-10-09 20:51:27 +0000455 if (C->isOne())
456 EmitBoolCondBranch = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Reid Spencer5f016e22007-07-11 17:01:13 +0000458 // As long as the condition is true, go to the loop body.
John McCallf1549f62010-07-06 01:34:17 +0000459 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
460 if (EmitBoolCondBranch) {
John McCallff8e1152010-07-23 21:56:41 +0000461 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
John McCallf1549f62010-07-06 01:34:17 +0000462 if (ConditionScope.requiresCleanups())
463 ExitBlock = createBasicBlock("while.exit");
464
465 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
466
John McCallff8e1152010-07-23 21:56:41 +0000467 if (ExitBlock != LoopExit.getBlock()) {
John McCallf1549f62010-07-06 01:34:17 +0000468 EmitBlock(ExitBlock);
469 EmitBranchThroughCleanup(LoopExit);
470 }
471 }
Douglas Gregor5656e142009-11-24 21:15:44 +0000472
John McCallf1549f62010-07-06 01:34:17 +0000473 // Emit the loop body. We have to emit this in a cleanup scope
474 // because it might be a singleton DeclStmt.
Douglas Gregor5656e142009-11-24 21:15:44 +0000475 {
John McCallf1549f62010-07-06 01:34:17 +0000476 RunCleanupsScope BodyScope(*this);
Douglas Gregor5656e142009-11-24 21:15:44 +0000477 EmitBlock(LoopBody);
478 EmitStmt(S.getBody());
479 }
Chris Lattnerda138702007-07-16 21:28:45 +0000480
Mike Stump1eb44332009-09-09 15:08:12 +0000481 BreakContinueStack.pop_back();
482
John McCallf1549f62010-07-06 01:34:17 +0000483 // Immediately force cleanup.
484 ConditionScope.ForceCleanup();
Douglas Gregor5656e142009-11-24 21:15:44 +0000485
John McCallf1549f62010-07-06 01:34:17 +0000486 // Branch to the loop header again.
John McCallff8e1152010-07-23 21:56:41 +0000487 EmitBranch(LoopHeader.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Reid Spencer5f016e22007-07-11 17:01:13 +0000489 // Emit the exit block.
John McCallff8e1152010-07-23 21:56:41 +0000490 EmitBlock(LoopExit.getBlock(), true);
Douglas Gregor5656e142009-11-24 21:15:44 +0000491
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000492 // The LoopHeader typically is just a branch if we skipped emitting
493 // a branch, try to erase it.
John McCallf1549f62010-07-06 01:34:17 +0000494 if (!EmitBoolCondBranch)
John McCallff8e1152010-07-23 21:56:41 +0000495 SimplifyForwardingBlocks(LoopHeader.getBlock());
Reid Spencer5f016e22007-07-11 17:01:13 +0000496}
497
498void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000499 JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
500 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Chris Lattnerda138702007-07-16 21:28:45 +0000502 // Store the blocks to use for break and continue.
John McCallf1549f62010-07-06 01:34:17 +0000503 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
Mike Stump1eb44332009-09-09 15:08:12 +0000504
John McCallf1549f62010-07-06 01:34:17 +0000505 // Emit the body of the loop.
506 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
507 EmitBlock(LoopBody);
508 {
509 RunCleanupsScope BodyScope(*this);
510 EmitStmt(S.getBody());
511 }
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Anders Carlssone4b6d342009-02-10 05:52:02 +0000513 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000514
John McCallff8e1152010-07-23 21:56:41 +0000515 EmitBlock(LoopCond.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Reid Spencer5f016e22007-07-11 17:01:13 +0000517 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
518 // after each execution of the loop body."
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 // Evaluate the conditional in the while header.
521 // C99 6.8.5p2/p4: The first substatement is executed if the expression
522 // compares unequal to 0. The condition must be a scalar type.
523 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000524
525 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
526 // to correctly handle break/continue though.
527 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000528 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel05f6e6b2007-10-09 20:33:39 +0000529 if (C->isZero())
530 EmitBoolCondBranch = false;
531
Reid Spencer5f016e22007-07-11 17:01:13 +0000532 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000533 if (EmitBoolCondBranch)
John McCallff8e1152010-07-23 21:56:41 +0000534 Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Reid Spencer5f016e22007-07-11 17:01:13 +0000536 // Emit the exit block.
John McCallff8e1152010-07-23 21:56:41 +0000537 EmitBlock(LoopExit.getBlock());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000538
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000539 // The DoCond block typically is just a branch if we skipped
540 // emitting a branch, try to erase it.
541 if (!EmitBoolCondBranch)
John McCallff8e1152010-07-23 21:56:41 +0000542 SimplifyForwardingBlocks(LoopCond.getBlock());
Reid Spencer5f016e22007-07-11 17:01:13 +0000543}
544
545void CodeGenFunction::EmitForStmt(const ForStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000546 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
547
548 RunCleanupsScope ForScope(*this);
Chris Lattnerda138702007-07-16 21:28:45 +0000549
Devang Patel0554e0e2010-08-25 00:28:56 +0000550 CGDebugInfo *DI = getDebugInfo();
551 if (DI) {
552 DI->setLocation(S.getSourceRange().getBegin());
553 DI->EmitRegionStart(Builder);
554 }
555
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 // Evaluate the first part before the loop.
557 if (S.getInit())
558 EmitStmt(S.getInit());
559
560 // Start the loop with a block that tests the condition.
John McCallf1549f62010-07-06 01:34:17 +0000561 // If there's an increment, the continue scope will be overwritten
562 // later.
563 JumpDest Continue = getJumpDestInCurrentScope("for.cond");
John McCallff8e1152010-07-23 21:56:41 +0000564 llvm::BasicBlock *CondBlock = Continue.getBlock();
Reid Spencer5f016e22007-07-11 17:01:13 +0000565 EmitBlock(CondBlock);
566
Douglas Gregord9752062009-11-25 01:51:31 +0000567 // Create a cleanup scope for the condition variable cleanups.
John McCallf1549f62010-07-06 01:34:17 +0000568 RunCleanupsScope ConditionScope(*this);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000569
Douglas Gregord9752062009-11-25 01:51:31 +0000570 llvm::Value *BoolCondVal = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000571 if (S.getCond()) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000572 // If the for statement has a condition scope, emit the local variable
573 // declaration.
John McCallff8e1152010-07-23 21:56:41 +0000574 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
Douglas Gregord9752062009-11-25 01:51:31 +0000575 if (S.getConditionVariable()) {
John McCallb6bbcc92010-10-15 04:57:14 +0000576 EmitAutoVarDecl(*S.getConditionVariable());
Douglas Gregord9752062009-11-25 01:51:31 +0000577 }
John McCallf1549f62010-07-06 01:34:17 +0000578
579 // If there are any cleanups between here and the loop-exit scope,
580 // create a block to stage a loop exit along.
581 if (ForScope.requiresCleanups())
582 ExitBlock = createBasicBlock("for.cond.cleanup");
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000583
Reid Spencer5f016e22007-07-11 17:01:13 +0000584 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000585 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Chris Lattner31a09842008-11-12 08:04:58 +0000587 // C99 6.8.5p2/p4: The first substatement is executed if the expression
588 // compares unequal to 0. The condition must be a scalar type.
Douglas Gregord9752062009-11-25 01:51:31 +0000589 BoolCondVal = EvaluateExprAsBool(S.getCond());
John McCallf1549f62010-07-06 01:34:17 +0000590 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
591
John McCallff8e1152010-07-23 21:56:41 +0000592 if (ExitBlock != LoopExit.getBlock()) {
John McCallf1549f62010-07-06 01:34:17 +0000593 EmitBlock(ExitBlock);
594 EmitBranchThroughCleanup(LoopExit);
595 }
Mike Stump1eb44332009-09-09 15:08:12 +0000596
597 EmitBlock(ForBody);
Reid Spencer5f016e22007-07-11 17:01:13 +0000598 } else {
599 // Treat it as a non-zero constant. Don't even create a new block for the
600 // body, just fall into it.
601 }
602
Mike Stump1eb44332009-09-09 15:08:12 +0000603 // If the for loop doesn't have an increment we can just use the
John McCallf1549f62010-07-06 01:34:17 +0000604 // condition as the continue block. Otherwise we'll need to create
605 // a block for it (in the current scope, i.e. in the scope of the
606 // condition), and that we will become our continue block.
Chris Lattnerda138702007-07-16 21:28:45 +0000607 if (S.getInc())
John McCallf1549f62010-07-06 01:34:17 +0000608 Continue = getJumpDestInCurrentScope("for.inc");
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Chris Lattnerda138702007-07-16 21:28:45 +0000610 // Store the blocks to use for break and continue.
John McCallf1549f62010-07-06 01:34:17 +0000611 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
Mike Stump3e9da662009-02-07 23:02:10 +0000612
Douglas Gregord9752062009-11-25 01:51:31 +0000613 {
614 // Create a separate cleanup scope for the body, in case it is not
615 // a compound statement.
John McCallf1549f62010-07-06 01:34:17 +0000616 RunCleanupsScope BodyScope(*this);
Douglas Gregord9752062009-11-25 01:51:31 +0000617 EmitStmt(S.getBody());
618 }
Chris Lattnerda138702007-07-16 21:28:45 +0000619
Reid Spencer5f016e22007-07-11 17:01:13 +0000620 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000621 if (S.getInc()) {
John McCallff8e1152010-07-23 21:56:41 +0000622 EmitBlock(Continue.getBlock());
Chris Lattner883f6a72007-08-11 00:04:45 +0000623 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000624 }
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Douglas Gregor45d3fe12010-05-21 18:36:48 +0000626 BreakContinueStack.pop_back();
Douglas Gregord9752062009-11-25 01:51:31 +0000627
John McCallf1549f62010-07-06 01:34:17 +0000628 ConditionScope.ForceCleanup();
629 EmitBranch(CondBlock);
630
631 ForScope.ForceCleanup();
632
Devang Patelbbd9fa42009-10-06 18:36:08 +0000633 if (DI) {
634 DI->setLocation(S.getSourceRange().getEnd());
Devang Patel4d939e62010-07-20 22:20:10 +0000635 DI->EmitRegionEnd(Builder);
Devang Patelbbd9fa42009-10-06 18:36:08 +0000636 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000637
Chris Lattnerda138702007-07-16 21:28:45 +0000638 // Emit the fall-through block.
John McCallff8e1152010-07-23 21:56:41 +0000639 EmitBlock(LoopExit.getBlock(), true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000640}
641
Richard Smithad762fc2011-04-14 22:09:26 +0000642void CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S) {
643 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
644
645 RunCleanupsScope ForScope(*this);
646
647 CGDebugInfo *DI = getDebugInfo();
648 if (DI) {
649 DI->setLocation(S.getSourceRange().getBegin());
650 DI->EmitRegionStart(Builder);
651 }
652
653 // Evaluate the first pieces before the loop.
654 EmitStmt(S.getRangeStmt());
655 EmitStmt(S.getBeginEndStmt());
656
657 // Start the loop with a block that tests the condition.
658 // If there's an increment, the continue scope will be overwritten
659 // later.
660 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
661 EmitBlock(CondBlock);
662
663 // If there are any cleanups between here and the loop-exit scope,
664 // create a block to stage a loop exit along.
665 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
666 if (ForScope.requiresCleanups())
667 ExitBlock = createBasicBlock("for.cond.cleanup");
668
669 // The loop body, consisting of the specified body and the loop variable.
670 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
671
672 // The body is executed if the expression, contextually converted
673 // to bool, is true.
674 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
675 Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
676
677 if (ExitBlock != LoopExit.getBlock()) {
678 EmitBlock(ExitBlock);
679 EmitBranchThroughCleanup(LoopExit);
680 }
681
682 EmitBlock(ForBody);
683
684 // Create a block for the increment. In case of a 'continue', we jump there.
685 JumpDest Continue = getJumpDestInCurrentScope("for.inc");
686
687 // Store the blocks to use for break and continue.
688 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
689
690 {
691 // Create a separate cleanup scope for the loop variable and body.
692 RunCleanupsScope BodyScope(*this);
693 EmitStmt(S.getLoopVarStmt());
694 EmitStmt(S.getBody());
695 }
696
697 // If there is an increment, emit it next.
698 EmitBlock(Continue.getBlock());
699 EmitStmt(S.getInc());
700
701 BreakContinueStack.pop_back();
702
703 EmitBranch(CondBlock);
704
705 ForScope.ForceCleanup();
706
707 if (DI) {
708 DI->setLocation(S.getSourceRange().getEnd());
709 DI->EmitRegionEnd(Builder);
710 }
711
712 // Emit the fall-through block.
713 EmitBlock(LoopExit.getBlock(), true);
714}
715
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000716void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
717 if (RV.isScalar()) {
718 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
719 } else if (RV.isAggregate()) {
720 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
721 } else {
722 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
723 }
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000724 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000725}
726
Reid Spencer5f016e22007-07-11 17:01:13 +0000727/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
728/// if the function returns void, or may be missing one if the function returns
729/// non-void. Fun stuff :).
730void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 // Emit the result value, even if unused, to evalute the side effects.
732 const Expr *RV = S.getRetValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000734 // FIXME: Clean this up by using an LValue for ReturnTemp,
735 // EmitStoreThroughLValue, and EmitAnyExpr.
Douglas Gregord86c4772010-05-15 06:46:45 +0000736 if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable() &&
737 !Target.useGlobalsForAutomaticVariables()) {
738 // Apply the named return value optimization for this return statement,
739 // which means doing nothing: the appropriate result has already been
740 // constructed into the NRVO variable.
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000741
742 // If there is an NRVO flag for this variable, set it to 1 into indicate
743 // that the cleanup code should not destroy the variable.
John McCalld16c2cf2011-02-08 08:22:06 +0000744 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
745 Builder.CreateStore(Builder.getTrue(), NRVOFlag);
Douglas Gregord86c4772010-05-15 06:46:45 +0000746 } else if (!ReturnValue) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000747 // Make sure not to return anything, but evaluate the expression
748 // for side effects.
749 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000750 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000752 // Do nothing (return value is left uninitialized)
Eli Friedmand54b6ac2009-05-27 04:56:12 +0000753 } else if (FnRetTy->isReferenceType()) {
754 // If this function returns a reference, take the address of the expression
755 // rather than the value.
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000756 RValue Result = EmitReferenceBindingToExpr(RV, /*InitializedDecl=*/0);
Douglas Gregor33fd1fc2010-03-24 23:14:04 +0000757 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
Chris Lattner4b0029d2007-08-26 07:14:44 +0000758 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000759 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000760 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000761 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 } else {
John McCall558d2ab2010-09-15 10:14:12 +0000763 EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, false, true));
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 }
Eli Friedman144ac612008-05-22 01:22:33 +0000765
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000766 EmitBranchThroughCleanup(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000767}
768
769void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Daniel Dunbar25b6ebf2009-07-19 07:03:11 +0000770 // As long as debug info is modeled with instructions, we have to ensure we
771 // have a place to insert here and write the stop point here.
772 if (getDebugInfo()) {
773 EnsureInsertPoint();
774 EmitStopPoint(&S);
775 }
776
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000777 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
778 I != E; ++I)
779 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000780}
Chris Lattnerda138702007-07-16 21:28:45 +0000781
Daniel Dunbar09124252008-11-12 08:21:33 +0000782void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000783 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
784
Daniel Dunbar09124252008-11-12 08:21:33 +0000785 // If this code is reachable then emit a stop point (if generating
786 // debug info). We have to do this ourselves because we are on the
787 // "simple" statement path.
788 if (HaveInsertPoint())
789 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000790
John McCallf1549f62010-07-06 01:34:17 +0000791 JumpDest Block = BreakContinueStack.back().BreakBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000792 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000793}
794
Daniel Dunbar09124252008-11-12 08:21:33 +0000795void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000796 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
797
Daniel Dunbar09124252008-11-12 08:21:33 +0000798 // If this code is reachable then emit a stop point (if generating
799 // debug info). We have to do this ourselves because we are on the
800 // "simple" statement path.
801 if (HaveInsertPoint())
802 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000803
John McCallf1549f62010-07-06 01:34:17 +0000804 JumpDest Block = BreakContinueStack.back().ContinueBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000805 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000806}
Devang Patel51b09f22007-10-04 23:45:31 +0000807
Devang Patelc049e4f2007-10-08 20:57:48 +0000808/// EmitCaseStmtRange - If case statement range is not too big then
809/// add multiple cases to switch instruction, one for each value within
810/// the range. If range is too big then emit "if" condition check.
811void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000812 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000813
Anders Carlsson51fe9962008-11-22 21:04:56 +0000814 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
815 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000816
Daniel Dunbar16f23572008-07-25 01:11:38 +0000817 // Emit the code for this case. We do this first to make sure it is
818 // properly chained from our predecessor before generating the
819 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000820 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000821 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
822 EmitStmt(S.getSubStmt());
823
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000824 // If range is empty, do nothing.
825 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
826 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000827
828 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000829 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000830 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
831 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000832 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
John McCalld16c2cf2011-02-08 08:22:06 +0000833 SwitchInsn->addCase(llvm::ConstantInt::get(getLLVMContext(), LHS),
834 CaseDest);
Devang Patel2d79d0f2007-10-05 20:54:07 +0000835 LHS++;
836 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000837 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000838 }
839
Daniel Dunbar16f23572008-07-25 01:11:38 +0000840 // The range is too big. Emit "if" condition into a new block,
841 // making sure to save and restore the current insertion point.
842 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000843
Daniel Dunbar16f23572008-07-25 01:11:38 +0000844 // Push this test onto the chain of range checks (which terminates
845 // in the default basic block). The switch's default will be changed
846 // to the top of this chain after switch emission is complete.
847 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000848 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000849
Daniel Dunbar16f23572008-07-25 01:11:38 +0000850 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
851 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000852
853 // Emit range check.
Mike Stump1eb44332009-09-09 15:08:12 +0000854 llvm::Value *Diff =
855 Builder.CreateSub(SwitchInsn->getCondition(),
John McCalld16c2cf2011-02-08 08:22:06 +0000856 llvm::ConstantInt::get(getLLVMContext(), LHS), "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000857 llvm::Value *Cond =
John McCalld16c2cf2011-02-08 08:22:06 +0000858 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(getLLVMContext(), Range),
859 "inbounds");
Devang Patelc049e4f2007-10-08 20:57:48 +0000860 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
861
Daniel Dunbar16f23572008-07-25 01:11:38 +0000862 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000863 if (RestoreBB)
864 Builder.SetInsertPoint(RestoreBB);
865 else
866 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000867}
868
869void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
Chris Lattnerb11f9192011-04-17 00:54:30 +0000870 // Handle case ranges.
Devang Patelc049e4f2007-10-08 20:57:48 +0000871 if (S.getRHS()) {
872 EmitCaseStmtRange(S);
873 return;
874 }
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Chris Lattnerb11f9192011-04-17 00:54:30 +0000876 // If the body of the case is just a 'break', try to not emit an empty block.
877 if (isa<BreakStmt>(S.getSubStmt())) {
878 JumpDest Block = BreakContinueStack.back().BreakBlock;
879
880 // Only do this optimization if there are no cleanups that need emitting.
881 if (isObviouslyBranchWithoutCleanups(Block)) {
882 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
883 SwitchInsn->addCase(llvm::ConstantInt::get(getLLVMContext(), CaseVal),
884 Block.getBlock());
885 return;
886 }
887 }
888
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000889 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000890 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000891 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
John McCalld16c2cf2011-02-08 08:22:06 +0000892 SwitchInsn->addCase(llvm::ConstantInt::get(getLLVMContext(), CaseVal),
893 CaseDest);
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Chris Lattner5512f282009-03-04 04:46:18 +0000895 // Recursively emitting the statement is acceptable, but is not wonderful for
896 // code where we have many case statements nested together, i.e.:
897 // case 1:
898 // case 2:
899 // case 3: etc.
900 // Handling this recursively will create a new block for each case statement
901 // that falls through to the next case which is IR intensive. It also causes
902 // deep recursion which can run into stack depth limitations. Handle
903 // sequential non-range case statements specially.
904 const CaseStmt *CurCase = &S;
905 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
906
907 // Otherwise, iteratively add consequtive cases to this switch stmt.
908 while (NextCase && NextCase->getRHS() == 0) {
909 CurCase = NextCase;
910 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
John McCalld16c2cf2011-02-08 08:22:06 +0000911 SwitchInsn->addCase(llvm::ConstantInt::get(getLLVMContext(), CaseVal),
912 CaseDest);
Chris Lattner5512f282009-03-04 04:46:18 +0000913
914 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
915 }
Mike Stump1eb44332009-09-09 15:08:12 +0000916
Chris Lattner5512f282009-03-04 04:46:18 +0000917 // Normal default recursion for non-cases.
918 EmitStmt(CurCase->getSubStmt());
Devang Patel51b09f22007-10-04 23:45:31 +0000919}
920
921void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000922 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Mike Stump1eb44332009-09-09 15:08:12 +0000923 assert(DefaultBlock->empty() &&
Daniel Dunbar55e87422008-11-11 02:29:29 +0000924 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000925 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000926 EmitStmt(S.getSubStmt());
927}
928
Chris Lattnerfda0f1f2011-02-28 00:22:07 +0000929/// CollectStatementsForCase - Given the body of a 'switch' statement and a
930/// constant value that is being switched on, see if we can dead code eliminate
931/// the body of the switch to a simple series of statements to emit. Basically,
932/// on a switch (5) we want to find these statements:
933/// case 5:
934/// printf(...); <--
935/// ++i; <--
936/// break;
937///
938/// and add them to the ResultStmts vector. If it is unsafe to do this
939/// transformation (for example, one of the elided statements contains a label
940/// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
941/// should include statements after it (e.g. the printf() line is a substmt of
942/// the case) then return CSFC_FallThrough. If we handled it and found a break
943/// statement, then return CSFC_Success.
944///
945/// If Case is non-null, then we are looking for the specified case, checking
946/// that nothing we jump over contains labels. If Case is null, then we found
947/// the case and are looking for the break.
948///
949/// If the recursive walk actually finds our Case, then we set FoundCase to
950/// true.
951///
952enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
953static CSFC_Result CollectStatementsForCase(const Stmt *S,
954 const SwitchCase *Case,
955 bool &FoundCase,
956 llvm::SmallVectorImpl<const Stmt*> &ResultStmts) {
Chris Lattner38589382011-02-28 01:02:29 +0000957 // If this is a null statement, just succeed.
958 if (S == 0)
959 return Case ? CSFC_Success : CSFC_FallThrough;
960
Chris Lattnerfda0f1f2011-02-28 00:22:07 +0000961 // If this is the switchcase (case 4: or default) that we're looking for, then
962 // we're in business. Just add the substatement.
963 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
964 if (S == Case) {
965 FoundCase = true;
966 return CollectStatementsForCase(SC->getSubStmt(), 0, FoundCase,
967 ResultStmts);
968 }
969
970 // Otherwise, this is some other case or default statement, just ignore it.
971 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
972 ResultStmts);
973 }
Chris Lattner38589382011-02-28 01:02:29 +0000974
975 // If we are in the live part of the code and we found our break statement,
976 // return a success!
977 if (Case == 0 && isa<BreakStmt>(S))
978 return CSFC_Success;
Chris Lattnerfda0f1f2011-02-28 00:22:07 +0000979
Chris Lattner38589382011-02-28 01:02:29 +0000980 // If this is a switch statement, then it might contain the SwitchCase, the
981 // break, or neither.
982 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
983 // Handle this as two cases: we might be looking for the SwitchCase (if so
984 // the skipped statements must be skippable) or we might already have it.
985 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
986 if (Case) {
Chris Lattner3f06e272011-02-28 07:22:44 +0000987 // Keep track of whether we see a skipped declaration. The code could be
988 // using the declaration even if it is skipped, so we can't optimize out
989 // the decl if the kept statements might refer to it.
990 bool HadSkippedDecl = false;
991
Chris Lattner38589382011-02-28 01:02:29 +0000992 // If we're looking for the case, just see if we can skip each of the
993 // substatements.
994 for (; Case && I != E; ++I) {
Chris Lattner3f06e272011-02-28 07:22:44 +0000995 HadSkippedDecl |= isa<DeclStmt>(I);
996
Chris Lattner38589382011-02-28 01:02:29 +0000997 switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
998 case CSFC_Failure: return CSFC_Failure;
999 case CSFC_Success:
1000 // A successful result means that either 1) that the statement doesn't
1001 // have the case and is skippable, or 2) does contain the case value
Chris Lattner94671102011-02-28 07:16:14 +00001002 // and also contains the break to exit the switch. In the later case,
1003 // we just verify the rest of the statements are elidable.
1004 if (FoundCase) {
Chris Lattner3f06e272011-02-28 07:22:44 +00001005 // If we found the case and skipped declarations, we can't do the
1006 // optimization.
1007 if (HadSkippedDecl)
1008 return CSFC_Failure;
1009
Chris Lattner94671102011-02-28 07:16:14 +00001010 for (++I; I != E; ++I)
1011 if (CodeGenFunction::ContainsLabel(*I, true))
1012 return CSFC_Failure;
1013 return CSFC_Success;
1014 }
Chris Lattner38589382011-02-28 01:02:29 +00001015 break;
1016 case CSFC_FallThrough:
1017 // If we have a fallthrough condition, then we must have found the
1018 // case started to include statements. Consider the rest of the
1019 // statements in the compound statement as candidates for inclusion.
1020 assert(FoundCase && "Didn't find case but returned fallthrough?");
1021 // We recursively found Case, so we're not looking for it anymore.
1022 Case = 0;
Chris Lattner3f06e272011-02-28 07:22:44 +00001023
1024 // If we found the case and skipped declarations, we can't do the
1025 // optimization.
1026 if (HadSkippedDecl)
1027 return CSFC_Failure;
Chris Lattner38589382011-02-28 01:02:29 +00001028 break;
1029 }
1030 }
1031 }
1032
1033 // If we have statements in our range, then we know that the statements are
1034 // live and need to be added to the set of statements we're tracking.
1035 for (; I != E; ++I) {
1036 switch (CollectStatementsForCase(*I, 0, FoundCase, ResultStmts)) {
1037 case CSFC_Failure: return CSFC_Failure;
1038 case CSFC_FallThrough:
1039 // A fallthrough result means that the statement was simple and just
1040 // included in ResultStmt, keep adding them afterwards.
1041 break;
1042 case CSFC_Success:
1043 // A successful result means that we found the break statement and
1044 // stopped statement inclusion. We just ensure that any leftover stmts
1045 // are skippable and return success ourselves.
1046 for (++I; I != E; ++I)
1047 if (CodeGenFunction::ContainsLabel(*I, true))
1048 return CSFC_Failure;
1049 return CSFC_Success;
1050 }
1051 }
1052
1053 return Case ? CSFC_Success : CSFC_FallThrough;
1054 }
1055
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001056 // Okay, this is some other statement that we don't handle explicitly, like a
1057 // for statement or increment etc. If we are skipping over this statement,
1058 // just verify it doesn't have labels, which would make it invalid to elide.
1059 if (Case) {
Chris Lattner3f06e272011-02-28 07:22:44 +00001060 if (CodeGenFunction::ContainsLabel(S, true))
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001061 return CSFC_Failure;
1062 return CSFC_Success;
1063 }
1064
1065 // Otherwise, we want to include this statement. Everything is cool with that
1066 // so long as it doesn't contain a break out of the switch we're in.
1067 if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1068
1069 // Otherwise, everything is great. Include the statement and tell the caller
1070 // that we fall through and include the next statement as well.
1071 ResultStmts.push_back(S);
1072 return CSFC_FallThrough;
1073}
1074
1075/// FindCaseStatementsForValue - Find the case statement being jumped to and
1076/// then invoke CollectStatementsForCase to find the list of statements to emit
1077/// for a switch on constant. See the comment above CollectStatementsForCase
1078/// for more details.
1079static bool FindCaseStatementsForValue(const SwitchStmt &S,
1080 const llvm::APInt &ConstantCondValue,
1081 llvm::SmallVectorImpl<const Stmt*> &ResultStmts,
1082 ASTContext &C) {
1083 // First step, find the switch case that is being branched to. We can do this
1084 // efficiently by scanning the SwitchCase list.
1085 const SwitchCase *Case = S.getSwitchCaseList();
1086 const DefaultStmt *DefaultCase = 0;
1087
1088 for (; Case; Case = Case->getNextSwitchCase()) {
1089 // It's either a default or case. Just remember the default statement in
1090 // case we're not jumping to any numbered cases.
1091 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1092 DefaultCase = DS;
1093 continue;
1094 }
1095
1096 // Check to see if this case is the one we're looking for.
1097 const CaseStmt *CS = cast<CaseStmt>(Case);
1098 // Don't handle case ranges yet.
1099 if (CS->getRHS()) return false;
1100
1101 // If we found our case, remember it as 'case'.
1102 if (CS->getLHS()->EvaluateAsInt(C) == ConstantCondValue)
1103 break;
1104 }
1105
1106 // If we didn't find a matching case, we use a default if it exists, or we
1107 // elide the whole switch body!
1108 if (Case == 0) {
1109 // It is safe to elide the body of the switch if it doesn't contain labels
1110 // etc. If it is safe, return successfully with an empty ResultStmts list.
1111 if (DefaultCase == 0)
1112 return !CodeGenFunction::ContainsLabel(&S);
1113 Case = DefaultCase;
1114 }
1115
1116 // Ok, we know which case is being jumped to, try to collect all the
1117 // statements that follow it. This can fail for a variety of reasons. Also,
1118 // check to see that the recursive walk actually found our case statement.
1119 // Insane cases like this can fail to find it in the recursive walk since we
1120 // don't handle every stmt kind:
1121 // switch (4) {
1122 // while (1) {
1123 // case 4: ...
1124 bool FoundCase = false;
1125 return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1126 ResultStmts) != CSFC_Failure &&
1127 FoundCase;
1128}
1129
Devang Patel51b09f22007-10-04 23:45:31 +00001130void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001131 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1132
1133 RunCleanupsScope ConditionScope(*this);
Douglas Gregord3d53012009-11-24 17:07:59 +00001134
1135 if (S.getConditionVariable())
John McCallb6bbcc92010-10-15 04:57:14 +00001136 EmitAutoVarDecl(*S.getConditionVariable());
Douglas Gregord3d53012009-11-24 17:07:59 +00001137
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001138 // See if we can constant fold the condition of the switch and therefore only
1139 // emit the live case statement (if any) of the switch.
1140 llvm::APInt ConstantCondValue;
1141 if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1142 llvm::SmallVector<const Stmt*, 4> CaseStmts;
1143 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1144 getContext())) {
1145 RunCleanupsScope ExecutedScope(*this);
1146
1147 // Okay, we can dead code eliminate everything except this case. Emit the
1148 // specified series of statements and we're good.
1149 for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1150 EmitStmt(CaseStmts[i]);
1151 return;
1152 }
1153 }
1154
Devang Patel51b09f22007-10-04 23:45:31 +00001155 llvm::Value *CondV = EmitScalarExpr(S.getCond());
1156
1157 // Handle nested switch statements.
1158 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +00001159 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +00001160
Daniel Dunbar16f23572008-07-25 01:11:38 +00001161 // Create basic block to hold stuff that comes after switch
1162 // statement. We also need to create a default block now so that
1163 // explicit case ranges tests can have a place to jump to on
1164 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001165 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +00001166 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1167 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +00001168
Daniel Dunbar09124252008-11-12 08:21:33 +00001169 // Clear the insertion point to indicate we are in unreachable code.
1170 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +00001171
Devang Patele9b8c0a2007-10-30 20:59:40 +00001172 // All break statements jump to NextBlock. If BreakContinueStack is non empty
1173 // then reuse last ContinueBlock.
John McCallf1549f62010-07-06 01:34:17 +00001174 JumpDest OuterContinue;
Anders Carlssone4b6d342009-02-10 05:52:02 +00001175 if (!BreakContinueStack.empty())
John McCallf1549f62010-07-06 01:34:17 +00001176 OuterContinue = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +00001177
John McCallf1549f62010-07-06 01:34:17 +00001178 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
Devang Patel51b09f22007-10-04 23:45:31 +00001179
1180 // Emit switch body.
1181 EmitStmt(S.getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Anders Carlssone4b6d342009-02-10 05:52:02 +00001183 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +00001184
Daniel Dunbar16f23572008-07-25 01:11:38 +00001185 // Update the default block in case explicit case range tests have
1186 // been chained on top.
1187 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Mike Stump1eb44332009-09-09 15:08:12 +00001188
John McCallf1549f62010-07-06 01:34:17 +00001189 // If a default was never emitted:
Daniel Dunbar16f23572008-07-25 01:11:38 +00001190 if (!DefaultBlock->getParent()) {
John McCallf1549f62010-07-06 01:34:17 +00001191 // If we have cleanups, emit the default block so that there's a
1192 // place to jump through the cleanups from.
1193 if (ConditionScope.requiresCleanups()) {
1194 EmitBlock(DefaultBlock);
1195
1196 // Otherwise, just forward the default block to the switch end.
1197 } else {
John McCallff8e1152010-07-23 21:56:41 +00001198 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
John McCallf1549f62010-07-06 01:34:17 +00001199 delete DefaultBlock;
1200 }
Daniel Dunbar16f23572008-07-25 01:11:38 +00001201 }
Devang Patel51b09f22007-10-04 23:45:31 +00001202
John McCallff8e1152010-07-23 21:56:41 +00001203 ConditionScope.ForceCleanup();
1204
Daniel Dunbar16f23572008-07-25 01:11:38 +00001205 // Emit continuation.
John McCallff8e1152010-07-23 21:56:41 +00001206 EmitBlock(SwitchExit.getBlock(), true);
Daniel Dunbar16f23572008-07-25 01:11:38 +00001207
Devang Patel51b09f22007-10-04 23:45:31 +00001208 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +00001209 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +00001210}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001211
Chris Lattner2819fa82009-04-26 17:57:12 +00001212static std::string
Daniel Dunbar444be732009-11-13 05:51:54 +00001213SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
Chris Lattner2819fa82009-04-26 17:57:12 +00001214 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001215 std::string Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001217 while (*Constraint) {
1218 switch (*Constraint) {
1219 default:
John Thompson2f474ea2010-09-18 01:15:13 +00001220 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001221 break;
1222 // Ignore these
1223 case '*':
1224 case '?':
1225 case '!':
John Thompsonef44e112010-08-10 19:20:14 +00001226 case '=': // Will see this and the following in mult-alt constraints.
1227 case '+':
1228 break;
John Thompson2f474ea2010-09-18 01:15:13 +00001229 case ',':
1230 Result += "|";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001231 break;
1232 case 'g':
1233 Result += "imr";
1234 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001235 case '[': {
Chris Lattner2819fa82009-04-26 17:57:12 +00001236 assert(OutCons &&
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001237 "Must pass output names to constraints with a symbolic name");
1238 unsigned Index;
Mike Stump1eb44332009-09-09 15:08:12 +00001239 bool result = Target.resolveSymbolicName(Constraint,
Chris Lattner2819fa82009-04-26 17:57:12 +00001240 &(*OutCons)[0],
1241 OutCons->size(), Index);
Chris Lattnercbf40f92011-01-05 18:41:53 +00001242 assert(result && "Could not resolve symbolic name"); (void)result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001243 Result += llvm::utostr(Index);
1244 break;
1245 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001246 }
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001248 Constraint++;
1249 }
Mike Stump1eb44332009-09-09 15:08:12 +00001250
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001251 return Result;
1252}
1253
Rafael Espindola03117d12011-01-01 21:12:33 +00001254/// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1255/// as using a particular register add that as a constraint that will be used
1256/// in this asm stmt.
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001257static std::string
Rafael Espindola03117d12011-01-01 21:12:33 +00001258AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1259 const TargetInfo &Target, CodeGenModule &CGM,
1260 const AsmStmt &Stmt) {
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001261 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1262 if (!AsmDeclRef)
1263 return Constraint;
1264 const ValueDecl &Value = *AsmDeclRef->getDecl();
1265 const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1266 if (!Variable)
1267 return Constraint;
1268 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1269 if (!Attr)
1270 return Constraint;
1271 llvm::StringRef Register = Attr->getLabel();
Rafael Espindolabaf86952011-01-01 21:47:03 +00001272 assert(Target.isValidGCCRegisterName(Register));
Rafael Espindola33a53442011-01-02 03:59:13 +00001273 // FIXME: We should check which registers are compatible with "r" or "x".
1274 if (Constraint != "r" && Constraint != "x") {
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001275 CGM.ErrorUnsupported(&Stmt, "__asm__");
1276 return Constraint;
1277 }
1278 return "{" + Register.str() + "}";
1279}
1280
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001281llvm::Value*
1282CodeGenFunction::EmitAsmInputLValue(const AsmStmt &S,
1283 const TargetInfo::ConstraintInfo &Info,
1284 LValue InputValue, QualType InputType,
1285 std::string &ConstraintStr) {
Anders Carlsson63471722009-01-11 19:32:54 +00001286 llvm::Value *Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00001287 if (Info.allowsRegister() || !Info.allowsMemory()) {
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001288 if (!CodeGenFunction::hasAggregateLLVMType(InputType)) {
1289 Arg = EmitLoadOfLValue(InputValue, InputType).getScalarVal();
Anders Carlsson63471722009-01-11 19:32:54 +00001290 } else {
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001291 const llvm::Type *Ty = ConvertType(InputType);
Anders Carlssonebaae2a2009-01-12 02:22:13 +00001292 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
1293 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
John McCalld16c2cf2011-02-08 08:22:06 +00001294 Ty = llvm::IntegerType::get(getLLVMContext(), Size);
Anders Carlssonebaae2a2009-01-12 02:22:13 +00001295 Ty = llvm::PointerType::getUnqual(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001296
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001297 Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1298 Ty));
Anders Carlssonebaae2a2009-01-12 02:22:13 +00001299 } else {
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001300 Arg = InputValue.getAddress();
Anders Carlssonebaae2a2009-01-12 02:22:13 +00001301 ConstraintStr += '*';
1302 }
Anders Carlsson63471722009-01-11 19:32:54 +00001303 }
1304 } else {
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001305 Arg = InputValue.getAddress();
Anders Carlsson63471722009-01-11 19:32:54 +00001306 ConstraintStr += '*';
1307 }
Mike Stump1eb44332009-09-09 15:08:12 +00001308
Anders Carlsson63471722009-01-11 19:32:54 +00001309 return Arg;
1310}
1311
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001312llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
1313 const TargetInfo::ConstraintInfo &Info,
1314 const Expr *InputExpr,
1315 std::string &ConstraintStr) {
1316 if (Info.allowsRegister() || !Info.allowsMemory())
1317 if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType()))
1318 return EmitScalarExpr(InputExpr);
1319
1320 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1321 LValue Dest = EmitLValue(InputExpr);
1322 return EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(), ConstraintStr);
1323}
1324
Chris Lattner47fc7e92010-11-17 05:58:54 +00001325/// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
Chris Lattner5d936532010-11-17 08:25:26 +00001326/// asm call instruction. The !srcloc MDNode contains a list of constant
1327/// integers which are the source locations of the start of each line in the
1328/// asm.
Chris Lattner47fc7e92010-11-17 05:58:54 +00001329static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1330 CodeGenFunction &CGF) {
Chris Lattner5d936532010-11-17 08:25:26 +00001331 llvm::SmallVector<llvm::Value *, 8> Locs;
1332 // Add the location of the first line to the MDNode.
1333 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1334 Str->getLocStart().getRawEncoding()));
1335 llvm::StringRef StrVal = Str->getString();
1336 if (!StrVal.empty()) {
1337 const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1338 const LangOptions &LangOpts = CGF.CGM.getLangOptions();
1339
1340 // Add the location of the start of each subsequent line of the asm to the
1341 // MDNode.
1342 for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
1343 if (StrVal[i] != '\n') continue;
1344 SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
1345 CGF.Target);
1346 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1347 LineLoc.getRawEncoding()));
1348 }
1349 }
1350
1351 return llvm::MDNode::get(CGF.getLLVMContext(), Locs.data(), Locs.size());
Chris Lattner47fc7e92010-11-17 05:58:54 +00001352}
1353
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001354void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Chris Lattner458cd9c2009-03-10 23:21:44 +00001355 // Analyze the asm string to decompose it into its pieces. We know that Sema
1356 // has already done this, so it is guaranteed to be successful.
1357 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +00001358 unsigned DiagOffs;
1359 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Chris Lattner458cd9c2009-03-10 23:21:44 +00001361 // Assemble the pieces into the final asm string.
1362 std::string AsmString;
1363 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
1364 if (Pieces[i].isString())
1365 AsmString += Pieces[i].getString();
1366 else if (Pieces[i].getModifier() == '\0')
1367 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
1368 else
1369 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
1370 Pieces[i].getModifier() + '}';
Daniel Dunbar281f55c2008-10-17 20:58:01 +00001371 }
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Chris Lattner481fef92009-05-03 07:05:00 +00001373 // Get all the output and input constraints together.
1374 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1375 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1376
Mike Stump1eb44332009-09-09 15:08:12 +00001377 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +00001378 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
1379 S.getOutputName(i));
Chris Lattnerb9922592010-03-03 21:52:23 +00001380 bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid;
1381 assert(IsValid && "Failed to parse output constraint");
Chris Lattner481fef92009-05-03 07:05:00 +00001382 OutputConstraintInfos.push_back(Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001383 }
1384
Chris Lattner481fef92009-05-03 07:05:00 +00001385 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1386 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
1387 S.getInputName(i));
Chris Lattnerb9922592010-03-03 21:52:23 +00001388 bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(),
1389 S.getNumOutputs(), Info);
1390 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
Chris Lattner481fef92009-05-03 07:05:00 +00001391 InputConstraintInfos.push_back(Info);
1392 }
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001394 std::string Constraints;
Mike Stump1eb44332009-09-09 15:08:12 +00001395
Chris Lattnerede9d902009-05-03 07:53:25 +00001396 std::vector<LValue> ResultRegDests;
1397 std::vector<QualType> ResultRegQualTys;
Chris Lattnera077b5c2009-05-03 08:21:20 +00001398 std::vector<const llvm::Type *> ResultRegTypes;
1399 std::vector<const llvm::Type *> ResultTruncRegTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001400 std::vector<const llvm::Type*> ArgTypes;
1401 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001402
1403 // Keep track of inout constraints.
1404 std::string InOutConstraints;
1405 std::vector<llvm::Value*> InOutArgs;
1406 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +00001407
Mike Stump1eb44332009-09-09 15:08:12 +00001408 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +00001409 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
Anders Carlsson03eb5432009-01-27 20:38:24 +00001410
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001411 // Simplify the output constraint.
Chris Lattner481fef92009-05-03 07:05:00 +00001412 std::string OutputConstraint(S.getOutputConstraint(i));
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +00001413 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Mike Stump1eb44332009-09-09 15:08:12 +00001414
Chris Lattner810f6d52009-03-13 17:38:01 +00001415 const Expr *OutExpr = S.getOutputExpr(i);
1416 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Rafael Espindola03117d12011-01-01 21:12:33 +00001418 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr, Target,
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001419 CGM, S);
1420
Chris Lattner810f6d52009-03-13 17:38:01 +00001421 LValue Dest = EmitLValue(OutExpr);
Chris Lattnerede9d902009-05-03 07:53:25 +00001422 if (!Constraints.empty())
Anders Carlssonbad3a942009-05-01 00:16:04 +00001423 Constraints += ',';
1424
Chris Lattnera077b5c2009-05-03 08:21:20 +00001425 // If this is a register output, then make the inline asm return it
1426 // by-value. If this is a memory result, return the value by-reference.
Chris Lattnerede9d902009-05-03 07:53:25 +00001427 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
Chris Lattnera077b5c2009-05-03 08:21:20 +00001428 Constraints += "=" + OutputConstraint;
Chris Lattnerede9d902009-05-03 07:53:25 +00001429 ResultRegQualTys.push_back(OutExpr->getType());
1430 ResultRegDests.push_back(Dest);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001431 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1432 ResultTruncRegTypes.push_back(ResultRegTypes.back());
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Chris Lattnera077b5c2009-05-03 08:21:20 +00001434 // If this output is tied to an input, and if the input is larger, then
1435 // we need to set the actual result type of the inline asm node to be the
1436 // same as the input type.
1437 if (Info.hasMatchingInput()) {
Chris Lattnerebfc9852009-05-03 08:38:58 +00001438 unsigned InputNo;
1439 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1440 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
Chris Lattneraab64d02010-04-23 17:27:29 +00001441 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
Chris Lattnera077b5c2009-05-03 08:21:20 +00001442 break;
Chris Lattnerebfc9852009-05-03 08:38:58 +00001443 }
1444 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Chris Lattnera077b5c2009-05-03 08:21:20 +00001446 QualType InputTy = S.getInputExpr(InputNo)->getType();
Chris Lattneraab64d02010-04-23 17:27:29 +00001447 QualType OutputType = OutExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Chris Lattnera077b5c2009-05-03 08:21:20 +00001449 uint64_t InputSize = getContext().getTypeSize(InputTy);
Chris Lattneraab64d02010-04-23 17:27:29 +00001450 if (getContext().getTypeSize(OutputType) < InputSize) {
1451 // Form the asm to return the value as a larger integer or fp type.
1452 ResultRegTypes.back() = ConvertType(InputTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001453 }
1454 }
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001455 if (const llvm::Type* AdjTy =
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001456 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1457 ResultRegTypes.back()))
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001458 ResultRegTypes.back() = AdjTy;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001459 } else {
1460 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +00001461 Args.push_back(Dest.getAddress());
Anders Carlssonf39a4212008-02-05 20:01:53 +00001462 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001463 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001464 }
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Chris Lattner44def072009-04-26 07:16:29 +00001466 if (Info.isReadWrite()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +00001467 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +00001468
Anders Carlssonfca93612009-08-04 18:18:36 +00001469 const Expr *InputExpr = S.getOutputExpr(i);
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001470 llvm::Value *Arg = EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(),
1471 InOutConstraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Chris Lattner44def072009-04-26 07:16:29 +00001473 if (Info.allowsRegister())
Anders Carlsson9f2505b2009-01-11 21:23:27 +00001474 InOutConstraints += llvm::utostr(i);
1475 else
1476 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +00001477
Anders Carlssonfca93612009-08-04 18:18:36 +00001478 InOutArgTypes.push_back(Arg->getType());
1479 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001480 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001481 }
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001483 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
Mike Stump1eb44332009-09-09 15:08:12 +00001484
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001485 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1486 const Expr *InputExpr = S.getInputExpr(i);
1487
Chris Lattner481fef92009-05-03 07:05:00 +00001488 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1489
Chris Lattnerede9d902009-05-03 07:53:25 +00001490 if (!Constraints.empty())
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001491 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001493 // Simplify the input constraint.
Chris Lattner481fef92009-05-03 07:05:00 +00001494 std::string InputConstraint(S.getInputConstraint(i));
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001495 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
Chris Lattner2819fa82009-04-26 17:57:12 +00001496 &OutputConstraintInfos);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001497
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001498 InputConstraint =
Rafael Espindola03117d12011-01-01 21:12:33 +00001499 AddVariableConstraints(InputConstraint,
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001500 *InputExpr->IgnoreParenNoopCasts(getContext()),
1501 Target, CGM, S);
1502
Anders Carlsson63471722009-01-11 19:32:54 +00001503 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Chris Lattner4df4ee02009-05-03 07:27:51 +00001505 // If this input argument is tied to a larger output result, extend the
1506 // input to be the same size as the output. The LLVM backend wants to see
1507 // the input and output of a matching constraint be the same size. Note
1508 // that GCC does not define what the top bits are here. We use zext because
1509 // that is usually cheaper, but LLVM IR should really get an anyext someday.
1510 if (Info.hasTiedOperand()) {
1511 unsigned Output = Info.getTiedOperand();
Chris Lattneraab64d02010-04-23 17:27:29 +00001512 QualType OutputType = S.getOutputExpr(Output)->getType();
Chris Lattner4df4ee02009-05-03 07:27:51 +00001513 QualType InputTy = InputExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Chris Lattneraab64d02010-04-23 17:27:29 +00001515 if (getContext().getTypeSize(OutputType) >
Chris Lattner4df4ee02009-05-03 07:27:51 +00001516 getContext().getTypeSize(InputTy)) {
1517 // Use ptrtoint as appropriate so that we can do our extension.
1518 if (isa<llvm::PointerType>(Arg->getType()))
Chris Lattner77b89b82010-06-27 07:15:29 +00001519 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
Chris Lattneraab64d02010-04-23 17:27:29 +00001520 const llvm::Type *OutputTy = ConvertType(OutputType);
1521 if (isa<llvm::IntegerType>(OutputTy))
1522 Arg = Builder.CreateZExt(Arg, OutputTy);
1523 else
1524 Arg = Builder.CreateFPExt(Arg, OutputTy);
Chris Lattner4df4ee02009-05-03 07:27:51 +00001525 }
1526 }
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001527 if (const llvm::Type* AdjTy =
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001528 getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
1529 Arg->getType()))
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001530 Arg = Builder.CreateBitCast(Arg, AdjTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001532 ArgTypes.push_back(Arg->getType());
1533 Args.push_back(Arg);
1534 Constraints += InputConstraint;
1535 }
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Anders Carlssonf39a4212008-02-05 20:01:53 +00001537 // Append the "input" part of inout constraints last.
1538 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1539 ArgTypes.push_back(InOutArgTypes[i]);
1540 Args.push_back(InOutArgs[i]);
1541 }
1542 Constraints += InOutConstraints;
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001544 // Clobbers
1545 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
Anders Carlsson83c021c2010-01-30 19:12:25 +00001546 llvm::StringRef Clobber = S.getClobber(i)->getString();
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001547
Anders Carlsson83c021c2010-01-30 19:12:25 +00001548 Clobber = Target.getNormalizedGCCRegisterName(Clobber);
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Anders Carlssonea041752008-02-06 00:11:32 +00001550 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001551 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Anders Carlssonea041752008-02-06 00:11:32 +00001553 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001554 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001555 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001556 }
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001558 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +00001559 std::string MachineClobbers = Target.getClobbers();
1560 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001561 if (!Constraints.empty())
1562 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00001563 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001564 }
Anders Carlssonbad3a942009-05-01 00:16:04 +00001565
1566 const llvm::Type *ResultType;
Chris Lattnera077b5c2009-05-03 08:21:20 +00001567 if (ResultRegTypes.empty())
John McCalld16c2cf2011-02-08 08:22:06 +00001568 ResultType = llvm::Type::getVoidTy(getLLVMContext());
Chris Lattnera077b5c2009-05-03 08:21:20 +00001569 else if (ResultRegTypes.size() == 1)
1570 ResultType = ResultRegTypes[0];
Anders Carlssonbad3a942009-05-01 00:16:04 +00001571 else
John McCalld16c2cf2011-02-08 08:22:06 +00001572 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
Mike Stump1eb44332009-09-09 15:08:12 +00001573
1574 const llvm::FunctionType *FTy =
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001575 llvm::FunctionType::get(ResultType, ArgTypes, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001576
1577 llvm::InlineAsm *IA =
1578 llvm::InlineAsm::get(FTy, AsmString, Constraints,
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001579 S.isVolatile() || S.getNumOutputs() == 0);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001580 llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end());
Anders Carlssonbc0822b2009-03-02 19:58:15 +00001581 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Chris Lattnerfc1a9c32010-04-07 05:46:54 +00001583 // Slap the source location of the inline asm into a !srcloc metadata on the
1584 // call.
Chris Lattner47fc7e92010-11-17 05:58:54 +00001585 Result->setMetadata("srcloc", getAsmSrcLocInfo(S.getAsmString(), *this));
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Chris Lattnera077b5c2009-05-03 08:21:20 +00001587 // Extract all of the register value results from the asm.
1588 std::vector<llvm::Value*> RegResults;
1589 if (ResultRegTypes.size() == 1) {
1590 RegResults.push_back(Result);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001591 } else {
Chris Lattnera077b5c2009-05-03 08:21:20 +00001592 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
Anders Carlssonbad3a942009-05-01 00:16:04 +00001593 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
Chris Lattnera077b5c2009-05-03 08:21:20 +00001594 RegResults.push_back(Tmp);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001595 }
1596 }
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Chris Lattnera077b5c2009-05-03 08:21:20 +00001598 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1599 llvm::Value *Tmp = RegResults[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Chris Lattnera077b5c2009-05-03 08:21:20 +00001601 // If the result type of the LLVM IR asm doesn't match the result type of
1602 // the expression, do the conversion.
1603 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1604 const llvm::Type *TruncTy = ResultTruncRegTypes[i];
Chris Lattneraab64d02010-04-23 17:27:29 +00001605
1606 // Truncate the integer result to the right size, note that TruncTy can be
1607 // a pointer.
1608 if (TruncTy->isFloatingPointTy())
1609 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00001610 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
Chris Lattneraab64d02010-04-23 17:27:29 +00001611 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
John McCalld16c2cf2011-02-08 08:22:06 +00001612 Tmp = Builder.CreateTrunc(Tmp,
1613 llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
Chris Lattnera077b5c2009-05-03 08:21:20 +00001614 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00001615 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
1616 uint64_t TmpSize =CGM.getTargetData().getTypeSizeInBits(Tmp->getType());
John McCalld16c2cf2011-02-08 08:22:06 +00001617 Tmp = Builder.CreatePtrToInt(Tmp,
1618 llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
Dan Gohman2dca88f2010-04-24 04:55:02 +00001619 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1620 } else if (TruncTy->isIntegerTy()) {
1621 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001622 } else if (TruncTy->isVectorTy()) {
1623 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001624 }
1625 }
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Chris Lattnera077b5c2009-05-03 08:21:20 +00001627 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i],
1628 ResultRegQualTys[i]);
1629 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001630}