blob: 839ba671b92cce833fa7667968d279800d507891 [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"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000018#include "clang/Basic/TargetInfo.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000019#include "llvm/ADT/StringExtras.h"
Anders Carlsson17d28a32008-12-12 05:52:00 +000020#include "llvm/InlineAsm.h"
21#include "llvm/Intrinsics.h"
Anders Carlssonebaae2a2009-01-12 02:22:13 +000022#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023using namespace clang;
24using namespace CodeGen;
25
26//===----------------------------------------------------------------------===//
27// Statement Emission
28//===----------------------------------------------------------------------===//
29
Daniel Dunbar09124252008-11-12 08:21:33 +000030void CodeGenFunction::EmitStopPoint(const Stmt *S) {
Anders Carlssone896d982009-02-13 08:11:52 +000031 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar09124252008-11-12 08:21:33 +000032 DI->setLocation(S->getLocStart());
33 DI->EmitStopPoint(CurFn, Builder);
34 }
35}
36
Reid Spencer5f016e22007-07-11 17:01:13 +000037void CodeGenFunction::EmitStmt(const Stmt *S) {
38 assert(S && "Null statement?");
Daniel Dunbara448fb22008-11-11 23:11:34 +000039
Daniel Dunbar09124252008-11-12 08:21:33 +000040 // Check if we can handle this without bothering to generate an
41 // insert point or debug info.
42 if (EmitSimpleStmt(S))
43 return;
44
Daniel Dunbara448fb22008-11-11 23:11:34 +000045 // If we happen to be at an unreachable point just create a dummy
46 // basic block to hold the code. We could change parts of irgen to
47 // simply not generate this code, but this situation is rare and
48 // probably not worth the effort.
49 // FIXME: Verify previous performance/effort claim.
50 EnsureInsertPoint();
Reid Spencer5f016e22007-07-11 17:01:13 +000051
Daniel Dunbar09124252008-11-12 08:21:33 +000052 // Generate a stoppoint if we are emitting debug info.
53 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000054
Reid Spencer5f016e22007-07-11 17:01:13 +000055 switch (S->getStmtClass()) {
56 default:
Chris Lattner1e4d21e2007-08-26 22:58:05 +000057 // Must be an expression in a stmt context. Emit the value (to get
58 // side-effects) and ignore the result.
Reid Spencer5f016e22007-07-11 17:01:13 +000059 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner1e4d21e2007-08-26 22:58:05 +000060 if (!hasAggregateLLVMType(E->getType()))
61 EmitScalarExpr(E);
Chris Lattner9b2dc282008-04-04 16:54:41 +000062 else if (E->getType()->isAnyComplexType())
Chris Lattner1e4d21e2007-08-26 22:58:05 +000063 EmitComplexExpr(E);
64 else
65 EmitAggExpr(E, 0, false);
Reid Spencer5f016e22007-07-11 17:01:13 +000066 } else {
Daniel Dunbar488e9932008-08-16 00:56:44 +000067 ErrorUnsupported(S, "statement");
Reid Spencer5f016e22007-07-11 17:01:13 +000068 }
69 break;
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000070 case Stmt::IndirectGotoStmtClass:
71 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +000072
73 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
74 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
75 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
76 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
77
78 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
79 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +000080
Devang Patel51b09f22007-10-04 23:45:31 +000081 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000082 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000083
84 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000085 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
86 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000087 case Stmt::ObjCAtCatchStmtClass:
Anders Carlssondde0a942008-09-11 09:15:33 +000088 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
89 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +000090 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000091 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +000092 break;
93 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +000094 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000095 break;
96 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +000097 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +000098 break;
Anders Carlsson3d8400d2008-08-30 19:51:14 +000099 case Stmt::ObjCForCollectionStmtClass:
100 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000101 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 }
103}
104
Daniel Dunbar09124252008-11-12 08:21:33 +0000105bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
106 switch (S->getStmtClass()) {
107 default: return false;
108 case Stmt::NullStmtClass: break;
109 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
110 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
111 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
112 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
113 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
114 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
115 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
116 }
117
118 return true;
119}
120
Chris Lattner33793202007-08-31 22:09:40 +0000121/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
122/// this captures the expression result of the last sub-statement and returns it
123/// (for use by the statement expression extension).
Chris Lattner9b655512007-08-31 22:49:20 +0000124RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
125 llvm::Value *AggLoc, bool isAggVol) {
Anders Carlssonc71c8452009-02-07 23:50:39 +0000126
Anders Carlssone896d982009-02-13 08:11:52 +0000127 CGDebugInfo *DI = getDebugInfo();
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000128 if (DI) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000129 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000130 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000131 DI->EmitRegionStart(CurFn, Builder);
132 }
133
Anders Carlssonc71c8452009-02-07 23:50:39 +0000134 // Keep track of the current cleanup stack depth.
135 size_t CleanupStackDepth = CleanupEntries.size();
Anders Carlsson74331892009-02-09 20:23:40 +0000136 bool OldDidCallStackSave = DidCallStackSave;
Anders Carlsson66b41512009-02-22 18:44:21 +0000137 DidCallStackSave = false;
Anders Carlsson74331892009-02-09 20:23:40 +0000138
Chris Lattner33793202007-08-31 22:09:40 +0000139 for (CompoundStmt::const_body_iterator I = S.body_begin(),
140 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000141 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000142
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000143 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000144 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000145 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000146 DI->EmitRegionEnd(CurFn, Builder);
147 }
148
Anders Carlsson17d28a32008-12-12 05:52:00 +0000149 RValue RV;
150 if (!GetLast)
151 RV = RValue::get(0);
152 else {
153 // We have to special case labels here. They are statements, but when put
154 // at the end of a statement expression, they yield the value of their
155 // subexpression. Handle this by walking through all labels we encounter,
156 // emitting them before we evaluate the subexpr.
157 const Stmt *LastStmt = S.body_back();
158 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
159 EmitLabel(*LS);
160 LastStmt = LS->getSubStmt();
161 }
Chris Lattner9b655512007-08-31 22:49:20 +0000162
Anders Carlsson17d28a32008-12-12 05:52:00 +0000163 EnsureInsertPoint();
164
165 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
166 }
167
Anders Carlsson74331892009-02-09 20:23:40 +0000168 DidCallStackSave = OldDidCallStackSave;
169
Anders Carlssonc71c8452009-02-07 23:50:39 +0000170 EmitCleanupBlocks(CleanupStackDepth);
171
Anders Carlsson17d28a32008-12-12 05:52:00 +0000172 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000173}
174
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000175void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000176 // Fall out of the current block (if necessary).
177 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000178
179 if (IsFinished && BB->use_empty()) {
180 delete BB;
181 return;
182 }
183
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000184 // If necessary, associate the block with the cleanup stack size.
185 if (!CleanupEntries.empty()) {
Anders Carlsson22ab8d82009-02-10 22:50:24 +0000186 // Check if the basic block has already been inserted.
187 BlockScopeMap::iterator I = BlockScopes.find(BB);
188 if (I != BlockScopes.end()) {
189 assert(I->second == CleanupEntries.size() - 1);
190 } else {
191 BlockScopes[BB] = CleanupEntries.size() - 1;
192 CleanupEntries.back().Blocks.push_back(BB);
193 }
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000194 }
195
Reid Spencer5f016e22007-07-11 17:01:13 +0000196 CurFn->getBasicBlockList().push_back(BB);
197 Builder.SetInsertPoint(BB);
198}
199
Daniel Dunbard57a8712008-11-11 09:41:28 +0000200void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
201 // Emit a branch from the current block to the target one if this
202 // was a real block. If this was just a fall-through block after a
203 // terminator, don't emit it.
204 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
205
206 if (!CurBB || CurBB->getTerminator()) {
207 // If there is no insert point or the previous block is already
208 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000209 } else {
210 // Otherwise, create a fall-through branch.
211 Builder.CreateBr(Target);
212 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000213
214 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000215}
216
Mike Stumpec9771d2009-02-08 09:22:19 +0000217void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Anders Carlssonfa1f7562009-02-10 06:07:49 +0000218 EmitBlock(getBasicBlockForLabel(&S));
Chris Lattner91d723d2008-07-26 20:23:23 +0000219}
220
221
222void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
223 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000224 EmitStmt(S.getSubStmt());
225}
226
227void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000228 // If this code is reachable then emit a stop point (if generating
229 // debug info). We have to do this ourselves because we are on the
230 // "simple" statement path.
231 if (HaveInsertPoint())
232 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000233
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000234 EmitBranchThroughCleanup(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000235}
236
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000237void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
238 // Emit initial switch which will be patched up later by
239 // EmitIndirectSwitches(). We need a default dest, so we use the
240 // current BB, but this is overwritten.
241 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
242 llvm::Type::Int32Ty,
243 "addr");
244 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
245 IndirectSwitches.push_back(I);
246
Daniel Dunbara448fb22008-11-11 23:11:34 +0000247 // Clear the insertion point to indicate we are in unreachable code.
248 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000249}
250
Chris Lattner62b72f62008-11-11 07:24:28 +0000251void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000252 // C99 6.8.4.1: The first substatement is executed if the expression compares
253 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000254
Chris Lattner9bc47e22008-11-12 07:46:33 +0000255 // If the condition constant folds and can be elided, try to avoid emitting
256 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000257 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000258 // Figure out which block (then or else) is executed.
259 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000260 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000261 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000262
Chris Lattner62b72f62008-11-11 07:24:28 +0000263 // If the skipped block has no labels in it, just emit the executed block.
264 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000265 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000266 if (Executed)
267 EmitStmt(Executed);
268 return;
269 }
270 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000271
272 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
273 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000274 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
275 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
276 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000278 ElseBlock = createBasicBlock("if.else");
279 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000280
281 // Emit the 'then' code.
282 EmitBlock(ThenBlock);
283 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000284 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000285
286 // Emit the 'else' code if present.
287 if (const Stmt *Else = S.getElse()) {
288 EmitBlock(ElseBlock);
289 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000290 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000291 }
292
293 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000294 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000295}
296
297void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 // Emit the header for the loop, insert it, which will create an uncond br to
299 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000300 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 EmitBlock(LoopHeader);
Mike Stump72cac2c2009-02-07 18:08:12 +0000302
303 // Create an exit block for when the condition fails, create a block for the
304 // body of the loop.
305 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
306 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
307
308 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000309 BreakContinueStack.push_back(BreakContinue(ExitBlock, LoopHeader));
Reid Spencer5f016e22007-07-11 17:01:13 +0000310
Mike Stump16b16202009-02-07 17:18:33 +0000311 // Evaluate the conditional in the while header. C99 6.8.5.1: The
312 // evaluation of the controlling expression takes place before each
313 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000314 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000315
316 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000317 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000318 bool EmitBoolCondBranch = true;
319 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
320 if (C->isOne())
321 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000322
Reid Spencer5f016e22007-07-11 17:01:13 +0000323 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000324 if (EmitBoolCondBranch)
325 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000326
Reid Spencer5f016e22007-07-11 17:01:13 +0000327 // Emit the loop body.
328 EmitBlock(LoopBody);
329 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000330
Anders Carlssone4b6d342009-02-10 05:52:02 +0000331 BreakContinueStack.pop_back();
Reid Spencer5f016e22007-07-11 17:01:13 +0000332
333 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000334 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000335
336 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000337 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000338
339 // If LoopHeader is a simple forwarding block then eliminate it.
340 if (!EmitBoolCondBranch
341 && &LoopHeader->front() == LoopHeader->getTerminator()) {
342 LoopHeader->replaceAllUsesWith(LoopBody);
343 LoopHeader->getTerminator()->eraseFromParent();
344 LoopHeader->eraseFromParent();
345 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000346}
347
348void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000349 // Emit the body for the loop, insert it, which will create an uncond br to
350 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000351 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
352 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000354
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000355 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattnerda138702007-07-16 21:28:45 +0000356
357 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000358 BreakContinueStack.push_back(BreakContinue(AfterDo, DoCond));
Reid Spencer5f016e22007-07-11 17:01:13 +0000359
360 // Emit the body of the loop into the block.
361 EmitStmt(S.getBody());
362
Anders Carlssone4b6d342009-02-10 05:52:02 +0000363 BreakContinueStack.pop_back();
Chris Lattnerda138702007-07-16 21:28:45 +0000364
365 EmitBlock(DoCond);
366
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
368 // after each execution of the loop body."
369
370 // Evaluate the conditional in the while header.
371 // C99 6.8.5p2/p4: The first substatement is executed if the expression
372 // compares unequal to 0. The condition must be a scalar type.
373 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000374
375 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
376 // to correctly handle break/continue though.
377 bool EmitBoolCondBranch = true;
378 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
379 if (C->isZero())
380 EmitBoolCondBranch = false;
381
Reid Spencer5f016e22007-07-11 17:01:13 +0000382 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000383 if (EmitBoolCondBranch)
384 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000385
386 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000387 EmitBlock(AfterDo, true);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000388
389 // If DoCond is a simple forwarding block then eliminate it.
390 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
391 DoCond->replaceAllUsesWith(AfterDo);
392 DoCond->getTerminator()->eraseFromParent();
393 DoCond->eraseFromParent();
394 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000395}
396
397void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
399 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000400
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 // Evaluate the first part before the loop.
402 if (S.getInit())
403 EmitStmt(S.getInit());
404
405 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000406 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
407 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattnerda138702007-07-16 21:28:45 +0000408
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 EmitBlock(CondBlock);
410
Mike Stump20926c62009-02-07 20:14:12 +0000411 // Evaluate the condition if present. If not, treat it as a
412 // non-zero-constant according to 6.8.5.3p2, aka, true.
Reid Spencer5f016e22007-07-11 17:01:13 +0000413 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000415 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner31a09842008-11-12 08:04:58 +0000416
417 // C99 6.8.5p2/p4: The first substatement is executed if the expression
418 // compares unequal to 0. The condition must be a scalar type.
419 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
420
Reid Spencer5f016e22007-07-11 17:01:13 +0000421 EmitBlock(ForBody);
422 } else {
423 // Treat it as a non-zero constant. Don't even create a new block for the
424 // body, just fall into it.
425 }
426
Chris Lattnerda138702007-07-16 21:28:45 +0000427 // If the for loop doesn't have an increment we can just use the
428 // condition as the continue block.
429 llvm::BasicBlock *ContinueBlock;
430 if (S.getInc())
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000431 ContinueBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000432 else
433 ContinueBlock = CondBlock;
434
435 // Store the blocks to use for break and continue.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000436 BreakContinueStack.push_back(BreakContinue(AfterFor, ContinueBlock));
Mike Stump3e9da662009-02-07 23:02:10 +0000437
Reid Spencer5f016e22007-07-11 17:01:13 +0000438 // If the condition is true, execute the body of the for stmt.
439 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000440
Anders Carlssone4b6d342009-02-10 05:52:02 +0000441 BreakContinueStack.pop_back();
Chris Lattnerda138702007-07-16 21:28:45 +0000442
Reid Spencer5f016e22007-07-11 17:01:13 +0000443 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000444 if (S.getInc()) {
445 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000446 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000447 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000448
449 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000450 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000451
Chris Lattnerda138702007-07-16 21:28:45 +0000452 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000453 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000454}
455
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000456void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
457 if (RV.isScalar()) {
458 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
459 } else if (RV.isAggregate()) {
460 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
461 } else {
462 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
463 }
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000464 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000465}
466
Reid Spencer5f016e22007-07-11 17:01:13 +0000467/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
468/// if the function returns void, or may be missing one if the function returns
469/// non-void. Fun stuff :).
470void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 // Emit the result value, even if unused, to evalute the side effects.
472 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000473
474 // FIXME: Clean this up by using an LValue for ReturnTemp,
475 // EmitStoreThroughLValue, and EmitAnyExpr.
476 if (!ReturnValue) {
477 // Make sure not to return anything, but evaluate the expression
478 // for side effects.
479 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000480 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000481 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000482 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000483 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000484 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000485 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000486 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000487 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000488 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000489 }
Eli Friedman144ac612008-05-22 01:22:33 +0000490
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000491 EmitBranchThroughCleanup(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000492}
493
494void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000495 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
496 I != E; ++I)
497 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000498}
Chris Lattnerda138702007-07-16 21:28:45 +0000499
Daniel Dunbar09124252008-11-12 08:21:33 +0000500void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000501 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
502
Daniel Dunbar09124252008-11-12 08:21:33 +0000503 // If this code is reachable then emit a stop point (if generating
504 // debug info). We have to do this ourselves because we are on the
505 // "simple" statement path.
506 if (HaveInsertPoint())
507 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000508
Chris Lattnerda138702007-07-16 21:28:45 +0000509 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000510 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000511}
512
Daniel Dunbar09124252008-11-12 08:21:33 +0000513void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000514 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
515
Daniel Dunbar09124252008-11-12 08:21:33 +0000516 // If this code is reachable then emit a stop point (if generating
517 // debug info). We have to do this ourselves because we are on the
518 // "simple" statement path.
519 if (HaveInsertPoint())
520 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +0000521
Chris Lattnerda138702007-07-16 21:28:45 +0000522 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000523 EmitBranchThroughCleanup(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000524}
Devang Patel51b09f22007-10-04 23:45:31 +0000525
Devang Patelc049e4f2007-10-08 20:57:48 +0000526/// EmitCaseStmtRange - If case statement range is not too big then
527/// add multiple cases to switch instruction, one for each value within
528/// the range. If range is too big then emit "if" condition check.
529void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000530 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000531
Anders Carlsson51fe9962008-11-22 21:04:56 +0000532 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
533 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000534
Daniel Dunbar16f23572008-07-25 01:11:38 +0000535 // Emit the code for this case. We do this first to make sure it is
536 // properly chained from our predecessor before generating the
537 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000538 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000539 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
540 EmitStmt(S.getSubStmt());
541
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000542 // If range is empty, do nothing.
543 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
544 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000545
546 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000547 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000548 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
549 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000550 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000551 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
552 LHS++;
553 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000554 return;
555 }
556
Daniel Dunbar16f23572008-07-25 01:11:38 +0000557 // The range is too big. Emit "if" condition into a new block,
558 // making sure to save and restore the current insertion point.
559 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000560
Daniel Dunbar16f23572008-07-25 01:11:38 +0000561 // Push this test onto the chain of range checks (which terminates
562 // in the default basic block). The switch's default will be changed
563 // to the top of this chain after switch emission is complete.
564 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000565 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000566
Daniel Dunbar16f23572008-07-25 01:11:38 +0000567 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
568 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000569
570 // Emit range check.
571 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000572 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
573 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000574 llvm::Value *Cond =
575 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
576 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
577
Daniel Dunbar16f23572008-07-25 01:11:38 +0000578 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000579 if (RestoreBB)
580 Builder.SetInsertPoint(RestoreBB);
581 else
582 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000583}
584
585void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
586 if (S.getRHS()) {
587 EmitCaseStmtRange(S);
588 return;
589 }
590
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000591 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000592 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000593 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000594 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Chris Lattner5512f282009-03-04 04:46:18 +0000595
596 // Recursively emitting the statement is acceptable, but is not wonderful for
597 // code where we have many case statements nested together, i.e.:
598 // case 1:
599 // case 2:
600 // case 3: etc.
601 // Handling this recursively will create a new block for each case statement
602 // that falls through to the next case which is IR intensive. It also causes
603 // deep recursion which can run into stack depth limitations. Handle
604 // sequential non-range case statements specially.
605 const CaseStmt *CurCase = &S;
606 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
607
608 // Otherwise, iteratively add consequtive cases to this switch stmt.
609 while (NextCase && NextCase->getRHS() == 0) {
610 CurCase = NextCase;
611 CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
612 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
613
614 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
615 }
616
617 // Normal default recursion for non-cases.
618 EmitStmt(CurCase->getSubStmt());
Devang Patel51b09f22007-10-04 23:45:31 +0000619}
620
621void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000622 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000623 assert(DefaultBlock->empty() &&
624 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000625 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000626 EmitStmt(S.getSubStmt());
627}
628
629void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
630 llvm::Value *CondV = EmitScalarExpr(S.getCond());
631
632 // Handle nested switch statements.
633 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000634 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000635
Daniel Dunbar16f23572008-07-25 01:11:38 +0000636 // Create basic block to hold stuff that comes after switch
637 // statement. We also need to create a default block now so that
638 // explicit case ranges tests can have a place to jump to on
639 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000640 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
641 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000642 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
643 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000644
Daniel Dunbar09124252008-11-12 08:21:33 +0000645 // Clear the insertion point to indicate we are in unreachable code.
646 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000647
Devang Patele9b8c0a2007-10-30 20:59:40 +0000648 // All break statements jump to NextBlock. If BreakContinueStack is non empty
649 // then reuse last ContinueBlock.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000650 llvm::BasicBlock *ContinueBlock = 0;
651 if (!BreakContinueStack.empty())
Devang Patel51b09f22007-10-04 23:45:31 +0000652 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +0000653
Mike Stump3e9da662009-02-07 23:02:10 +0000654 // Ensure any vlas created between there and here, are undone
Anders Carlssone4b6d342009-02-10 05:52:02 +0000655 BreakContinueStack.push_back(BreakContinue(NextBlock, ContinueBlock));
Devang Patel51b09f22007-10-04 23:45:31 +0000656
657 // Emit switch body.
658 EmitStmt(S.getBody());
Anders Carlssone4b6d342009-02-10 05:52:02 +0000659
660 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +0000661
Daniel Dunbar16f23572008-07-25 01:11:38 +0000662 // Update the default block in case explicit case range tests have
663 // been chained on top.
664 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000665
Daniel Dunbar16f23572008-07-25 01:11:38 +0000666 // If a default was never emitted then reroute any jumps to it and
667 // discard.
668 if (!DefaultBlock->getParent()) {
669 DefaultBlock->replaceAllUsesWith(NextBlock);
670 delete DefaultBlock;
671 }
Devang Patel51b09f22007-10-04 23:45:31 +0000672
Daniel Dunbar16f23572008-07-25 01:11:38 +0000673 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000674 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000675
Devang Patel51b09f22007-10-04 23:45:31 +0000676 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000677 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000678}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000679
Anders Carlssonce179ab2008-11-09 18:54:14 +0000680static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
681{
682 // FIXME: No need to create new std::string here, we could just make sure
683 // that we don't read past the end of the string data.
684 std::string str(S.getAsmString()->getStrData(),
685 S.getAsmString()->getByteLength());
686 const char *Start = str.c_str();
687
688 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
689 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000690 Failed = false;
691
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000692 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000693 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000694 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000695 if (IsSimple) {
696 while (*Start) {
697 switch (*Start) {
698 default:
699 Result += *Start;
700 break;
701 case '$':
702 Result += "$$";
703 break;
704 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000705 Start++;
706 }
707
708 return Result;
709 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000710
711 while (*Start) {
712 switch (*Start) {
713 default:
714 Result += *Start;
715 break;
716 case '$':
717 Result += "$$";
718 break;
719 case '%':
720 // Escaped character
721 Start++;
722 if (!*Start) {
723 // FIXME: This should be caught during Sema.
724 assert(0 && "Trailing '%' in asm string.");
725 }
726
727 char EscapedChar = *Start;
728 if (EscapedChar == '%') {
729 // Escaped percentage sign.
730 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000731 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000732 // Generate an unique ID.
733 Result += llvm::utostr(AsmCounter);
734 } else if (isdigit(EscapedChar)) {
735 // %n - Assembler operand n
736 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000737 unsigned long n = strtoul(Start, &End, 10);
738 if (Start == End) {
739 // FIXME: This should be caught during Sema.
740 assert(0 && "Missing operand!");
741 } else if (n >= NumOperands) {
742 // FIXME: This should be caught during Sema.
743 assert(0 && "Operand number out of range!");
744 }
745
746 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000747 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000748 } else if (isalpha(EscapedChar)) {
749 char *End;
750
751 unsigned long n = strtoul(Start + 1, &End, 10);
752 if (Start == End) {
753 // FIXME: This should be caught during Sema.
754 assert(0 && "Missing operand!");
755 } else if (n >= NumOperands) {
756 // FIXME: This should be caught during Sema.
757 assert(0 && "Operand number out of range!");
758 }
759
760 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000761 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000762 } else if (EscapedChar == '[') {
763 std::string SymbolicName;
764
765 Start++;
766
767 while (*Start && *Start != ']') {
768 SymbolicName += *Start;
769
770 Start++;
771 }
772
773 if (!Start) {
774 // FIXME: Should be caught by sema.
775 assert(0 && "Could not parse symbolic name");
776 }
777
778 assert(*Start == ']' && "Error parsing symbolic name");
779
780 int Index = -1;
781
782 // Check if this is an output operand.
783 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
784 if (S.getOutputName(i) == SymbolicName) {
785 Index = i;
786 break;
787 }
788 }
789
790 if (Index == -1) {
791 for (unsigned i = 0; i < S.getNumInputs(); i++) {
792 if (S.getInputName(i) == SymbolicName) {
793 Index = S.getNumOutputs() + i;
794 }
795 }
796 }
797
798 assert(Index != -1 && "Did not find right operand!");
799
800 Result += '$' + llvm::utostr(Index);
801
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000802 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000803 Failed = true;
804 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000805 }
806 }
807 Start++;
808 }
809
810 return Result;
811}
812
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000813static std::string SimplifyConstraint(const char* Constraint,
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000814 TargetInfo &Target,
815 const std::string *OutputNamesBegin = 0,
816 const std::string *OutputNamesEnd = 0)
817{
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000818 std::string Result;
819
820 while (*Constraint) {
821 switch (*Constraint) {
822 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000823 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000824 break;
825 // Ignore these
826 case '*':
827 case '?':
828 case '!':
829 break;
830 case 'g':
831 Result += "imr";
832 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000833 case '[': {
834 assert(OutputNamesBegin && OutputNamesEnd &&
835 "Must pass output names to constraints with a symbolic name");
836 unsigned Index;
837 bool result = Target.resolveSymbolicName(Constraint,
838 OutputNamesBegin,
839 OutputNamesEnd, Index);
Chris Lattner53637652009-01-21 07:35:26 +0000840 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000841 Result += llvm::utostr(Index);
842 break;
843 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000844 }
845
846 Constraint++;
847 }
848
849 return Result;
850}
851
Anders Carlsson63471722009-01-11 19:32:54 +0000852llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
853 TargetInfo::ConstraintInfo Info,
854 const Expr *InputExpr,
855 std::string &ConstraintStr)
856{
857 llvm::Value *Arg;
858 if ((Info & TargetInfo::CI_AllowsRegister) ||
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000859 !(Info & TargetInfo::CI_AllowsMemory)) {
860 const llvm::Type *Ty = ConvertType(InputExpr->getType());
861
862 if (Ty->isSingleValueType()) {
Anders Carlsson63471722009-01-11 19:32:54 +0000863 Arg = EmitScalarExpr(InputExpr);
864 } else {
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000865 LValue Dest = EmitLValue(InputExpr);
866
867 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
868 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
869 Ty = llvm::IntegerType::get(Size);
870 Ty = llvm::PointerType::getUnqual(Ty);
871
872 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
873 } else {
874 Arg = Dest.getAddress();
875 ConstraintStr += '*';
876 }
Anders Carlsson63471722009-01-11 19:32:54 +0000877 }
878 } else {
879 LValue Dest = EmitLValue(InputExpr);
880 Arg = Dest.getAddress();
881 ConstraintStr += '*';
882 }
883
884 return Arg;
885}
886
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000887void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000888 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000889 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000890 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000891
892 if (Failed) {
893 ErrorUnsupported(&S, "asm string");
894 return;
895 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000896
897 std::string Constraints;
898
899 llvm::Value *ResultAddr = 0;
900 const llvm::Type *ResultType = llvm::Type::VoidTy;
901
902 std::vector<const llvm::Type*> ArgTypes;
903 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000904
905 // Keep track of inout constraints.
906 std::string InOutConstraints;
907 std::vector<llvm::Value*> InOutArgs;
908 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +0000909
910 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
911
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000912 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
913 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
914 S.getOutputConstraint(i)->getByteLength());
915
916 TargetInfo::ConstraintInfo Info;
917 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
918 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000919 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000920
Anders Carlsson03eb5432009-01-27 20:38:24 +0000921 OutputConstraintInfos.push_back(Info);
922
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000923 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000924 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000925
926 LValue Dest = EmitLValue(S.getOutputExpr(i));
927 const llvm::Type *DestValueType =
928 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
929
930 // If the first output operand is not a memory dest, we'll
931 // make it the return value.
932 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +0000933 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000934 ResultAddr = Dest.getAddress();
935 ResultType = DestValueType;
936 Constraints += "=" + OutputConstraint;
937 } else {
938 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +0000939 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000940 if (i != 0)
941 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +0000942 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000943 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000944 }
945
946 if (Info & TargetInfo::CI_ReadWrite) {
Anders Carlssonf39a4212008-02-05 20:01:53 +0000947 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +0000948
Anders Carlssonf39a4212008-02-05 20:01:53 +0000949 const Expr *InputExpr = S.getOutputExpr(i);
Anders Carlsson63471722009-01-11 19:32:54 +0000950 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Anders Carlssonf39a4212008-02-05 20:01:53 +0000951
Anders Carlsson9f2505b2009-01-11 21:23:27 +0000952 if (Info & TargetInfo::CI_AllowsRegister)
953 InOutConstraints += llvm::utostr(i);
954 else
955 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +0000956
Anders Carlssonf39a4212008-02-05 20:01:53 +0000957 InOutArgTypes.push_back(Arg->getType());
958 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +0000959 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000960 }
961
962 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
963
964 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
965 const Expr *InputExpr = S.getInputExpr(i);
966
967 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
968 S.getInputConstraint(i)->getByteLength());
969
970 TargetInfo::ConstraintInfo Info;
971 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Anders Carlsson45b050e2009-01-17 23:36:15 +0000972 S.begin_output_names(),
973 S.end_output_names(),
Anders Carlsson03eb5432009-01-27 20:38:24 +0000974 &OutputConstraintInfos[0],
Chris Lattner53637652009-01-21 07:35:26 +0000975 Info); result=result;
Anders Carlsson42e1ee02009-01-18 01:56:57 +0000976 assert(result && "Failed to parse input constraint");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000977
978 if (i != 0 || S.getNumOutputs() > 0)
979 Constraints += ',';
980
981 // Simplify the input constraint.
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000982 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
983 S.begin_output_names(),
984 S.end_output_names());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000985
Anders Carlsson63471722009-01-11 19:32:54 +0000986 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000987
988 ArgTypes.push_back(Arg->getType());
989 Args.push_back(Arg);
990 Constraints += InputConstraint;
991 }
992
Anders Carlssonf39a4212008-02-05 20:01:53 +0000993 // Append the "input" part of inout constraints last.
994 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
995 ArgTypes.push_back(InOutArgTypes[i]);
996 Args.push_back(InOutArgs[i]);
997 }
998 Constraints += InOutConstraints;
999
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001000 // Clobbers
1001 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1002 std::string Clobber(S.getClobber(i)->getStrData(),
1003 S.getClobber(i)->getByteLength());
1004
1005 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
1006
Anders Carlssonea041752008-02-06 00:11:32 +00001007 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001008 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +00001009
1010 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001011 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001012 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001013 }
1014
1015 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +00001016 std::string MachineClobbers = Target.getClobbers();
1017 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001018 if (!Constraints.empty())
1019 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00001020 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001021 }
Anders Carlssonf39a4212008-02-05 20:01:53 +00001022
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001023 const llvm::FunctionType *FTy =
1024 llvm::FunctionType::get(ResultType, ArgTypes, false);
1025
1026 llvm::InlineAsm *IA =
1027 llvm::InlineAsm::get(FTy, AsmString, Constraints,
1028 S.isVolatile() || S.getNumOutputs() == 0);
Anders Carlssonbc0822b2009-03-02 19:58:15 +00001029 llvm::CallInst *Result
1030 = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
1031 Result->addAttribute(~0, llvm::Attribute::NoUnwind);
1032
Eli Friedman1e692ac2008-06-13 23:01:12 +00001033 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001034 Builder.CreateStore(Result, ResultAddr);
1035}