blob: 7a1ce19b07cc401c419e1897b79d41d786d1ff20 [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) {
870 if (S.getRHS()) {
871 EmitCaseStmtRange(S);
872 return;
873 }
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000875 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000876 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000877 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
John McCalld16c2cf2011-02-08 08:22:06 +0000878 SwitchInsn->addCase(llvm::ConstantInt::get(getLLVMContext(), CaseVal),
879 CaseDest);
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Chris Lattner5512f282009-03-04 04:46:18 +0000881 // Recursively emitting the statement is acceptable, but is not wonderful for
882 // code where we have many case statements nested together, i.e.:
883 // case 1:
884 // case 2:
885 // case 3: etc.
886 // Handling this recursively will create a new block for each case statement
887 // that falls through to the next case which is IR intensive. It also causes
888 // deep recursion which can run into stack depth limitations. Handle
889 // sequential non-range case statements specially.
890 const CaseStmt *CurCase = &S;
891 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
892
893 // Otherwise, iteratively add consequtive cases to this switch stmt.
894 while (NextCase && NextCase->getRHS() == 0) {
895 CurCase = NextCase;
896 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
John McCalld16c2cf2011-02-08 08:22:06 +0000897 SwitchInsn->addCase(llvm::ConstantInt::get(getLLVMContext(), CaseVal),
898 CaseDest);
Chris Lattner5512f282009-03-04 04:46:18 +0000899
900 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
901 }
Mike Stump1eb44332009-09-09 15:08:12 +0000902
Chris Lattner5512f282009-03-04 04:46:18 +0000903 // Normal default recursion for non-cases.
904 EmitStmt(CurCase->getSubStmt());
Devang Patel51b09f22007-10-04 23:45:31 +0000905}
906
907void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000908 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Mike Stump1eb44332009-09-09 15:08:12 +0000909 assert(DefaultBlock->empty() &&
Daniel Dunbar55e87422008-11-11 02:29:29 +0000910 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000911 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000912 EmitStmt(S.getSubStmt());
913}
914
Chris Lattnerfda0f1f2011-02-28 00:22:07 +0000915/// CollectStatementsForCase - Given the body of a 'switch' statement and a
916/// constant value that is being switched on, see if we can dead code eliminate
917/// the body of the switch to a simple series of statements to emit. Basically,
918/// on a switch (5) we want to find these statements:
919/// case 5:
920/// printf(...); <--
921/// ++i; <--
922/// break;
923///
924/// and add them to the ResultStmts vector. If it is unsafe to do this
925/// transformation (for example, one of the elided statements contains a label
926/// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
927/// should include statements after it (e.g. the printf() line is a substmt of
928/// the case) then return CSFC_FallThrough. If we handled it and found a break
929/// statement, then return CSFC_Success.
930///
931/// If Case is non-null, then we are looking for the specified case, checking
932/// that nothing we jump over contains labels. If Case is null, then we found
933/// the case and are looking for the break.
934///
935/// If the recursive walk actually finds our Case, then we set FoundCase to
936/// true.
937///
938enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
939static CSFC_Result CollectStatementsForCase(const Stmt *S,
940 const SwitchCase *Case,
941 bool &FoundCase,
942 llvm::SmallVectorImpl<const Stmt*> &ResultStmts) {
Chris Lattner38589382011-02-28 01:02:29 +0000943 // If this is a null statement, just succeed.
944 if (S == 0)
945 return Case ? CSFC_Success : CSFC_FallThrough;
946
Chris Lattnerfda0f1f2011-02-28 00:22:07 +0000947 // If this is the switchcase (case 4: or default) that we're looking for, then
948 // we're in business. Just add the substatement.
949 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
950 if (S == Case) {
951 FoundCase = true;
952 return CollectStatementsForCase(SC->getSubStmt(), 0, FoundCase,
953 ResultStmts);
954 }
955
956 // Otherwise, this is some other case or default statement, just ignore it.
957 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
958 ResultStmts);
959 }
Chris Lattner38589382011-02-28 01:02:29 +0000960
961 // If we are in the live part of the code and we found our break statement,
962 // return a success!
963 if (Case == 0 && isa<BreakStmt>(S))
964 return CSFC_Success;
Chris Lattnerfda0f1f2011-02-28 00:22:07 +0000965
Chris Lattner38589382011-02-28 01:02:29 +0000966 // If this is a switch statement, then it might contain the SwitchCase, the
967 // break, or neither.
968 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
969 // Handle this as two cases: we might be looking for the SwitchCase (if so
970 // the skipped statements must be skippable) or we might already have it.
971 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
972 if (Case) {
Chris Lattner3f06e272011-02-28 07:22:44 +0000973 // Keep track of whether we see a skipped declaration. The code could be
974 // using the declaration even if it is skipped, so we can't optimize out
975 // the decl if the kept statements might refer to it.
976 bool HadSkippedDecl = false;
977
Chris Lattner38589382011-02-28 01:02:29 +0000978 // If we're looking for the case, just see if we can skip each of the
979 // substatements.
980 for (; Case && I != E; ++I) {
Chris Lattner3f06e272011-02-28 07:22:44 +0000981 HadSkippedDecl |= isa<DeclStmt>(I);
982
Chris Lattner38589382011-02-28 01:02:29 +0000983 switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
984 case CSFC_Failure: return CSFC_Failure;
985 case CSFC_Success:
986 // A successful result means that either 1) that the statement doesn't
987 // have the case and is skippable, or 2) does contain the case value
Chris Lattner94671102011-02-28 07:16:14 +0000988 // and also contains the break to exit the switch. In the later case,
989 // we just verify the rest of the statements are elidable.
990 if (FoundCase) {
Chris Lattner3f06e272011-02-28 07:22:44 +0000991 // If we found the case and skipped declarations, we can't do the
992 // optimization.
993 if (HadSkippedDecl)
994 return CSFC_Failure;
995
Chris Lattner94671102011-02-28 07:16:14 +0000996 for (++I; I != E; ++I)
997 if (CodeGenFunction::ContainsLabel(*I, true))
998 return CSFC_Failure;
999 return CSFC_Success;
1000 }
Chris Lattner38589382011-02-28 01:02:29 +00001001 break;
1002 case CSFC_FallThrough:
1003 // If we have a fallthrough condition, then we must have found the
1004 // case started to include statements. Consider the rest of the
1005 // statements in the compound statement as candidates for inclusion.
1006 assert(FoundCase && "Didn't find case but returned fallthrough?");
1007 // We recursively found Case, so we're not looking for it anymore.
1008 Case = 0;
Chris Lattner3f06e272011-02-28 07:22:44 +00001009
1010 // If we found the case and skipped declarations, we can't do the
1011 // optimization.
1012 if (HadSkippedDecl)
1013 return CSFC_Failure;
Chris Lattner38589382011-02-28 01:02:29 +00001014 break;
1015 }
1016 }
1017 }
1018
1019 // If we have statements in our range, then we know that the statements are
1020 // live and need to be added to the set of statements we're tracking.
1021 for (; I != E; ++I) {
1022 switch (CollectStatementsForCase(*I, 0, FoundCase, ResultStmts)) {
1023 case CSFC_Failure: return CSFC_Failure;
1024 case CSFC_FallThrough:
1025 // A fallthrough result means that the statement was simple and just
1026 // included in ResultStmt, keep adding them afterwards.
1027 break;
1028 case CSFC_Success:
1029 // A successful result means that we found the break statement and
1030 // stopped statement inclusion. We just ensure that any leftover stmts
1031 // are skippable and return success ourselves.
1032 for (++I; I != E; ++I)
1033 if (CodeGenFunction::ContainsLabel(*I, true))
1034 return CSFC_Failure;
1035 return CSFC_Success;
1036 }
1037 }
1038
1039 return Case ? CSFC_Success : CSFC_FallThrough;
1040 }
1041
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001042 // Okay, this is some other statement that we don't handle explicitly, like a
1043 // for statement or increment etc. If we are skipping over this statement,
1044 // just verify it doesn't have labels, which would make it invalid to elide.
1045 if (Case) {
Chris Lattner3f06e272011-02-28 07:22:44 +00001046 if (CodeGenFunction::ContainsLabel(S, true))
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001047 return CSFC_Failure;
1048 return CSFC_Success;
1049 }
1050
1051 // Otherwise, we want to include this statement. Everything is cool with that
1052 // so long as it doesn't contain a break out of the switch we're in.
1053 if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1054
1055 // Otherwise, everything is great. Include the statement and tell the caller
1056 // that we fall through and include the next statement as well.
1057 ResultStmts.push_back(S);
1058 return CSFC_FallThrough;
1059}
1060
1061/// FindCaseStatementsForValue - Find the case statement being jumped to and
1062/// then invoke CollectStatementsForCase to find the list of statements to emit
1063/// for a switch on constant. See the comment above CollectStatementsForCase
1064/// for more details.
1065static bool FindCaseStatementsForValue(const SwitchStmt &S,
1066 const llvm::APInt &ConstantCondValue,
1067 llvm::SmallVectorImpl<const Stmt*> &ResultStmts,
1068 ASTContext &C) {
1069 // First step, find the switch case that is being branched to. We can do this
1070 // efficiently by scanning the SwitchCase list.
1071 const SwitchCase *Case = S.getSwitchCaseList();
1072 const DefaultStmt *DefaultCase = 0;
1073
1074 for (; Case; Case = Case->getNextSwitchCase()) {
1075 // It's either a default or case. Just remember the default statement in
1076 // case we're not jumping to any numbered cases.
1077 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1078 DefaultCase = DS;
1079 continue;
1080 }
1081
1082 // Check to see if this case is the one we're looking for.
1083 const CaseStmt *CS = cast<CaseStmt>(Case);
1084 // Don't handle case ranges yet.
1085 if (CS->getRHS()) return false;
1086
1087 // If we found our case, remember it as 'case'.
1088 if (CS->getLHS()->EvaluateAsInt(C) == ConstantCondValue)
1089 break;
1090 }
1091
1092 // If we didn't find a matching case, we use a default if it exists, or we
1093 // elide the whole switch body!
1094 if (Case == 0) {
1095 // It is safe to elide the body of the switch if it doesn't contain labels
1096 // etc. If it is safe, return successfully with an empty ResultStmts list.
1097 if (DefaultCase == 0)
1098 return !CodeGenFunction::ContainsLabel(&S);
1099 Case = DefaultCase;
1100 }
1101
1102 // Ok, we know which case is being jumped to, try to collect all the
1103 // statements that follow it. This can fail for a variety of reasons. Also,
1104 // check to see that the recursive walk actually found our case statement.
1105 // Insane cases like this can fail to find it in the recursive walk since we
1106 // don't handle every stmt kind:
1107 // switch (4) {
1108 // while (1) {
1109 // case 4: ...
1110 bool FoundCase = false;
1111 return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1112 ResultStmts) != CSFC_Failure &&
1113 FoundCase;
1114}
1115
Devang Patel51b09f22007-10-04 23:45:31 +00001116void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001117 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1118
1119 RunCleanupsScope ConditionScope(*this);
Douglas Gregord3d53012009-11-24 17:07:59 +00001120
1121 if (S.getConditionVariable())
John McCallb6bbcc92010-10-15 04:57:14 +00001122 EmitAutoVarDecl(*S.getConditionVariable());
Douglas Gregord3d53012009-11-24 17:07:59 +00001123
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001124 // See if we can constant fold the condition of the switch and therefore only
1125 // emit the live case statement (if any) of the switch.
1126 llvm::APInt ConstantCondValue;
1127 if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1128 llvm::SmallVector<const Stmt*, 4> CaseStmts;
1129 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1130 getContext())) {
1131 RunCleanupsScope ExecutedScope(*this);
1132
1133 // Okay, we can dead code eliminate everything except this case. Emit the
1134 // specified series of statements and we're good.
1135 for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1136 EmitStmt(CaseStmts[i]);
1137 return;
1138 }
1139 }
1140
Devang Patel51b09f22007-10-04 23:45:31 +00001141 llvm::Value *CondV = EmitScalarExpr(S.getCond());
1142
1143 // Handle nested switch statements.
1144 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +00001145 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +00001146
Daniel Dunbar16f23572008-07-25 01:11:38 +00001147 // Create basic block to hold stuff that comes after switch
1148 // statement. We also need to create a default block now so that
1149 // explicit case ranges tests can have a place to jump to on
1150 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001151 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +00001152 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1153 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +00001154
Daniel Dunbar09124252008-11-12 08:21:33 +00001155 // Clear the insertion point to indicate we are in unreachable code.
1156 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +00001157
Devang Patele9b8c0a2007-10-30 20:59:40 +00001158 // All break statements jump to NextBlock. If BreakContinueStack is non empty
1159 // then reuse last ContinueBlock.
John McCallf1549f62010-07-06 01:34:17 +00001160 JumpDest OuterContinue;
Anders Carlssone4b6d342009-02-10 05:52:02 +00001161 if (!BreakContinueStack.empty())
John McCallf1549f62010-07-06 01:34:17 +00001162 OuterContinue = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +00001163
John McCallf1549f62010-07-06 01:34:17 +00001164 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
Devang Patel51b09f22007-10-04 23:45:31 +00001165
1166 // Emit switch body.
1167 EmitStmt(S.getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Anders Carlssone4b6d342009-02-10 05:52:02 +00001169 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +00001170
Daniel Dunbar16f23572008-07-25 01:11:38 +00001171 // Update the default block in case explicit case range tests have
1172 // been chained on top.
1173 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Mike Stump1eb44332009-09-09 15:08:12 +00001174
John McCallf1549f62010-07-06 01:34:17 +00001175 // If a default was never emitted:
Daniel Dunbar16f23572008-07-25 01:11:38 +00001176 if (!DefaultBlock->getParent()) {
John McCallf1549f62010-07-06 01:34:17 +00001177 // If we have cleanups, emit the default block so that there's a
1178 // place to jump through the cleanups from.
1179 if (ConditionScope.requiresCleanups()) {
1180 EmitBlock(DefaultBlock);
1181
1182 // Otherwise, just forward the default block to the switch end.
1183 } else {
John McCallff8e1152010-07-23 21:56:41 +00001184 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
John McCallf1549f62010-07-06 01:34:17 +00001185 delete DefaultBlock;
1186 }
Daniel Dunbar16f23572008-07-25 01:11:38 +00001187 }
Devang Patel51b09f22007-10-04 23:45:31 +00001188
John McCallff8e1152010-07-23 21:56:41 +00001189 ConditionScope.ForceCleanup();
1190
Daniel Dunbar16f23572008-07-25 01:11:38 +00001191 // Emit continuation.
John McCallff8e1152010-07-23 21:56:41 +00001192 EmitBlock(SwitchExit.getBlock(), true);
Daniel Dunbar16f23572008-07-25 01:11:38 +00001193
Devang Patel51b09f22007-10-04 23:45:31 +00001194 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +00001195 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +00001196}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001197
Chris Lattner2819fa82009-04-26 17:57:12 +00001198static std::string
Daniel Dunbar444be732009-11-13 05:51:54 +00001199SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
Chris Lattner2819fa82009-04-26 17:57:12 +00001200 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001201 std::string Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001203 while (*Constraint) {
1204 switch (*Constraint) {
1205 default:
John Thompson2f474ea2010-09-18 01:15:13 +00001206 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001207 break;
1208 // Ignore these
1209 case '*':
1210 case '?':
1211 case '!':
John Thompsonef44e112010-08-10 19:20:14 +00001212 case '=': // Will see this and the following in mult-alt constraints.
1213 case '+':
1214 break;
John Thompson2f474ea2010-09-18 01:15:13 +00001215 case ',':
1216 Result += "|";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001217 break;
1218 case 'g':
1219 Result += "imr";
1220 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001221 case '[': {
Chris Lattner2819fa82009-04-26 17:57:12 +00001222 assert(OutCons &&
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001223 "Must pass output names to constraints with a symbolic name");
1224 unsigned Index;
Mike Stump1eb44332009-09-09 15:08:12 +00001225 bool result = Target.resolveSymbolicName(Constraint,
Chris Lattner2819fa82009-04-26 17:57:12 +00001226 &(*OutCons)[0],
1227 OutCons->size(), Index);
Chris Lattnercbf40f92011-01-05 18:41:53 +00001228 assert(result && "Could not resolve symbolic name"); (void)result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001229 Result += llvm::utostr(Index);
1230 break;
1231 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001232 }
Mike Stump1eb44332009-09-09 15:08:12 +00001233
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001234 Constraint++;
1235 }
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001237 return Result;
1238}
1239
Rafael Espindola03117d12011-01-01 21:12:33 +00001240/// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1241/// as using a particular register add that as a constraint that will be used
1242/// in this asm stmt.
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001243static std::string
Rafael Espindola03117d12011-01-01 21:12:33 +00001244AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1245 const TargetInfo &Target, CodeGenModule &CGM,
1246 const AsmStmt &Stmt) {
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001247 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1248 if (!AsmDeclRef)
1249 return Constraint;
1250 const ValueDecl &Value = *AsmDeclRef->getDecl();
1251 const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1252 if (!Variable)
1253 return Constraint;
1254 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1255 if (!Attr)
1256 return Constraint;
1257 llvm::StringRef Register = Attr->getLabel();
Rafael Espindolabaf86952011-01-01 21:47:03 +00001258 assert(Target.isValidGCCRegisterName(Register));
Rafael Espindola33a53442011-01-02 03:59:13 +00001259 // FIXME: We should check which registers are compatible with "r" or "x".
1260 if (Constraint != "r" && Constraint != "x") {
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001261 CGM.ErrorUnsupported(&Stmt, "__asm__");
1262 return Constraint;
1263 }
1264 return "{" + Register.str() + "}";
1265}
1266
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001267llvm::Value*
1268CodeGenFunction::EmitAsmInputLValue(const AsmStmt &S,
1269 const TargetInfo::ConstraintInfo &Info,
1270 LValue InputValue, QualType InputType,
1271 std::string &ConstraintStr) {
Anders Carlsson63471722009-01-11 19:32:54 +00001272 llvm::Value *Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00001273 if (Info.allowsRegister() || !Info.allowsMemory()) {
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001274 if (!CodeGenFunction::hasAggregateLLVMType(InputType)) {
1275 Arg = EmitLoadOfLValue(InputValue, InputType).getScalarVal();
Anders Carlsson63471722009-01-11 19:32:54 +00001276 } else {
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001277 const llvm::Type *Ty = ConvertType(InputType);
Anders Carlssonebaae2a2009-01-12 02:22:13 +00001278 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
1279 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
John McCalld16c2cf2011-02-08 08:22:06 +00001280 Ty = llvm::IntegerType::get(getLLVMContext(), Size);
Anders Carlssonebaae2a2009-01-12 02:22:13 +00001281 Ty = llvm::PointerType::getUnqual(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001283 Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1284 Ty));
Anders Carlssonebaae2a2009-01-12 02:22:13 +00001285 } else {
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001286 Arg = InputValue.getAddress();
Anders Carlssonebaae2a2009-01-12 02:22:13 +00001287 ConstraintStr += '*';
1288 }
Anders Carlsson63471722009-01-11 19:32:54 +00001289 }
1290 } else {
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001291 Arg = InputValue.getAddress();
Anders Carlsson63471722009-01-11 19:32:54 +00001292 ConstraintStr += '*';
1293 }
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Anders Carlsson63471722009-01-11 19:32:54 +00001295 return Arg;
1296}
1297
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001298llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
1299 const TargetInfo::ConstraintInfo &Info,
1300 const Expr *InputExpr,
1301 std::string &ConstraintStr) {
1302 if (Info.allowsRegister() || !Info.allowsMemory())
1303 if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType()))
1304 return EmitScalarExpr(InputExpr);
1305
1306 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1307 LValue Dest = EmitLValue(InputExpr);
1308 return EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(), ConstraintStr);
1309}
1310
Chris Lattner47fc7e92010-11-17 05:58:54 +00001311/// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
Chris Lattner5d936532010-11-17 08:25:26 +00001312/// asm call instruction. The !srcloc MDNode contains a list of constant
1313/// integers which are the source locations of the start of each line in the
1314/// asm.
Chris Lattner47fc7e92010-11-17 05:58:54 +00001315static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1316 CodeGenFunction &CGF) {
Chris Lattner5d936532010-11-17 08:25:26 +00001317 llvm::SmallVector<llvm::Value *, 8> Locs;
1318 // Add the location of the first line to the MDNode.
1319 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1320 Str->getLocStart().getRawEncoding()));
1321 llvm::StringRef StrVal = Str->getString();
1322 if (!StrVal.empty()) {
1323 const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1324 const LangOptions &LangOpts = CGF.CGM.getLangOptions();
1325
1326 // Add the location of the start of each subsequent line of the asm to the
1327 // MDNode.
1328 for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
1329 if (StrVal[i] != '\n') continue;
1330 SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
1331 CGF.Target);
1332 Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1333 LineLoc.getRawEncoding()));
1334 }
1335 }
1336
1337 return llvm::MDNode::get(CGF.getLLVMContext(), Locs.data(), Locs.size());
Chris Lattner47fc7e92010-11-17 05:58:54 +00001338}
1339
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001340void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Chris Lattner458cd9c2009-03-10 23:21:44 +00001341 // Analyze the asm string to decompose it into its pieces. We know that Sema
1342 // has already done this, so it is guaranteed to be successful.
1343 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +00001344 unsigned DiagOffs;
1345 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
Mike Stump1eb44332009-09-09 15:08:12 +00001346
Chris Lattner458cd9c2009-03-10 23:21:44 +00001347 // Assemble the pieces into the final asm string.
1348 std::string AsmString;
1349 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
1350 if (Pieces[i].isString())
1351 AsmString += Pieces[i].getString();
1352 else if (Pieces[i].getModifier() == '\0')
1353 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
1354 else
1355 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
1356 Pieces[i].getModifier() + '}';
Daniel Dunbar281f55c2008-10-17 20:58:01 +00001357 }
Mike Stump1eb44332009-09-09 15:08:12 +00001358
Chris Lattner481fef92009-05-03 07:05:00 +00001359 // Get all the output and input constraints together.
1360 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1361 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1362
Mike Stump1eb44332009-09-09 15:08:12 +00001363 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +00001364 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
1365 S.getOutputName(i));
Chris Lattnerb9922592010-03-03 21:52:23 +00001366 bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid;
1367 assert(IsValid && "Failed to parse output constraint");
Chris Lattner481fef92009-05-03 07:05:00 +00001368 OutputConstraintInfos.push_back(Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001369 }
1370
Chris Lattner481fef92009-05-03 07:05:00 +00001371 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1372 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
1373 S.getInputName(i));
Chris Lattnerb9922592010-03-03 21:52:23 +00001374 bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(),
1375 S.getNumOutputs(), Info);
1376 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
Chris Lattner481fef92009-05-03 07:05:00 +00001377 InputConstraintInfos.push_back(Info);
1378 }
Mike Stump1eb44332009-09-09 15:08:12 +00001379
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001380 std::string Constraints;
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Chris Lattnerede9d902009-05-03 07:53:25 +00001382 std::vector<LValue> ResultRegDests;
1383 std::vector<QualType> ResultRegQualTys;
Chris Lattnera077b5c2009-05-03 08:21:20 +00001384 std::vector<const llvm::Type *> ResultRegTypes;
1385 std::vector<const llvm::Type *> ResultTruncRegTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001386 std::vector<const llvm::Type*> ArgTypes;
1387 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001388
1389 // Keep track of inout constraints.
1390 std::string InOutConstraints;
1391 std::vector<llvm::Value*> InOutArgs;
1392 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +00001393
Mike Stump1eb44332009-09-09 15:08:12 +00001394 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +00001395 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
Anders Carlsson03eb5432009-01-27 20:38:24 +00001396
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001397 // Simplify the output constraint.
Chris Lattner481fef92009-05-03 07:05:00 +00001398 std::string OutputConstraint(S.getOutputConstraint(i));
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +00001399 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Chris Lattner810f6d52009-03-13 17:38:01 +00001401 const Expr *OutExpr = S.getOutputExpr(i);
1402 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001403
Rafael Espindola03117d12011-01-01 21:12:33 +00001404 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr, Target,
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001405 CGM, S);
1406
Chris Lattner810f6d52009-03-13 17:38:01 +00001407 LValue Dest = EmitLValue(OutExpr);
Chris Lattnerede9d902009-05-03 07:53:25 +00001408 if (!Constraints.empty())
Anders Carlssonbad3a942009-05-01 00:16:04 +00001409 Constraints += ',';
1410
Chris Lattnera077b5c2009-05-03 08:21:20 +00001411 // If this is a register output, then make the inline asm return it
1412 // by-value. If this is a memory result, return the value by-reference.
Chris Lattnerede9d902009-05-03 07:53:25 +00001413 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
Chris Lattnera077b5c2009-05-03 08:21:20 +00001414 Constraints += "=" + OutputConstraint;
Chris Lattnerede9d902009-05-03 07:53:25 +00001415 ResultRegQualTys.push_back(OutExpr->getType());
1416 ResultRegDests.push_back(Dest);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001417 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1418 ResultTruncRegTypes.push_back(ResultRegTypes.back());
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Chris Lattnera077b5c2009-05-03 08:21:20 +00001420 // If this output is tied to an input, and if the input is larger, then
1421 // we need to set the actual result type of the inline asm node to be the
1422 // same as the input type.
1423 if (Info.hasMatchingInput()) {
Chris Lattnerebfc9852009-05-03 08:38:58 +00001424 unsigned InputNo;
1425 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1426 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
Chris Lattneraab64d02010-04-23 17:27:29 +00001427 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
Chris Lattnera077b5c2009-05-03 08:21:20 +00001428 break;
Chris Lattnerebfc9852009-05-03 08:38:58 +00001429 }
1430 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Chris Lattnera077b5c2009-05-03 08:21:20 +00001432 QualType InputTy = S.getInputExpr(InputNo)->getType();
Chris Lattneraab64d02010-04-23 17:27:29 +00001433 QualType OutputType = OutExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Chris Lattnera077b5c2009-05-03 08:21:20 +00001435 uint64_t InputSize = getContext().getTypeSize(InputTy);
Chris Lattneraab64d02010-04-23 17:27:29 +00001436 if (getContext().getTypeSize(OutputType) < InputSize) {
1437 // Form the asm to return the value as a larger integer or fp type.
1438 ResultRegTypes.back() = ConvertType(InputTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001439 }
1440 }
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001441 if (const llvm::Type* AdjTy =
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001442 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1443 ResultRegTypes.back()))
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001444 ResultRegTypes.back() = AdjTy;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001445 } else {
1446 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +00001447 Args.push_back(Dest.getAddress());
Anders Carlssonf39a4212008-02-05 20:01:53 +00001448 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001449 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001450 }
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Chris Lattner44def072009-04-26 07:16:29 +00001452 if (Info.isReadWrite()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +00001453 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +00001454
Anders Carlssonfca93612009-08-04 18:18:36 +00001455 const Expr *InputExpr = S.getOutputExpr(i);
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001456 llvm::Value *Arg = EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(),
1457 InOutConstraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001458
Chris Lattner44def072009-04-26 07:16:29 +00001459 if (Info.allowsRegister())
Anders Carlsson9f2505b2009-01-11 21:23:27 +00001460 InOutConstraints += llvm::utostr(i);
1461 else
1462 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +00001463
Anders Carlssonfca93612009-08-04 18:18:36 +00001464 InOutArgTypes.push_back(Arg->getType());
1465 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001466 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001467 }
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001469 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001471 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1472 const Expr *InputExpr = S.getInputExpr(i);
1473
Chris Lattner481fef92009-05-03 07:05:00 +00001474 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1475
Chris Lattnerede9d902009-05-03 07:53:25 +00001476 if (!Constraints.empty())
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001477 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001479 // Simplify the input constraint.
Chris Lattner481fef92009-05-03 07:05:00 +00001480 std::string InputConstraint(S.getInputConstraint(i));
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001481 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
Chris Lattner2819fa82009-04-26 17:57:12 +00001482 &OutputConstraintInfos);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001483
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001484 InputConstraint =
Rafael Espindola03117d12011-01-01 21:12:33 +00001485 AddVariableConstraints(InputConstraint,
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001486 *InputExpr->IgnoreParenNoopCasts(getContext()),
1487 Target, CGM, S);
1488
Anders Carlsson63471722009-01-11 19:32:54 +00001489 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Chris Lattner4df4ee02009-05-03 07:27:51 +00001491 // If this input argument is tied to a larger output result, extend the
1492 // input to be the same size as the output. The LLVM backend wants to see
1493 // the input and output of a matching constraint be the same size. Note
1494 // that GCC does not define what the top bits are here. We use zext because
1495 // that is usually cheaper, but LLVM IR should really get an anyext someday.
1496 if (Info.hasTiedOperand()) {
1497 unsigned Output = Info.getTiedOperand();
Chris Lattneraab64d02010-04-23 17:27:29 +00001498 QualType OutputType = S.getOutputExpr(Output)->getType();
Chris Lattner4df4ee02009-05-03 07:27:51 +00001499 QualType InputTy = InputExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Chris Lattneraab64d02010-04-23 17:27:29 +00001501 if (getContext().getTypeSize(OutputType) >
Chris Lattner4df4ee02009-05-03 07:27:51 +00001502 getContext().getTypeSize(InputTy)) {
1503 // Use ptrtoint as appropriate so that we can do our extension.
1504 if (isa<llvm::PointerType>(Arg->getType()))
Chris Lattner77b89b82010-06-27 07:15:29 +00001505 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
Chris Lattneraab64d02010-04-23 17:27:29 +00001506 const llvm::Type *OutputTy = ConvertType(OutputType);
1507 if (isa<llvm::IntegerType>(OutputTy))
1508 Arg = Builder.CreateZExt(Arg, OutputTy);
1509 else
1510 Arg = Builder.CreateFPExt(Arg, OutputTy);
Chris Lattner4df4ee02009-05-03 07:27:51 +00001511 }
1512 }
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001513 if (const llvm::Type* AdjTy =
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001514 getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
1515 Arg->getType()))
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001516 Arg = Builder.CreateBitCast(Arg, AdjTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001518 ArgTypes.push_back(Arg->getType());
1519 Args.push_back(Arg);
1520 Constraints += InputConstraint;
1521 }
Mike Stump1eb44332009-09-09 15:08:12 +00001522
Anders Carlssonf39a4212008-02-05 20:01:53 +00001523 // Append the "input" part of inout constraints last.
1524 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1525 ArgTypes.push_back(InOutArgTypes[i]);
1526 Args.push_back(InOutArgs[i]);
1527 }
1528 Constraints += InOutConstraints;
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001530 // Clobbers
1531 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
Anders Carlsson83c021c2010-01-30 19:12:25 +00001532 llvm::StringRef Clobber = S.getClobber(i)->getString();
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001533
Anders Carlsson83c021c2010-01-30 19:12:25 +00001534 Clobber = Target.getNormalizedGCCRegisterName(Clobber);
Mike Stump1eb44332009-09-09 15:08:12 +00001535
Anders Carlssonea041752008-02-06 00:11:32 +00001536 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001537 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Anders Carlssonea041752008-02-06 00:11:32 +00001539 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001540 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001541 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001542 }
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001544 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +00001545 std::string MachineClobbers = Target.getClobbers();
1546 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001547 if (!Constraints.empty())
1548 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00001549 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001550 }
Anders Carlssonbad3a942009-05-01 00:16:04 +00001551
1552 const llvm::Type *ResultType;
Chris Lattnera077b5c2009-05-03 08:21:20 +00001553 if (ResultRegTypes.empty())
John McCalld16c2cf2011-02-08 08:22:06 +00001554 ResultType = llvm::Type::getVoidTy(getLLVMContext());
Chris Lattnera077b5c2009-05-03 08:21:20 +00001555 else if (ResultRegTypes.size() == 1)
1556 ResultType = ResultRegTypes[0];
Anders Carlssonbad3a942009-05-01 00:16:04 +00001557 else
John McCalld16c2cf2011-02-08 08:22:06 +00001558 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
Mike Stump1eb44332009-09-09 15:08:12 +00001559
1560 const llvm::FunctionType *FTy =
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001561 llvm::FunctionType::get(ResultType, ArgTypes, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001562
1563 llvm::InlineAsm *IA =
1564 llvm::InlineAsm::get(FTy, AsmString, Constraints,
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001565 S.isVolatile() || S.getNumOutputs() == 0);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001566 llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end());
Anders Carlssonbc0822b2009-03-02 19:58:15 +00001567 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Chris Lattnerfc1a9c32010-04-07 05:46:54 +00001569 // Slap the source location of the inline asm into a !srcloc metadata on the
1570 // call.
Chris Lattner47fc7e92010-11-17 05:58:54 +00001571 Result->setMetadata("srcloc", getAsmSrcLocInfo(S.getAsmString(), *this));
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Chris Lattnera077b5c2009-05-03 08:21:20 +00001573 // Extract all of the register value results from the asm.
1574 std::vector<llvm::Value*> RegResults;
1575 if (ResultRegTypes.size() == 1) {
1576 RegResults.push_back(Result);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001577 } else {
Chris Lattnera077b5c2009-05-03 08:21:20 +00001578 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
Anders Carlssonbad3a942009-05-01 00:16:04 +00001579 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
Chris Lattnera077b5c2009-05-03 08:21:20 +00001580 RegResults.push_back(Tmp);
Anders Carlssonbad3a942009-05-01 00:16:04 +00001581 }
1582 }
Mike Stump1eb44332009-09-09 15:08:12 +00001583
Chris Lattnera077b5c2009-05-03 08:21:20 +00001584 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1585 llvm::Value *Tmp = RegResults[i];
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Chris Lattnera077b5c2009-05-03 08:21:20 +00001587 // If the result type of the LLVM IR asm doesn't match the result type of
1588 // the expression, do the conversion.
1589 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1590 const llvm::Type *TruncTy = ResultTruncRegTypes[i];
Chris Lattneraab64d02010-04-23 17:27:29 +00001591
1592 // Truncate the integer result to the right size, note that TruncTy can be
1593 // a pointer.
1594 if (TruncTy->isFloatingPointTy())
1595 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00001596 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
Chris Lattneraab64d02010-04-23 17:27:29 +00001597 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
John McCalld16c2cf2011-02-08 08:22:06 +00001598 Tmp = Builder.CreateTrunc(Tmp,
1599 llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
Chris Lattnera077b5c2009-05-03 08:21:20 +00001600 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00001601 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
1602 uint64_t TmpSize =CGM.getTargetData().getTypeSizeInBits(Tmp->getType());
John McCalld16c2cf2011-02-08 08:22:06 +00001603 Tmp = Builder.CreatePtrToInt(Tmp,
1604 llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
Dan Gohman2dca88f2010-04-24 04:55:02 +00001605 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1606 } else if (TruncTy->isIntegerTy()) {
1607 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001608 } else if (TruncTy->isVectorTy()) {
1609 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001610 }
1611 }
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Chris Lattnera077b5c2009-05-03 08:21:20 +00001613 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i],
1614 ResultRegQualTys[i]);
1615 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001616}