blob: 0e9cec42c81f5e4f32c6b456209667fabef3f0dc [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)) {
Eli Friedman8a3e0b12009-04-13 21:41:57 +000061 EmitAnyExpr(E);
Reid Spencer5f016e22007-07-11 17:01:13 +000062 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000063 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000064 }
65 break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000066 case Stmt::IndirectGotoStmtClass:
67 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000068
69 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
70 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
71 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
72 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
73
74 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
75 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +000076
Devang Patel51b09f22007-10-04 23:45:31 +000077 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000078 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000079
80 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000081 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
82 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000083 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +000084 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
85 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000086 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000087 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +000088 break;
89 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000090 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000091 break;
92 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +000093 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000094 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +000095 case Stmt::ObjCForCollectionStmtClass:
96 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000097 break;
Reid Spencer5f016e22007-07-11 17:01:13 +000098 }
99}
100
Daniel Dunbar09124252008-11-12 08:21:33 +0000101bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
102 switch (S->getStmtClass()) {
103 default: return false;
104 case Stmt::NullStmtClass: break;
105 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
106 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
107 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
108 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
109 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
110 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
111 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
112 }
113
114 return true;
115}
116
Chris Lattner33793202007-08-31 22:09:40 +0000117/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
118/// this captures the expression result of the last sub-statement and returns it
119/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000120RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
121 llvm::Value *AggLoc, bool isAggVol) {
Chris Lattner7d22bf02009-03-05 08:04:57 +0000122 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
123 "LLVM IR generation of compound statement ('{}')");
124
Anders Carlssone896d982009-02-13 08:11:52 +0000125 CGDebugInfo *DI = getDebugInfo();
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000126 if (DI) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000127 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000128 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000129 DI->EmitRegionStart(CurFn, Builder);
130 }
131
Anders Carlssonc71c8452009-02-07 23:50:39 +0000132 // Keep track of the current cleanup stack depth.
133 size_t CleanupStackDepth = CleanupEntries.size();
Anders Carlsson74331892009-02-09 20:23:40 +0000134 bool OldDidCallStackSave = DidCallStackSave;
Anders Carlsson66b41512009-02-22 18:44:21 +0000135 DidCallStackSave = false;
Anders Carlsson74331892009-02-09 20:23:40 +0000136
Chris Lattner33793202007-08-31 22:09:40 +0000137 for (CompoundStmt::const_body_iterator I = S.body_begin(),
138 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000139 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000140
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000141 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000142 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000143 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000144 DI->EmitRegionEnd(CurFn, Builder);
145 }
146
Anders Carlsson17d28a32008-12-12 05:52:00 +0000147 RValue RV;
148 if (!GetLast)
149 RV = RValue::get(0);
150 else {
151 // We have to special case labels here. They are statements, but when put
152 // at the end of a statement expression, they yield the value of their
153 // subexpression. Handle this by walking through all labels we encounter,
154 // emitting them before we evaluate the subexpr.
155 const Stmt *LastStmt = S.body_back();
156 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
157 EmitLabel(*LS);
158 LastStmt = LS->getSubStmt();
159 }
Chris Lattner9b655512007-08-31 22:49:20 +0000160
Anders Carlsson17d28a32008-12-12 05:52:00 +0000161 EnsureInsertPoint();
162
163 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
164 }
165
Anders Carlsson74331892009-02-09 20:23:40 +0000166 DidCallStackSave = OldDidCallStackSave;
167
Anders Carlssonc71c8452009-02-07 23:50:39 +0000168 EmitCleanupBlocks(CleanupStackDepth);
169
Anders Carlsson17d28a32008-12-12 05:52:00 +0000170 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000171}
172
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000173void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
174 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
175
176 // If there is a cleanup stack, then we it isn't worth trying to
177 // simplify this block (we would need to remove it from the scope map
178 // and cleanup entry).
179 if (!CleanupEntries.empty())
180 return;
181
182 // Can only simplify direct branches.
183 if (!BI || !BI->isUnconditional())
184 return;
185
186 BB->replaceAllUsesWith(BI->getSuccessor(0));
187 BI->eraseFromParent();
188 BB->eraseFromParent();
189}
190
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000191void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000192 // Fall out of the current block (if necessary).
193 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000194
195 if (IsFinished && BB->use_empty()) {
196 delete BB;
197 return;
198 }
199
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000200 // If necessary, associate the block with the cleanup stack size.
201 if (!CleanupEntries.empty()) {
Anders Carlsson22ab8d82009-02-10 22:50:24 +0000202 // Check if the basic block has already been inserted.
203 BlockScopeMap::iterator I = BlockScopes.find(BB);
204 if (I != BlockScopes.end()) {
205 assert(I->second == CleanupEntries.size() - 1);
206 } else {
207 BlockScopes[BB] = CleanupEntries.size() - 1;
208 CleanupEntries.back().Blocks.push_back(BB);
209 }
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000210 }
211
Reid Spencer5f016e22007-07-11 17:01:13 +0000212 CurFn->getBasicBlockList().push_back(BB);
213 Builder.SetInsertPoint(BB);
214}
215
Daniel Dunbard57a8712008-11-11 09:41:28 +0000216void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
217 // Emit a branch from the current block to the target one if this
218 // was a real block. If this was just a fall-through block after a
219 // terminator, don't emit it.
220 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
221
222 if (!CurBB || CurBB->getTerminator()) {
223 // If there is no insert point or the previous block is already
224 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000225 } else {
226 // Otherwise, create a fall-through branch.
227 Builder.CreateBr(Target);
228 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000229
230 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000231}
232
Mike Stumpec9771d2009-02-08 09:22:19 +0000233void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Anders Carlssonfa1f7562009-02-10 06:07:49 +0000234 EmitBlock(getBasicBlockForLabel(&S));
Chris Lattner91d723d2008-07-26 20:23:23 +0000235}
236
237
238void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
239 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000240 EmitStmt(S.getSubStmt());
241}
242
243void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000244 // If this code is reachable then emit a stop point (if generating
245 // debug info). We have to do this ourselves because we are on the
246 // "simple" statement path.
247 if (HaveInsertPoint())
248 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000249
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000250 EmitBranchThroughCleanup(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000251}
252
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000253void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
254 // Emit initial switch which will be patched up later by
255 // EmitIndirectSwitches(). We need a default dest, so we use the
256 // current BB, but this is overwritten.
257 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
258 llvm::Type::Int32Ty,
259 "addr");
260 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
261 IndirectSwitches.push_back(I);
262
Daniel Dunbara448fb22008-11-11 23:11:34 +0000263 // Clear the insertion point to indicate we are in unreachable code.
264 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000265}
266
Chris Lattner62b72f62008-11-11 07:24:28 +0000267void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000268 // C99 6.8.4.1: The first substatement is executed if the expression compares
269 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000270
Chris Lattner9bc47e22008-11-12 07:46:33 +0000271 // If the condition constant folds and can be elided, try to avoid emitting
272 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000273 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000274 // Figure out which block (then or else) is executed.
275 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000276 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000277 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000278
Chris Lattner62b72f62008-11-11 07:24:28 +0000279 // If the skipped block has no labels in it, just emit the executed block.
280 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000281 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000282 if (Executed)
283 EmitStmt(Executed);
284 return;
285 }
286 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000287
288 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
289 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000290 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
291 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
292 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000294 ElseBlock = createBasicBlock("if.else");
295 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000296
297 // Emit the 'then' code.
298 EmitBlock(ThenBlock);
299 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000300 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000301
302 // Emit the 'else' code if present.
303 if (const Stmt *Else = S.getElse()) {
304 EmitBlock(ElseBlock);
305 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000306 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000307 }
308
309 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000310 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000311}
312
313void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000314 // Emit the header for the loop, insert it, which will create an uncond br to
315 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000316 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000317 EmitBlock(LoopHeader);
Mike Stump72cac2c2009-02-07 18:08:12 +0000318
319 // Create an exit block for when the condition fails, create a block for the
320 // body of the loop.
321 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
322 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
323
324 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000325 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000326
Mike Stump16b16202009-02-07 17:18:33 +0000327 // Evaluate the conditional in the while header. C99 6.8.5.1: The
328 // evaluation of the controlling expression takes place before each
329 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000330 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000331
332 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000334 bool EmitBoolCondBranch = true;
335 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
336 if (C->isOne())
337 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000338
Reid Spencer5f016e22007-07-11 17:01:13 +0000339 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000340 if (EmitBoolCondBranch)
341 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000342
Reid Spencer5f016e22007-07-11 17:01:13 +0000343 // Emit the loop body.
344 EmitBlock(LoopBody);
345 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000346
Anders Carlssone4b6d342009-02-10 05:52:02 +0000347 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000348
349 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000350 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000351
352 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000353 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000354
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000355 // The LoopHeader typically is just a branch if we skipped emitting
356 // a branch, try to erase it.
357 if (!EmitBoolCondBranch)
358 SimplifyForwardingBlocks(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000359}
360
361void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 // Emit the body for the loop, insert it, which will create an uncond br to
363 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000364 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
365 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000366 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000367
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000368 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattnerda138702007-07-16 21:28:45 +0000369
370 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000371 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000372
373 // Emit the body of the loop into the block.
374 EmitStmt(S.getBody());
375
Anders Carlssone4b6d342009-02-10 05:52:02 +0000376 BreakContinueStack.pop_back();
Chris Lattnerda138702007-07-16 21:28:45 +0000377
378 EmitBlock(DoCond);
379
Reid Spencer5f016e22007-07-11 17:01:13 +0000380 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
381 // after each execution of the loop body."
382
383 // Evaluate the conditional in the while header.
384 // C99 6.8.5p2/p4: The first substatement is executed if the expression
385 // compares unequal to 0. The condition must be a scalar type.
386 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000387
388 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
389 // to correctly handle break/continue though.
390 bool EmitBoolCondBranch = true;
391 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
392 if (C->isZero())
393 EmitBoolCondBranch = false;
394
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000396 if (EmitBoolCondBranch)
397 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000398
399 // Emit the exit block.
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000400 EmitBlock(AfterDo);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000401
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000402 // The DoCond block typically is just a branch if we skipped
403 // emitting a branch, try to erase it.
404 if (!EmitBoolCondBranch)
405 SimplifyForwardingBlocks(DoCond);
Reid Spencer5f016e22007-07-11 17:01:13 +0000406}
407
408void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
410 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000411
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 // Evaluate the first part before the loop.
413 if (S.getInit())
414 EmitStmt(S.getInit());
415
416 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000417 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
418 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattnerda138702007-07-16 21:28:45 +0000419
Reid Spencer5f016e22007-07-11 17:01:13 +0000420 EmitBlock(CondBlock);
421
Mike Stump20926c62009-02-07 20:14:12 +0000422 // Evaluate the condition if present. If not, treat it as a
423 // non-zero-constant according to 6.8.5.3p2, aka, true.
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000425 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000426 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner31a09842008-11-12 08:04:58 +0000427
428 // C99 6.8.5p2/p4: The first substatement is executed if the expression
429 // compares unequal to 0. The condition must be a scalar type.
430 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
431
Reid Spencer5f016e22007-07-11 17:01:13 +0000432 EmitBlock(ForBody);
433 } else {
434 // Treat it as a non-zero constant. Don't even create a new block for the
435 // body, just fall into it.
436 }
437
Chris Lattnerda138702007-07-16 21:28:45 +0000438 // If the for loop doesn't have an increment we can just use the
439 // condition as the continue block.
440 llvm::BasicBlock *ContinueBlock;
441 if (S.getInc())
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000442 ContinueBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000443 else
444 ContinueBlock = CondBlock;
445
446 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000447 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
Mike Stump3e9da662009-02-07 23:02:10 +0000448
Reid Spencer5f016e22007-07-11 17:01:13 +0000449 // If the condition is true, execute the body of the for stmt.
450 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000451
Anders Carlssone4b6d342009-02-10 05:52:02 +0000452 BreakContinueStack.pop_back();
Chris Lattnerda138702007-07-16 21:28:45 +0000453
Reid Spencer5f016e22007-07-11 17:01:13 +0000454 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000455 if (S.getInc()) {
456 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000457 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000458 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000459
460 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000461 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000462
Chris Lattnerda138702007-07-16 21:28:45 +0000463 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000464 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000465}
466
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000467void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
468 if (RV.isScalar()) {
469 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
470 } else if (RV.isAggregate()) {
471 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
472 } else {
473 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
474 }
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000475 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000476}
477
Reid Spencer5f016e22007-07-11 17:01:13 +0000478/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
479/// if the function returns void, or may be missing one if the function returns
480/// non-void. Fun stuff :).
481void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000482 // Emit the result value, even if unused, to evalute the side effects.
483 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000484
485 // FIXME: Clean this up by using an LValue for ReturnTemp,
486 // EmitStoreThroughLValue, and EmitAnyExpr.
487 if (!ReturnValue) {
488 // Make sure not to return anything, but evaluate the expression
489 // for side effects.
490 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000491 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000493 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000494 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000495 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000496 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000497 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000498 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000499 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 }
Eli Friedman144ac612008-05-22 01:22:33 +0000501
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000502 EmitBranchThroughCleanup(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000503}
504
505void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000506 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
507 I != E; ++I)
508 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000509}
Chris Lattnerda138702007-07-16 21:28:45 +0000510
Daniel Dunbar09124252008-11-12 08:21:33 +0000511void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000512 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
513
Daniel Dunbar09124252008-11-12 08:21:33 +0000514 // If this code is reachable then emit a stop point (if generating
515 // debug info). We have to do this ourselves because we are on the
516 // "simple" statement path.
517 if (HaveInsertPoint())
518 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000519
Chris Lattnerda138702007-07-16 21:28:45 +0000520 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000521 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000522}
523
Daniel Dunbar09124252008-11-12 08:21:33 +0000524void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000525 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
526
Daniel Dunbar09124252008-11-12 08:21:33 +0000527 // If this code is reachable then emit a stop point (if generating
528 // debug info). We have to do this ourselves because we are on the
529 // "simple" statement path.
530 if (HaveInsertPoint())
531 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000532
Chris Lattnerda138702007-07-16 21:28:45 +0000533 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000534 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000535}
Devang Patel51b09f22007-10-04 23:45:31 +0000536
Devang Patelc049e4f2007-10-08 20:57:48 +0000537/// EmitCaseStmtRange - If case statement range is not too big then
538/// add multiple cases to switch instruction, one for each value within
539/// the range. If range is too big then emit "if" condition check.
540void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000541 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000542
Anders Carlsson51fe9962008-11-22 21:04:56 +0000543 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
544 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000545
Daniel Dunbar16f23572008-07-25 01:11:38 +0000546 // Emit the code for this case. We do this first to make sure it is
547 // properly chained from our predecessor before generating the
548 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000549 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000550 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
551 EmitStmt(S.getSubStmt());
552
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000553 // If range is empty, do nothing.
554 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
555 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000556
557 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000558 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000559 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
560 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000561 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000562 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
563 LHS++;
564 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000565 return;
566 }
567
Daniel Dunbar16f23572008-07-25 01:11:38 +0000568 // The range is too big. Emit "if" condition into a new block,
569 // making sure to save and restore the current insertion point.
570 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000571
Daniel Dunbar16f23572008-07-25 01:11:38 +0000572 // Push this test onto the chain of range checks (which terminates
573 // in the default basic block). The switch's default will be changed
574 // to the top of this chain after switch emission is complete.
575 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000576 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000577
Daniel Dunbar16f23572008-07-25 01:11:38 +0000578 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
579 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000580
581 // Emit range check.
582 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000583 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
584 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000585 llvm::Value *Cond =
586 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
587 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
588
Daniel Dunbar16f23572008-07-25 01:11:38 +0000589 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000590 if (RestoreBB)
591 Builder.SetInsertPoint(RestoreBB);
592 else
593 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000594}
595
596void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
597 if (S.getRHS()) {
598 EmitCaseStmtRange(S);
599 return;
600 }
601
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000602 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000603 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000604 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000605 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Chris Lattner5512f282009-03-04 04:46:18 +0000606
607 // Recursively emitting the statement is acceptable, but is not wonderful for
608 // code where we have many case statements nested together, i.e.:
609 // case 1:
610 // case 2:
611 // case 3: etc.
612 // Handling this recursively will create a new block for each case statement
613 // that falls through to the next case which is IR intensive. It also causes
614 // deep recursion which can run into stack depth limitations. Handle
615 // sequential non-range case statements specially.
616 const CaseStmt *CurCase = &S;
617 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
618
619 // Otherwise, iteratively add consequtive cases to this switch stmt.
620 while (NextCase && NextCase->getRHS() == 0) {
621 CurCase = NextCase;
622 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
623 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
624
625 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
626 }
627
628 // Normal default recursion for non-cases.
629 EmitStmt(CurCase->getSubStmt());
Devang Patel51b09f22007-10-04 23:45:31 +0000630}
631
632void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000633 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000634 assert(DefaultBlock->empty() &&
635 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000636 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000637 EmitStmt(S.getSubStmt());
638}
639
640void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
641 llvm::Value *CondV = EmitScalarExpr(S.getCond());
642
643 // Handle nested switch statements.
644 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000645 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000646
Daniel Dunbar16f23572008-07-25 01:11:38 +0000647 // Create basic block to hold stuff that comes after switch
648 // statement. We also need to create a default block now so that
649 // explicit case ranges tests can have a place to jump to on
650 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000651 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
652 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000653 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
654 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000655
Daniel Dunbar09124252008-11-12 08:21:33 +0000656 // Clear the insertion point to indicate we are in unreachable code.
657 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000658
Devang Patele9b8c0a2007-10-30 20:59:40 +0000659 // All break statements jump to NextBlock. If BreakContinueStack is non empty
660 // then reuse last ContinueBlock.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000661 llvm::BasicBlock *ContinueBlock = 0;
662 if (!BreakContinueStack.empty())
Devang Patel51b09f22007-10-04 23:45:31 +0000663 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000664
Mike Stump3e9da662009-02-07 23:02:10 +0000665 // Ensure any vlas created between there and here, are undone
Anders Carlssone4b6d342009-02-10 05:52:02 +0000666 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
Devang Patel51b09f22007-10-04 23:45:31 +0000667
668 // Emit switch body.
669 EmitStmt(S.getBody());
Anders Carlssone4b6d342009-02-10 05:52:02 +0000670
671 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +0000672
Daniel Dunbar16f23572008-07-25 01:11:38 +0000673 // Update the default block in case explicit case range tests have
674 // been chained on top.
675 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000676
Daniel Dunbar16f23572008-07-25 01:11:38 +0000677 // If a default was never emitted then reroute any jumps to it and
678 // discard.
679 if (!DefaultBlock->getParent()) {
680 DefaultBlock->replaceAllUsesWith(NextBlock);
681 delete DefaultBlock;
682 }
Devang Patel51b09f22007-10-04 23:45:31 +0000683
Daniel Dunbar16f23572008-07-25 01:11:38 +0000684 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000685 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000686
Devang Patel51b09f22007-10-04 23:45:31 +0000687 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000688 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000689}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000690
Chris Lattner2819fa82009-04-26 17:57:12 +0000691static std::string
692SimplifyConstraint(const char *Constraint, TargetInfo &Target,
693 llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000694 std::string Result;
695
696 while (*Constraint) {
697 switch (*Constraint) {
698 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000699 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000700 break;
701 // Ignore these
702 case '*':
703 case '?':
704 case '!':
705 break;
706 case 'g':
707 Result += "imr";
708 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000709 case '[': {
Chris Lattner2819fa82009-04-26 17:57:12 +0000710 assert(OutCons &&
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000711 "Must pass output names to constraints with a symbolic name");
712 unsigned Index;
713 bool result = Target.resolveSymbolicName(Constraint,
Chris Lattner2819fa82009-04-26 17:57:12 +0000714 &(*OutCons)[0],
715 OutCons->size(), Index);
Chris Lattner53637652009-01-21 07:35:26 +0000716 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000717 Result += llvm::utostr(Index);
718 break;
719 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000720 }
721
722 Constraint++;
723 }
724
725 return Result;
726}
727
Anders Carlsson63471722009-01-11 19:32:54 +0000728llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
729 TargetInfo::ConstraintInfo Info,
730 const Expr *InputExpr,
Chris Lattner63c8b142009-03-10 05:39:21 +0000731 std::string &ConstraintStr) {
Anders Carlsson63471722009-01-11 19:32:54 +0000732 llvm::Value *Arg;
Chris Lattner44def072009-04-26 07:16:29 +0000733 if (Info.allowsRegister() || !Info.allowsMemory()) {
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000734 const llvm::Type *Ty = ConvertType(InputExpr->getType());
735
736 if (Ty->isSingleValueType()) {
Anders Carlsson63471722009-01-11 19:32:54 +0000737 Arg = EmitScalarExpr(InputExpr);
738 } else {
Chris Lattner810f6d52009-03-13 17:38:01 +0000739 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000740 LValue Dest = EmitLValue(InputExpr);
741
742 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
743 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
744 Ty = llvm::IntegerType::get(Size);
745 Ty = llvm::PointerType::getUnqual(Ty);
746
747 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
748 } else {
749 Arg = Dest.getAddress();
750 ConstraintStr += '*';
751 }
Anders Carlsson63471722009-01-11 19:32:54 +0000752 }
753 } else {
Chris Lattner810f6d52009-03-13 17:38:01 +0000754 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
Anders Carlsson63471722009-01-11 19:32:54 +0000755 LValue Dest = EmitLValue(InputExpr);
756 Arg = Dest.getAddress();
757 ConstraintStr += '*';
758 }
759
760 return Arg;
761}
762
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000763void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Chris Lattner458cd9c2009-03-10 23:21:44 +0000764 // Analyze the asm string to decompose it into its pieces. We know that Sema
765 // has already done this, so it is guaranteed to be successful.
766 llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
Chris Lattnerfb5058e2009-03-10 23:41:04 +0000767 unsigned DiagOffs;
768 S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
Chris Lattner458cd9c2009-03-10 23:21:44 +0000769
770 // Assemble the pieces into the final asm string.
771 std::string AsmString;
772 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
773 if (Pieces[i].isString())
774 AsmString += Pieces[i].getString();
775 else if (Pieces[i].getModifier() == '\0')
776 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
777 else
778 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
779 Pieces[i].getModifier() + '}';
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000780 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000781
Chris Lattner481fef92009-05-03 07:05:00 +0000782 // Get all the output and input constraints together.
783 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
784 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
785
786 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
787 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
788 S.getOutputName(i));
789 bool result = Target.validateOutputConstraint(Info);
790 assert(result && "Failed to parse output constraint"); result=result;
791 OutputConstraintInfos.push_back(Info);
792 }
793
794 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
795 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
796 S.getInputName(i));
797 bool result = Target.validateInputConstraint(&OutputConstraintInfos[0],
798 S.getNumOutputs(),
799 Info); result=result;
800 assert(result && "Failed to parse input constraint");
801 InputConstraintInfos.push_back(Info);
802 }
803
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000804 std::string Constraints;
805
Chris Lattnerede9d902009-05-03 07:53:25 +0000806 std::vector<LValue> ResultRegDests;
807 std::vector<QualType> ResultRegQualTys;
Chris Lattnera077b5c2009-05-03 08:21:20 +0000808 std::vector<const llvm::Type *> ResultRegTypes;
809 std::vector<const llvm::Type *> ResultTruncRegTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000810 std::vector<const llvm::Type*> ArgTypes;
811 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000812
813 // Keep track of inout constraints.
814 std::string InOutConstraints;
815 std::vector<llvm::Value*> InOutArgs;
816 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +0000817
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000818 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +0000819 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000820
Anders Carlsson03eb5432009-01-27 20:38:24 +0000821 OutputConstraintInfos.push_back(Info);
822
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000823 // Simplify the output constraint.
Chris Lattner481fef92009-05-03 07:05:00 +0000824 std::string OutputConstraint(S.getOutputConstraint(i));
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000825 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000826
Chris Lattner810f6d52009-03-13 17:38:01 +0000827 const Expr *OutExpr = S.getOutputExpr(i);
828 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
829
830 LValue Dest = EmitLValue(OutExpr);
Chris Lattnerede9d902009-05-03 07:53:25 +0000831 if (!Constraints.empty())
Anders Carlssonbad3a942009-05-01 00:16:04 +0000832 Constraints += ',';
833
Chris Lattnera077b5c2009-05-03 08:21:20 +0000834 // If this is a register output, then make the inline asm return it
835 // by-value. If this is a memory result, return the value by-reference.
Chris Lattnerede9d902009-05-03 07:53:25 +0000836 if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
Chris Lattnera077b5c2009-05-03 08:21:20 +0000837 Constraints += "=" + OutputConstraint;
Chris Lattnerede9d902009-05-03 07:53:25 +0000838 ResultRegQualTys.push_back(OutExpr->getType());
839 ResultRegDests.push_back(Dest);
Chris Lattnera077b5c2009-05-03 08:21:20 +0000840 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
841 ResultTruncRegTypes.push_back(ResultRegTypes.back());
842
843 // If this output is tied to an input, and if the input is larger, then
844 // we need to set the actual result type of the inline asm node to be the
845 // same as the input type.
846 if (Info.hasMatchingInput()) {
Chris Lattnerebfc9852009-05-03 08:38:58 +0000847 unsigned InputNo;
848 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
849 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
850 if (Input.hasTiedOperand() &&
851 Input.getTiedOperand() == i) {
Chris Lattnera077b5c2009-05-03 08:21:20 +0000852 InputNo = i;
853 break;
854 }
Chris Lattnerebfc9852009-05-03 08:38:58 +0000855 }
856 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
Chris Lattnera077b5c2009-05-03 08:21:20 +0000857
858 QualType InputTy = S.getInputExpr(InputNo)->getType();
859 QualType OutputTy = OutExpr->getType();
860
861 uint64_t InputSize = getContext().getTypeSize(InputTy);
862 if (getContext().getTypeSize(OutputTy) < InputSize) {
863 // Form the asm to return the value as a larger integer type.
864 ResultRegTypes.back() = llvm::IntegerType::get((unsigned)InputSize);
865 }
866 }
867
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000868 } else {
869 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000870 Args.push_back(Dest.getAddress());
Anders Carlssonf39a4212008-02-05 20:01:53 +0000871 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000872 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000873 }
874
Chris Lattner44def072009-04-26 07:16:29 +0000875 if (Info.isReadWrite()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000876 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +0000877
Anders Carlssonf39a4212008-02-05 20:01:53 +0000878 const Expr *InputExpr = S.getOutputExpr(i);
Anders Carlsson63471722009-01-11 19:32:54 +0000879 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Anders Carlssonf39a4212008-02-05 20:01:53 +0000880
Chris Lattner44def072009-04-26 07:16:29 +0000881 if (Info.allowsRegister())
Anders Carlsson9f2505b2009-01-11 21:23:27 +0000882 InOutConstraints += llvm::utostr(i);
883 else
884 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +0000885
Anders Carlssonf39a4212008-02-05 20:01:53 +0000886 InOutArgTypes.push_back(Arg->getType());
887 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +0000888 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000889 }
890
891 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
892
893 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
894 const Expr *InputExpr = S.getInputExpr(i);
895
Chris Lattner481fef92009-05-03 07:05:00 +0000896 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
897
Chris Lattnerede9d902009-05-03 07:53:25 +0000898 if (!Constraints.empty())
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000899 Constraints += ',';
900
901 // Simplify the input constraint.
Chris Lattner481fef92009-05-03 07:05:00 +0000902 std::string InputConstraint(S.getInputConstraint(i));
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000903 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
Chris Lattner2819fa82009-04-26 17:57:12 +0000904 &OutputConstraintInfos);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000905
Anders Carlsson63471722009-01-11 19:32:54 +0000906 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000907
Chris Lattner4df4ee02009-05-03 07:27:51 +0000908 // If this input argument is tied to a larger output result, extend the
909 // input to be the same size as the output. The LLVM backend wants to see
910 // the input and output of a matching constraint be the same size. Note
911 // that GCC does not define what the top bits are here. We use zext because
912 // that is usually cheaper, but LLVM IR should really get an anyext someday.
913 if (Info.hasTiedOperand()) {
914 unsigned Output = Info.getTiedOperand();
915 QualType OutputTy = S.getOutputExpr(Output)->getType();
916 QualType InputTy = InputExpr->getType();
917
918 if (getContext().getTypeSize(OutputTy) >
919 getContext().getTypeSize(InputTy)) {
920 // Use ptrtoint as appropriate so that we can do our extension.
921 if (isa<llvm::PointerType>(Arg->getType()))
922 Arg = Builder.CreatePtrToInt(Arg,
923 llvm::IntegerType::get(LLVMPointerWidth));
924 unsigned OutputSize = (unsigned)getContext().getTypeSize(OutputTy);
925 Arg = Builder.CreateZExt(Arg, llvm::IntegerType::get(OutputSize));
926 }
927 }
928
929
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000930 ArgTypes.push_back(Arg->getType());
931 Args.push_back(Arg);
932 Constraints += InputConstraint;
933 }
934
Anders Carlssonf39a4212008-02-05 20:01:53 +0000935 // Append the "input" part of inout constraints last.
936 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
937 ArgTypes.push_back(InOutArgTypes[i]);
938 Args.push_back(InOutArgs[i]);
939 }
940 Constraints += InOutConstraints;
941
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000942 // Clobbers
943 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
944 std::string Clobber(S.getClobber(i)->getStrData(),
945 S.getClobber(i)->getByteLength());
946
947 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
948
Anders Carlssonea041752008-02-06 00:11:32 +0000949 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000950 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +0000951
952 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000953 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +0000954 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000955 }
956
957 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +0000958 std::string MachineClobbers = Target.getClobbers();
959 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000960 if (!Constraints.empty())
961 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +0000962 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000963 }
Anders Carlssonbad3a942009-05-01 00:16:04 +0000964
965 const llvm::Type *ResultType;
Chris Lattnera077b5c2009-05-03 08:21:20 +0000966 if (ResultRegTypes.empty())
Anders Carlssonbad3a942009-05-01 00:16:04 +0000967 ResultType = llvm::Type::VoidTy;
Chris Lattnera077b5c2009-05-03 08:21:20 +0000968 else if (ResultRegTypes.size() == 1)
969 ResultType = ResultRegTypes[0];
Anders Carlssonbad3a942009-05-01 00:16:04 +0000970 else
Chris Lattnera077b5c2009-05-03 08:21:20 +0000971 ResultType = llvm::StructType::get(ResultRegTypes);
Anders Carlssonbad3a942009-05-01 00:16:04 +0000972
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000973 const llvm::FunctionType *FTy =
974 llvm::FunctionType::get(ResultType, ArgTypes, false);
975
976 llvm::InlineAsm *IA =
977 llvm::InlineAsm::get(FTy, AsmString, Constraints,
978 S.isVolatile() || S.getNumOutputs() == 0);
Anders Carlssonbad3a942009-05-01 00:16:04 +0000979 llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end());
Anders Carlssonbc0822b2009-03-02 19:58:15 +0000980 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
981
Chris Lattnera077b5c2009-05-03 08:21:20 +0000982
983 // Extract all of the register value results from the asm.
984 std::vector<llvm::Value*> RegResults;
985 if (ResultRegTypes.size() == 1) {
986 RegResults.push_back(Result);
Anders Carlssonbad3a942009-05-01 00:16:04 +0000987 } else {
Chris Lattnera077b5c2009-05-03 08:21:20 +0000988 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
Anders Carlssonbad3a942009-05-01 00:16:04 +0000989 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
Chris Lattnera077b5c2009-05-03 08:21:20 +0000990 RegResults.push_back(Tmp);
Anders Carlssonbad3a942009-05-01 00:16:04 +0000991 }
992 }
Chris Lattnera077b5c2009-05-03 08:21:20 +0000993
994 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
995 llvm::Value *Tmp = RegResults[i];
996
997 // If the result type of the LLVM IR asm doesn't match the result type of
998 // the expression, do the conversion.
999 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1000 const llvm::Type *TruncTy = ResultTruncRegTypes[i];
1001 // Truncate the integer result to the right size, note that
1002 // ResultTruncRegTypes can be a pointer.
1003 uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
1004 Tmp = Builder.CreateTrunc(Tmp, llvm::IntegerType::get((unsigned)ResSize));
1005
1006 if (Tmp->getType() != TruncTy) {
1007 assert(isa<llvm::PointerType>(TruncTy));
1008 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
1009 }
1010 }
1011
1012 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i],
1013 ResultRegQualTys[i]);
1014 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001015}