blob: ff9021012611b781c58bda3eef44536659cd7a57 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Stmt nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
15#include "CodeGenModule.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "CodeGenFunction.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000017#include "clang/AST/StmtVisitor.h"
Chris Lattner7d22bf02009-03-05 08:04:57 +000018#include "clang/Basic/PrettyStackTrace.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000020#include "llvm/ADT/StringExtras.h"
Anders Carlsson17d28a32008-12-12 05:52:00 +000021#include "llvm/InlineAsm.h"
22#include "llvm/Intrinsics.h"
Anders Carlssonebaae2a2009-01-12 02:22:13 +000023#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25using namespace CodeGen;
26
27//===----------------------------------------------------------------------===//
28// Statement Emission
29//===----------------------------------------------------------------------===//
30
Daniel Dunbar09124252008-11-12 08:21:33 +000031void CodeGenFunction::EmitStopPoint(const Stmt *S) {
Anders Carlssone896d982009-02-13 08:11:52 +000032 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar09124252008-11-12 08:21:33 +000033 DI->setLocation(S->getLocStart());
34 DI->EmitStopPoint(CurFn, Builder);
35 }
36}
37
Reid Spencer5f016e22007-07-11 17:01:13 +000038void CodeGenFunction::EmitStmt(const Stmt *S) {
39 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000040
Daniel Dunbar09124252008-11-12 08:21:33 +000041 // Check if we can handle this without bothering to generate an
42 // insert point or debug info.
43 if (EmitSimpleStmt(S))
44 return;
45
Daniel Dunbara448fb22008-11-11 23:11:34 +000046 // If we happen to be at an unreachable point just create a dummy
47 // basic block to hold the code. We could change parts of irgen to
48 // simply not generate this code, but this situation is rare and
49 // probably not worth the effort.
50 // FIXME: Verify previous performance/effort claim.
51 EnsureInsertPoint();
Reid Spencer5f016e22007-07-11 17:01:13 +000052
Daniel Dunbar09124252008-11-12 08:21:33 +000053 // Generate a stoppoint if we are emitting debug info.
54 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000055
Reid Spencer5f016e22007-07-11 17:01:13 +000056 switch (S->getStmtClass()) {
57 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000058 // Must be an expression in a stmt context. Emit the value (to get
59 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000060 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000061 if (!hasAggregateLLVMType(E->getType()))
62 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000063 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000064 EmitComplexExpr(E);
65 else
66 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000067 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000068 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000069 }
70 break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000071 case Stmt::IndirectGotoStmtClass:
72 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000073
74 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
75 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
76 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
77 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
78
79 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
80 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +000081
Devang Patel51b09f22007-10-04 23:45:31 +000082 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000083 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000084
85 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000086 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
87 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000088 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +000089 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
90 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000091 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000092 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +000093 break;
94 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000095 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000096 break;
97 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +000098 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000099 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000100 case Stmt::ObjCForCollectionStmtClass:
101 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000102 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000103 }
104}
105
Daniel Dunbar09124252008-11-12 08:21:33 +0000106bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
107 switch (S->getStmtClass()) {
108 default: return false;
109 case Stmt::NullStmtClass: break;
110 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
111 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
112 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
113 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
114 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
115 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
116 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
117 }
118
119 return true;
120}
121
Chris Lattner33793202007-08-31 22:09:40 +0000122/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
123/// this captures the expression result of the last sub-statement and returns it
124/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000125RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
126 llvm::Value *AggLoc, bool isAggVol) {
Chris Lattner7d22bf02009-03-05 08:04:57 +0000127 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
128 "LLVM IR generation of compound statement ('{}')");
129
Anders Carlssone896d982009-02-13 08:11:52 +0000130 CGDebugInfo *DI = getDebugInfo();
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000131 if (DI) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000132 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000133 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000134 DI->EmitRegionStart(CurFn, Builder);
135 }
136
Anders Carlssonc71c8452009-02-07 23:50:39 +0000137 // Keep track of the current cleanup stack depth.
138 size_t CleanupStackDepth = CleanupEntries.size();
Anders Carlsson74331892009-02-09 20:23:40 +0000139 bool OldDidCallStackSave = DidCallStackSave;
Anders Carlsson66b41512009-02-22 18:44:21 +0000140 DidCallStackSave = false;
Anders Carlsson74331892009-02-09 20:23:40 +0000141
Chris Lattner33793202007-08-31 22:09:40 +0000142 for (CompoundStmt::const_body_iterator I = S.body_begin(),
143 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000145
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000146 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000147 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000148 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000149 DI->EmitRegionEnd(CurFn, Builder);
150 }
151
Anders Carlsson17d28a32008-12-12 05:52:00 +0000152 RValue RV;
153 if (!GetLast)
154 RV = RValue::get(0);
155 else {
156 // We have to special case labels here. They are statements, but when put
157 // at the end of a statement expression, they yield the value of their
158 // subexpression. Handle this by walking through all labels we encounter,
159 // emitting them before we evaluate the subexpr.
160 const Stmt *LastStmt = S.body_back();
161 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
162 EmitLabel(*LS);
163 LastStmt = LS->getSubStmt();
164 }
Chris Lattner9b655512007-08-31 22:49:20 +0000165
Anders Carlsson17d28a32008-12-12 05:52:00 +0000166 EnsureInsertPoint();
167
168 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
169 }
170
Anders Carlsson74331892009-02-09 20:23:40 +0000171 DidCallStackSave = OldDidCallStackSave;
172
Anders Carlssonc71c8452009-02-07 23:50:39 +0000173 EmitCleanupBlocks(CleanupStackDepth);
174
Anders Carlsson17d28a32008-12-12 05:52:00 +0000175 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000176}
177
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000178void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
179 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
180
181 // If there is a cleanup stack, then we it isn't worth trying to
182 // simplify this block (we would need to remove it from the scope map
183 // and cleanup entry).
184 if (!CleanupEntries.empty())
185 return;
186
187 // Can only simplify direct branches.
188 if (!BI || !BI->isUnconditional())
189 return;
190
191 BB->replaceAllUsesWith(BI->getSuccessor(0));
192 BI->eraseFromParent();
193 BB->eraseFromParent();
194}
195
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000196void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000197 // Fall out of the current block (if necessary).
198 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000199
200 if (IsFinished && BB->use_empty()) {
201 delete BB;
202 return;
203 }
204
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000205 // If necessary, associate the block with the cleanup stack size.
206 if (!CleanupEntries.empty()) {
Anders Carlsson22ab8d82009-02-10 22:50:24 +0000207 // Check if the basic block has already been inserted.
208 BlockScopeMap::iterator I = BlockScopes.find(BB);
209 if (I != BlockScopes.end()) {
210 assert(I->second == CleanupEntries.size() - 1);
211 } else {
212 BlockScopes[BB] = CleanupEntries.size() - 1;
213 CleanupEntries.back().Blocks.push_back(BB);
214 }
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000215 }
216
Reid Spencer5f016e22007-07-11 17:01:13 +0000217 CurFn->getBasicBlockList().push_back(BB);
218 Builder.SetInsertPoint(BB);
219}
220
Daniel Dunbard57a8712008-11-11 09:41:28 +0000221void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
222 // Emit a branch from the current block to the target one if this
223 // was a real block. If this was just a fall-through block after a
224 // terminator, don't emit it.
225 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
226
227 if (!CurBB || CurBB->getTerminator()) {
228 // If there is no insert point or the previous block is already
229 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000230 } else {
231 // Otherwise, create a fall-through branch.
232 Builder.CreateBr(Target);
233 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000234
235 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000236}
237
Mike Stumpec9771d2009-02-08 09:22:19 +0000238void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Anders Carlssonfa1f7562009-02-10 06:07:49 +0000239 EmitBlock(getBasicBlockForLabel(&S));
Chris Lattner91d723d2008-07-26 20:23:23 +0000240}
241
242
243void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
244 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000245 EmitStmt(S.getSubStmt());
246}
247
248void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000249 // If this code is reachable then emit a stop point (if generating
250 // debug info). We have to do this ourselves because we are on the
251 // "simple" statement path.
252 if (HaveInsertPoint())
253 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000254
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000255 EmitBranchThroughCleanup(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000256}
257
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000258void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
259 // Emit initial switch which will be patched up later by
260 // EmitIndirectSwitches(). We need a default dest, so we use the
261 // current BB, but this is overwritten.
262 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
263 llvm::Type::Int32Ty,
264 "addr");
265 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
266 IndirectSwitches.push_back(I);
267
Daniel Dunbara448fb22008-11-11 23:11:34 +0000268 // Clear the insertion point to indicate we are in unreachable code.
269 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000270}
271
Chris Lattner62b72f62008-11-11 07:24:28 +0000272void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000273 // C99 6.8.4.1: The first substatement is executed if the expression compares
274 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000275
Chris Lattner9bc47e22008-11-12 07:46:33 +0000276 // If the condition constant folds and can be elided, try to avoid emitting
277 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000278 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000279 // Figure out which block (then or else) is executed.
280 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000281 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000282 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000283
Chris Lattner62b72f62008-11-11 07:24:28 +0000284 // If the skipped block has no labels in it, just emit the executed block.
285 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000286 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000287 if (Executed)
288 EmitStmt(Executed);
289 return;
290 }
291 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000292
293 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
294 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000295 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
296 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
297 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000299 ElseBlock = createBasicBlock("if.else");
300 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000301
302 // Emit the 'then' code.
303 EmitBlock(ThenBlock);
304 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000305 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000306
307 // Emit the 'else' code if present.
308 if (const Stmt *Else = S.getElse()) {
309 EmitBlock(ElseBlock);
310 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000311 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 }
313
314 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000315 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000316}
317
318void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 // Emit the header for the loop, insert it, which will create an uncond br to
320 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000321 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000322 EmitBlock(LoopHeader);
Mike Stump72cac2c2009-02-07 18:08:12 +0000323
324 // Create an exit block for when the condition fails, create a block for the
325 // body of the loop.
326 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
327 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
328
329 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000330 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000331
Mike Stump16b16202009-02-07 17:18:33 +0000332 // Evaluate the conditional in the while header. C99 6.8.5.1: The
333 // evaluation of the controlling expression takes place before each
334 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000336
337 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000338 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000339 bool EmitBoolCondBranch = true;
340 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
341 if (C->isOne())
342 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000343
Reid Spencer5f016e22007-07-11 17:01:13 +0000344 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000345 if (EmitBoolCondBranch)
346 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000347
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 // Emit the loop body.
349 EmitBlock(LoopBody);
350 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000351
Anders Carlssone4b6d342009-02-10 05:52:02 +0000352 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000353
354 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000355 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000356
357 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000358 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000359
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000360 // The LoopHeader typically is just a branch if we skipped emitting
361 // a branch, try to erase it.
362 if (!EmitBoolCondBranch)
363 SimplifyForwardingBlocks(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000364}
365
366void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 // Emit the body for the loop, insert it, which will create an uncond br to
368 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000369 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
370 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000371 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000372
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000373 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattnerda138702007-07-16 21:28:45 +0000374
375 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000376 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000377
378 // Emit the body of the loop into the block.
379 EmitStmt(S.getBody());
380
Anders Carlssone4b6d342009-02-10 05:52:02 +0000381 BreakContinueStack.pop_back();
Chris Lattnerda138702007-07-16 21:28:45 +0000382
383 EmitBlock(DoCond);
384
Reid Spencer5f016e22007-07-11 17:01:13 +0000385 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
386 // after each execution of the loop body."
387
388 // Evaluate the conditional in the while header.
389 // C99 6.8.5p2/p4: The first substatement is executed if the expression
390 // compares unequal to 0. The condition must be a scalar type.
391 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000392
393 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
394 // to correctly handle break/continue though.
395 bool EmitBoolCondBranch = true;
396 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
397 if (C->isZero())
398 EmitBoolCondBranch = false;
399
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000401 if (EmitBoolCondBranch)
402 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000403
404 // Emit the exit block.
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000405 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000406
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000407 // The DoCond block typically is just a branch if we skipped
408 // emitting a branch, try to erase it.
409 if (!EmitBoolCondBranch)
410 SimplifyForwardingBlocks(DoCond);
Reid Spencer5f016e22007-07-11 17:01:13 +0000411}
412
413void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
415 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000416
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 // Evaluate the first part before the loop.
418 if (S.getInit())
419 EmitStmt(S.getInit());
420
421 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000422 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
423 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattnerda138702007-07-16 21:28:45 +0000424
Reid Spencer5f016e22007-07-11 17:01:13 +0000425 EmitBlock(CondBlock);
426
Mike Stump20926c62009-02-07 20:14:12 +0000427 // Evaluate the condition if present. If not, treat it as a
428 // non-zero-constant according to 6.8.5.3p2, aka, true.
Reid Spencer5f016e22007-07-11 17:01:13 +0000429 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000430 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000431 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner31a09842008-11-12 08:04:58 +0000432
433 // C99 6.8.5p2/p4: The first substatement is executed if the expression
434 // compares unequal to 0. The condition must be a scalar type.
435 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
436
Reid Spencer5f016e22007-07-11 17:01:13 +0000437 EmitBlock(ForBody);
438 } else {
439 // Treat it as a non-zero constant. Don't even create a new block for the
440 // body, just fall into it.
441 }
442
Chris Lattnerda138702007-07-16 21:28:45 +0000443 // If the for loop doesn't have an increment we can just use the
444 // condition as the continue block.
445 llvm::BasicBlock *ContinueBlock;
446 if (S.getInc())
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000447 ContinueBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000448 else
449 ContinueBlock = CondBlock;
450
451 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000452 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
Mike Stump3e9da662009-02-07 23:02:10 +0000453
Reid Spencer5f016e22007-07-11 17:01:13 +0000454 // If the condition is true, execute the body of the for stmt.
455 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000456
Anders Carlssone4b6d342009-02-10 05:52:02 +0000457 BreakContinueStack.pop_back();
Chris Lattnerda138702007-07-16 21:28:45 +0000458
Reid Spencer5f016e22007-07-11 17:01:13 +0000459 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000460 if (S.getInc()) {
461 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000462 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000463 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000464
465 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000466 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000467
Chris Lattnerda138702007-07-16 21:28:45 +0000468 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000469 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000470}
471
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000472void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
473 if (RV.isScalar()) {
474 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
475 } else if (RV.isAggregate()) {
476 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
477 } else {
478 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
479 }
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000480 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000481}
482
Reid Spencer5f016e22007-07-11 17:01:13 +0000483/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
484/// if the function returns void, or may be missing one if the function returns
485/// non-void. Fun stuff :).
486void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000487 // Emit the result value, even if unused, to evalute the side effects.
488 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000489
490 // FIXME: Clean this up by using an LValue for ReturnTemp,
491 // EmitStoreThroughLValue, and EmitAnyExpr.
492 if (!ReturnValue) {
493 // Make sure not to return anything, but evaluate the expression
494 // for side effects.
495 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000496 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000497 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000498 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000499 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000500 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000501 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000502 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000503 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000504 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 }
Eli Friedman144ac612008-05-22 01:22:33 +0000506
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000507 EmitBranchThroughCleanup(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000508}
509
510void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000511 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
512 I != E; ++I)
513 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000514}
Chris Lattnerda138702007-07-16 21:28:45 +0000515
Daniel Dunbar09124252008-11-12 08:21:33 +0000516void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000517 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
518
Daniel Dunbar09124252008-11-12 08:21:33 +0000519 // If this code is reachable then emit a stop point (if generating
520 // debug info). We have to do this ourselves because we are on the
521 // "simple" statement path.
522 if (HaveInsertPoint())
523 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000524
Chris Lattnerda138702007-07-16 21:28:45 +0000525 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000526 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000527}
528
Daniel Dunbar09124252008-11-12 08:21:33 +0000529void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000530 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
531
Daniel Dunbar09124252008-11-12 08:21:33 +0000532 // If this code is reachable then emit a stop point (if generating
533 // debug info). We have to do this ourselves because we are on the
534 // "simple" statement path.
535 if (HaveInsertPoint())
536 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000537
Chris Lattnerda138702007-07-16 21:28:45 +0000538 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000539 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000540}
Devang Patel51b09f22007-10-04 23:45:31 +0000541
Devang Patelc049e4f2007-10-08 20:57:48 +0000542/// EmitCaseStmtRange - If case statement range is not too big then
543/// add multiple cases to switch instruction, one for each value within
544/// the range. If range is too big then emit "if" condition check.
545void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000546 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000547
Anders Carlsson51fe9962008-11-22 21:04:56 +0000548 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
549 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000550
Daniel Dunbar16f23572008-07-25 01:11:38 +0000551 // Emit the code for this case. We do this first to make sure it is
552 // properly chained from our predecessor before generating the
553 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000554 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000555 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
556 EmitStmt(S.getSubStmt());
557
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000558 // If range is empty, do nothing.
559 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
560 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000561
562 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000563 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000564 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
565 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000566 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000567 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
568 LHS++;
569 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000570 return;
571 }
572
Daniel Dunbar16f23572008-07-25 01:11:38 +0000573 // The range is too big. Emit "if" condition into a new block,
574 // making sure to save and restore the current insertion point.
575 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000576
Daniel Dunbar16f23572008-07-25 01:11:38 +0000577 // Push this test onto the chain of range checks (which terminates
578 // in the default basic block). The switch's default will be changed
579 // to the top of this chain after switch emission is complete.
580 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000581 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000582
Daniel Dunbar16f23572008-07-25 01:11:38 +0000583 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
584 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000585
586 // Emit range check.
587 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000588 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
589 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000590 llvm::Value *Cond =
591 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
592 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
593
Daniel Dunbar16f23572008-07-25 01:11:38 +0000594 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000595 if (RestoreBB)
596 Builder.SetInsertPoint(RestoreBB);
597 else
598 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000599}
600
601void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
602 if (S.getRHS()) {
603 EmitCaseStmtRange(S);
604 return;
605 }
606
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000607 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000608 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000609 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000610 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Chris Lattner5512f282009-03-04 04:46:18 +0000611
612 // Recursively emitting the statement is acceptable, but is not wonderful for
613 // code where we have many case statements nested together, i.e.:
614 // case 1:
615 // case 2:
616 // case 3: etc.
617 // Handling this recursively will create a new block for each case statement
618 // that falls through to the next case which is IR intensive. It also causes
619 // deep recursion which can run into stack depth limitations. Handle
620 // sequential non-range case statements specially.
621 const CaseStmt *CurCase = &S;
622 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
623
624 // Otherwise, iteratively add consequtive cases to this switch stmt.
625 while (NextCase && NextCase->getRHS() == 0) {
626 CurCase = NextCase;
627 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
628 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
629
630 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
631 }
632
633 // Normal default recursion for non-cases.
634 EmitStmt(CurCase->getSubStmt());
Devang Patel51b09f22007-10-04 23:45:31 +0000635}
636
637void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000638 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000639 assert(DefaultBlock->empty() &&
640 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000641 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000642 EmitStmt(S.getSubStmt());
643}
644
645void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
646 llvm::Value *CondV = EmitScalarExpr(S.getCond());
647
648 // Handle nested switch statements.
649 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000650 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000651
Daniel Dunbar16f23572008-07-25 01:11:38 +0000652 // Create basic block to hold stuff that comes after switch
653 // statement. We also need to create a default block now so that
654 // explicit case ranges tests can have a place to jump to on
655 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000656 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
657 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000658 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
659 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000660
Daniel Dunbar09124252008-11-12 08:21:33 +0000661 // Clear the insertion point to indicate we are in unreachable code.
662 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000663
Devang Patele9b8c0a2007-10-30 20:59:40 +0000664 // All break statements jump to NextBlock. If BreakContinueStack is non empty
665 // then reuse last ContinueBlock.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000666 llvm::BasicBlock *ContinueBlock = 0;
667 if (!BreakContinueStack.empty())
Devang Patel51b09f22007-10-04 23:45:31 +0000668 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000669
Mike Stump3e9da662009-02-07 23:02:10 +0000670 // Ensure any vlas created between there and here, are undone
Anders Carlssone4b6d342009-02-10 05:52:02 +0000671 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
Devang Patel51b09f22007-10-04 23:45:31 +0000672
673 // Emit switch body.
674 EmitStmt(S.getBody());
Anders Carlssone4b6d342009-02-10 05:52:02 +0000675
676 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +0000677
Daniel Dunbar16f23572008-07-25 01:11:38 +0000678 // Update the default block in case explicit case range tests have
679 // been chained on top.
680 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000681
Daniel Dunbar16f23572008-07-25 01:11:38 +0000682 // If a default was never emitted then reroute any jumps to it and
683 // discard.
684 if (!DefaultBlock->getParent()) {
685 DefaultBlock->replaceAllUsesWith(NextBlock);
686 delete DefaultBlock;
687 }
Devang Patel51b09f22007-10-04 23:45:31 +0000688
Daniel Dunbar16f23572008-07-25 01:11:38 +0000689 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000690 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000691
Devang Patel51b09f22007-10-04 23:45:31 +0000692 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000693 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000694}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000695
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000696static std::string SimplifyConstraint(const char* Constraint,
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000697 TargetInfo &Target,
698 const std::string *OutputNamesBegin = 0,
Chris Lattner63c8b142009-03-10 05:39:21 +0000699 const std::string *OutputNamesEnd = 0) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000700 std::string Result;
701
702 while (*Constraint) {
703 switch (*Constraint) {
704 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000705 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000706 break;
707 // Ignore these
708 case '*':
709 case '?':
710 case '!':
711 break;
712 case 'g':
713 Result += "imr";
714 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000715 case '[': {
716 assert(OutputNamesBegin && OutputNamesEnd &&
717 "Must pass output names to constraints with a symbolic name");
718 unsigned Index;
719 bool result = Target.resolveSymbolicName(Constraint,
720 OutputNamesBegin,
721 OutputNamesEnd, Index);
Chris Lattner53637652009-01-21 07:35:26 +0000722 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000723 Result += llvm::utostr(Index);
724 break;
725 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000726 }
727
728 Constraint++;
729 }
730
731 return Result;
732}
733
Anders Carlsson63471722009-01-11 19:32:54 +0000734llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
735 TargetInfo::ConstraintInfo Info,
736 const Expr *InputExpr,
Chris Lattner63c8b142009-03-10 05:39:21 +0000737 std::string &ConstraintStr) {
Anders Carlsson63471722009-01-11 19:32:54 +0000738 llvm::Value *Arg;
739 if ((Info & TargetInfo::CI_AllowsRegister) ||
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000740 !(Info & TargetInfo::CI_AllowsMemory)) {
741 const llvm::Type *Ty = ConvertType(InputExpr->getType());
742
743 if (Ty->isSingleValueType()) {
Anders Carlsson63471722009-01-11 19:32:54 +0000744 Arg = EmitScalarExpr(InputExpr);
745 } else {
Chris Lattner810f6d52009-03-13 17:38:01 +0000746 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000747 LValue Dest = EmitLValue(InputExpr);
748
749 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
750 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
751 Ty = llvm::IntegerType::get(Size);
752 Ty = llvm::PointerType::getUnqual(Ty);
753
754 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
755 } else {
756 Arg = Dest.getAddress();
757 ConstraintStr += '*';
758 }
Anders Carlsson63471722009-01-11 19:32:54 +0000759 }
760 } else {
Chris Lattner810f6d52009-03-13 17:38:01 +0000761 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
Anders Carlsson63471722009-01-11 19:32:54 +0000762 LValue Dest = EmitLValue(InputExpr);
763 Arg = Dest.getAddress();
764 ConstraintStr += '*';
765 }
766
767 return Arg;
768}
769
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000770void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Chris Lattner458cd9c2009-03-10 23:21:44 +0000771 // Analyze the asm string to decompose it into its pieces. We know that Sema
772 // has already done this, so it is guaranteed to be successful.
773 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +0000774 unsigned DiagOffs;
775 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
Chris Lattner458cd9c2009-03-10 23:21:44 +0000776
777 // Assemble the pieces into the final asm string.
778 std::string AsmString;
779 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
780 if (Pieces[i].isString())
781 AsmString += Pieces[i].getString();
782 else if (Pieces[i].getModifier() == '\0')
783 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
784 else
785 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
786 Pieces[i].getModifier() + '}';
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000787 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000788
789 std::string Constraints;
790
791 llvm::Value *ResultAddr = 0;
792 const llvm::Type *ResultType = llvm::Type::VoidTy;
793
794 std::vector<const llvm::Type*> ArgTypes;
795 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000796
797 // Keep track of inout constraints.
798 std::string InOutConstraints;
799 std::vector<llvm::Value*> InOutArgs;
800 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +0000801
802 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
803
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000804 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattnerb3277932009-03-10 04:59:06 +0000805 std::string OutputConstraint(S.getOutputConstraint(i));
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000806
807 TargetInfo::ConstraintInfo Info;
808 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
809 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000810 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000811
Anders Carlsson03eb5432009-01-27 20:38:24 +0000812 OutputConstraintInfos.push_back(Info);
813
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000814 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000815 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000816
Chris Lattner810f6d52009-03-13 17:38:01 +0000817 const Expr *OutExpr = S.getOutputExpr(i);
818 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
819
820 LValue Dest = EmitLValue(OutExpr);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000821 const llvm::Type *DestValueType =
822 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
823
824 // If the first output operand is not a memory dest, we'll
825 // make it the return value.
826 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000827 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000828 ResultAddr = Dest.getAddress();
829 ResultType = DestValueType;
830 Constraints += "=" + OutputConstraint;
831 } else {
832 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000833 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000834 if (i != 0)
835 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000836 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000837 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000838 }
839
840 if (Info & TargetInfo::CI_ReadWrite) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000841 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +0000842
Anders Carlssonf39a4212008-02-05 20:01:53 +0000843 const Expr *InputExpr = S.getOutputExpr(i);
Anders Carlsson63471722009-01-11 19:32:54 +0000844 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Anders Carlssonf39a4212008-02-05 20:01:53 +0000845
Anders Carlsson9f2505b2009-01-11 21:23:27 +0000846 if (Info & TargetInfo::CI_AllowsRegister)
847 InOutConstraints += llvm::utostr(i);
848 else
849 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +0000850
Anders Carlssonf39a4212008-02-05 20:01:53 +0000851 InOutArgTypes.push_back(Arg->getType());
852 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +0000853 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000854 }
855
856 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
857
858 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
859 const Expr *InputExpr = S.getInputExpr(i);
860
Chris Lattnerb3277932009-03-10 04:59:06 +0000861 std::string InputConstraint(S.getInputConstraint(i));
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000862
863 TargetInfo::ConstraintInfo Info;
864 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Anders Carlsson45b050e2009-01-17 23:36:15 +0000865 S.begin_output_names(),
866 S.end_output_names(),
Anders Carlsson03eb5432009-01-27 20:38:24 +0000867 &OutputConstraintInfos[0],
Chris Lattner53637652009-01-21 07:35:26 +0000868 Info); result=result;
Anders Carlsson42e1ee02009-01-18 01:56:57 +0000869 assert(result && "Failed to parse input constraint");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000870
871 if (i != 0 || S.getNumOutputs() > 0)
872 Constraints += ',';
873
874 // Simplify the input constraint.
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000875 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
876 S.begin_output_names(),
877 S.end_output_names());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000878
Anders Carlsson63471722009-01-11 19:32:54 +0000879 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000880
881 ArgTypes.push_back(Arg->getType());
882 Args.push_back(Arg);
883 Constraints += InputConstraint;
884 }
885
Anders Carlssonf39a4212008-02-05 20:01:53 +0000886 // Append the "input" part of inout constraints last.
887 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
888 ArgTypes.push_back(InOutArgTypes[i]);
889 Args.push_back(InOutArgs[i]);
890 }
891 Constraints += InOutConstraints;
892
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000893 // Clobbers
894 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
895 std::string Clobber(S.getClobber(i)->getStrData(),
896 S.getClobber(i)->getByteLength());
897
898 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
899
Anders Carlssonea041752008-02-06 00:11:32 +0000900 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000901 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000902
903 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000904 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000905 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000906 }
907
908 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +0000909 std::string MachineClobbers = Target.getClobbers();
910 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000911 if (!Constraints.empty())
912 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +0000913 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000914 }
Anders Carlssonf39a4212008-02-05 20:01:53 +0000915
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000916 const llvm::FunctionType *FTy =
917 llvm::FunctionType::get(ResultType, ArgTypes, false);
918
919 llvm::InlineAsm *IA =
920 llvm::InlineAsm::get(FTy, AsmString, Constraints,
921 S.isVolatile() || S.getNumOutputs() == 0);
Anders Carlssonbc0822b2009-03-02 19:58:15 +0000922 llvm::CallInst *Result
923 = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
924 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
925
Eli Friedman1e692ac2008-06-13 23:01:12 +0000926 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000927 Builder.CreateStore(Result, ResultAddr);
928}