blob: c65b8114f37fe2fa28f184f22e323ee953538440 [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) {
31 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
32 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) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000126 // FIXME: handle vla's etc.
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000127 CGDebugInfo *DI = CGM.getDebugInfo();
128 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 Carlsson17d28a32008-12-12 05:52:00 +0000134 // Push a null stack save value.
135 StackSaveValues.push_back(0);
136
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
166 if (llvm::Value *V = StackSaveValues.pop_back_val()) {
Mike Stump36a2ada2009-02-07 12:52:26 +0000167 StackDepth = V;
Anders Carlsson17d28a32008-12-12 05:52:00 +0000168 V = Builder.CreateLoad(V, "tmp");
169
170 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
171 Builder.CreateCall(F, V);
Chris Lattner91d723d2008-07-26 20:23:23 +0000172 }
173
Anders Carlsson17d28a32008-12-12 05:52:00 +0000174 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000175}
176
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000177void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000178 // Fall out of the current block (if necessary).
179 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000180
181 if (IsFinished && BB->use_empty()) {
182 delete BB;
183 return;
184 }
185
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 CurFn->getBasicBlockList().push_back(BB);
187 Builder.SetInsertPoint(BB);
188}
189
Mike Stump36a2ada2009-02-07 12:52:26 +0000190void CodeGenFunction::EmitStackUpdate(const LabelStmt &S) {
191 if (StackDepthMap.find(&S) == StackDepthMap.end()) {
192 // If we can't find it, just remember the depth now,
193 // so we can validate it later.
194 // FIXME: We need to save a place to insert the adjustment,
195 // if needed, here, sa that later in EmitLabel, we can
196 // backpatch the adjustment into that place, instead of
197 // saying unsupported.
198 StackDepthMap[&S] = StackDepth;
199 return;
200 }
201
202 // Find applicable stack depth, if any...
203 llvm::Value *V = StackDepthMap[&S];
204 // V can be 0 here, if it is, be sure to start searching from the
205 // top of the function, as we want the next save after that point.
206 for (unsigned int i = 0; i < StackSaveValues.size(); ++i)
207 if (StackSaveValues[i] == V) {
208 // The actual depth is actually in the next used slot, if any.
209 while (++i < StackSaveValues.size()
210 && (V = StackSaveValues[i]) == 0) ;
211 // If there were no other depth changes, we don't need any
212 // adjustments.
213 if (V) {
214 V = Builder.CreateLoad(V, "tmp");
215 // and restore it.
216 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
217 Builder.CreateCall(F, V);
218 }
219 } else
220 // FIXME: Move to semq and assert here, codegen isn't the right
221 // time to be checking.
222 CGM.ErrorUnsupported(&S, "invalid goto to VLA scope that has finished");
223}
224
Daniel Dunbard57a8712008-11-11 09:41:28 +0000225void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
226 // Emit a branch from the current block to the target one if this
227 // was a real block. If this was just a fall-through block after a
228 // terminator, don't emit it.
229 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
230
231 if (!CurBB || CurBB->getTerminator()) {
232 // If there is no insert point or the previous block is already
233 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000234 } else {
235 // Otherwise, create a fall-through branch.
236 Builder.CreateBr(Target);
237 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000238
239 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000240}
241
Chris Lattner91d723d2008-07-26 20:23:23 +0000242void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000243 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000244 if (StackDepthMap.find(&S) == StackDepthMap.end()) {
245 // We need to remember the stack depth so that we can readjust the
246 // stack back to the right depth for this label if we want to
247 // transfer here from a different depth.
248 StackDepthMap[&S] = StackDepth;
249 } else {
250 if (StackDepthMap[&S] != StackDepth) {
251 // FIXME: Sema needs to ckeck for jumps that cross decls with
252 // initializations for C++, and all VLAs, not just the first in
253 // a block that does a stacksave.
254 // FIXME: We need to save a place to insert the adjustment
255 // when we do a EmitStackUpdate on a forward jump, and then
256 // backpatch the adjustment into that place.
257 CGM.ErrorUnsupported(&S, "forward goto inside scope with VLA");
258 }
259 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000260 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000261}
262
263
264void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
265 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000266 EmitStmt(S.getSubStmt());
267}
268
269void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000270 // FIXME: Implement goto out in @try or @catch blocks.
271 if (!ObjCEHStack.empty()) {
272 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
273 return;
274 }
275
Daniel Dunbar09124252008-11-12 08:21:33 +0000276 // If this code is reachable then emit a stop point (if generating
277 // debug info). We have to do this ourselves because we are on the
278 // "simple" statement path.
279 if (HaveInsertPoint())
280 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000281
282 // We need to adjust the stack, if the destination was (will be) at
283 // a different depth.
284 EmitStackUpdate(*S.getLabel());
285
Daniel Dunbard57a8712008-11-11 09:41:28 +0000286 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000287}
288
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000289void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000290 // FIXME: Implement indirect goto in @try or @catch blocks.
291 if (!ObjCEHStack.empty()) {
292 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
293 return;
294 }
295
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000296 // Emit initial switch which will be patched up later by
297 // EmitIndirectSwitches(). We need a default dest, so we use the
298 // current BB, but this is overwritten.
299 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
300 llvm::Type::Int32Ty,
301 "addr");
302 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
303 IndirectSwitches.push_back(I);
304
Daniel Dunbara448fb22008-11-11 23:11:34 +0000305 // Clear the insertion point to indicate we are in unreachable code.
306 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000307}
308
Chris Lattner62b72f62008-11-11 07:24:28 +0000309void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000310 // C99 6.8.4.1: The first substatement is executed if the expression compares
311 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000312
Chris Lattner9bc47e22008-11-12 07:46:33 +0000313 // If the condition constant folds and can be elided, try to avoid emitting
314 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000315 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000316 // Figure out which block (then or else) is executed.
317 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000318 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000319 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000320
Chris Lattner62b72f62008-11-11 07:24:28 +0000321 // If the skipped block has no labels in it, just emit the executed block.
322 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000323 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000324 if (Executed)
325 EmitStmt(Executed);
326 return;
327 }
328 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000329
330 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
331 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000332 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
333 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
334 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000335 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000336 ElseBlock = createBasicBlock("if.else");
337 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000338
339 // Emit the 'then' code.
340 EmitBlock(ThenBlock);
341 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000342 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000343
344 // Emit the 'else' code if present.
345 if (const Stmt *Else = S.getElse()) {
346 EmitBlock(ElseBlock);
347 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000348 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000349 }
350
351 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000352 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000353}
354
355void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 // Emit the header for the loop, insert it, which will create an uncond br to
357 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000358 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 EmitBlock(LoopHeader);
Mike Stump72cac2c2009-02-07 18:08:12 +0000360
361 // Create an exit block for when the condition fails, create a block for the
362 // body of the loop.
363 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
364 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
365
366 // Store the blocks to use for break and continue.
367 BreakContinuePush(ExitBlock, LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000368
Mike Stump16b16202009-02-07 17:18:33 +0000369 // Evaluate the conditional in the while header. C99 6.8.5.1: The
370 // evaluation of the controlling expression takes place before each
371 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000372 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000373
374 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000376 bool EmitBoolCondBranch = true;
377 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
378 if (C->isOne())
379 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000380
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000382 if (EmitBoolCondBranch)
383 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000384
Reid Spencer5f016e22007-07-11 17:01:13 +0000385 // Emit the loop body.
386 EmitBlock(LoopBody);
387 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000388
Mike Stump36a2ada2009-02-07 12:52:26 +0000389 BreakContinuePop();
Reid Spencer5f016e22007-07-11 17:01:13 +0000390
391 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000392 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000393
394 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000395 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000396
397 // If LoopHeader is a simple forwarding block then eliminate it.
398 if (!EmitBoolCondBranch
399 && &LoopHeader->front() == LoopHeader->getTerminator()) {
400 LoopHeader->replaceAllUsesWith(LoopBody);
401 LoopHeader->getTerminator()->eraseFromParent();
402 LoopHeader->eraseFromParent();
403 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000404}
405
406void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000407 // Emit the body for the loop, insert it, which will create an uncond br to
408 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000409 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
410 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000412
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000413 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattnerda138702007-07-16 21:28:45 +0000414
415 // Store the blocks to use for break and continue.
Mike Stump36a2ada2009-02-07 12:52:26 +0000416 BreakContinuePush(AfterDo, DoCond);
Reid Spencer5f016e22007-07-11 17:01:13 +0000417
418 // Emit the body of the loop into the block.
419 EmitStmt(S.getBody());
420
Mike Stump36a2ada2009-02-07 12:52:26 +0000421 BreakContinuePop();
Chris Lattnerda138702007-07-16 21:28:45 +0000422
423 EmitBlock(DoCond);
424
Reid Spencer5f016e22007-07-11 17:01:13 +0000425 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
426 // after each execution of the loop body."
427
428 // Evaluate the conditional in the while header.
429 // C99 6.8.5p2/p4: The first substatement is executed if the expression
430 // compares unequal to 0. The condition must be a scalar type.
431 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000432
433 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
434 // to correctly handle break/continue though.
435 bool EmitBoolCondBranch = true;
436 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
437 if (C->isZero())
438 EmitBoolCondBranch = false;
439
Reid Spencer5f016e22007-07-11 17:01:13 +0000440 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000441 if (EmitBoolCondBranch)
442 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000443
444 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000445 EmitBlock(AfterDo, true);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000446
447 // If DoCond is a simple forwarding block then eliminate it.
448 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
449 DoCond->replaceAllUsesWith(AfterDo);
450 DoCond->getTerminator()->eraseFromParent();
451 DoCond->eraseFromParent();
452 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000453}
454
455void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000456 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
457 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000458
Reid Spencer5f016e22007-07-11 17:01:13 +0000459 // Evaluate the first part before the loop.
460 if (S.getInit())
461 EmitStmt(S.getInit());
462
463 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000464 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
465 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattnerda138702007-07-16 21:28:45 +0000466
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 EmitBlock(CondBlock);
468
Mike Stump20926c62009-02-07 20:14:12 +0000469 // Evaluate the condition if present. If not, treat it as a
470 // non-zero-constant according to 6.8.5.3p2, aka, true.
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000473 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner31a09842008-11-12 08:04:58 +0000474
475 // C99 6.8.5p2/p4: The first substatement is executed if the expression
476 // compares unequal to 0. The condition must be a scalar type.
477 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
478
Reid Spencer5f016e22007-07-11 17:01:13 +0000479 EmitBlock(ForBody);
480 } else {
481 // Treat it as a non-zero constant. Don't even create a new block for the
482 // body, just fall into it.
483 }
484
Chris Lattnerda138702007-07-16 21:28:45 +0000485 // If the for loop doesn't have an increment we can just use the
486 // condition as the continue block.
487 llvm::BasicBlock *ContinueBlock;
488 if (S.getInc())
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000489 ContinueBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000490 else
491 ContinueBlock = CondBlock;
492
493 // Store the blocks to use for break and continue.
Mike Stump36a2ada2009-02-07 12:52:26 +0000494 BreakContinuePush(AfterFor, ContinueBlock);
Chris Lattnerda138702007-07-16 21:28:45 +0000495
Reid Spencer5f016e22007-07-11 17:01:13 +0000496 // If the condition is true, execute the body of the for stmt.
497 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000498
Mike Stump36a2ada2009-02-07 12:52:26 +0000499 BreakContinuePop();
Chris Lattnerda138702007-07-16 21:28:45 +0000500
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000502 if (S.getInc()) {
503 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000504 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000505 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000506
507 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000508 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000509
Chris Lattnerda138702007-07-16 21:28:45 +0000510 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000511 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000512}
513
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000514void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
515 if (RV.isScalar()) {
516 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
517 } else if (RV.isAggregate()) {
518 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
519 } else {
520 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
521 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000522 EmitBranch(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000523}
524
Reid Spencer5f016e22007-07-11 17:01:13 +0000525/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
526/// if the function returns void, or may be missing one if the function returns
527/// non-void. Fun stuff :).
528void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Eli Friedman20c802b2008-12-20 23:18:29 +0000529 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
Anders Carlsson7e63b852008-12-20 21:33:38 +0000530 if (StackSaveValues[i]) {
531 CGM.ErrorUnsupported(&S, "return inside scope with VLA");
532 return;
533 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000534 }
535
Reid Spencer5f016e22007-07-11 17:01:13 +0000536 // Emit the result value, even if unused, to evalute the side effects.
537 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000538
539 // FIXME: Clean this up by using an LValue for ReturnTemp,
540 // EmitStoreThroughLValue, and EmitAnyExpr.
541 if (!ReturnValue) {
542 // Make sure not to return anything, but evaluate the expression
543 // for side effects.
544 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000545 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000546 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000547 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000548 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000549 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000550 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000551 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000552 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000553 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000554 }
Eli Friedman144ac612008-05-22 01:22:33 +0000555
Daniel Dunbar898d5082008-09-30 01:06:03 +0000556 if (!ObjCEHStack.empty()) {
557 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
558 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000559 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000560 EmitJumpThroughFinally(*i, ReturnPad);
561 EmitBlock(ReturnPad);
562 }
563 }
564
Daniel Dunbard57a8712008-11-11 09:41:28 +0000565 EmitBranch(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000566}
567
568void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000569 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
570 I != E; ++I)
571 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000572}
Chris Lattnerda138702007-07-16 21:28:45 +0000573
Daniel Dunbar09124252008-11-12 08:21:33 +0000574void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000575 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
576
Daniel Dunbar09124252008-11-12 08:21:33 +0000577 // FIXME: Implement break in @try or @catch blocks.
Anders Carlssone21269b2008-12-13 22:52:24 +0000578 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000579 CGM.ErrorUnsupported(&S, "break inside an Obj-C exception block");
Daniel Dunbar09124252008-11-12 08:21:33 +0000580 return;
581 }
582
Eli Friedman20c802b2008-12-20 23:18:29 +0000583 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
584 if (StackSaveValues[i]) {
585 CGM.ErrorUnsupported(&S, "break inside scope with VLA");
586 return;
587 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000588 }
589
Daniel Dunbar09124252008-11-12 08:21:33 +0000590 // If this code is reachable then emit a stop point (if generating
591 // debug info). We have to do this ourselves because we are on the
592 // "simple" statement path.
593 if (HaveInsertPoint())
594 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000595 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000596 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000597}
598
Daniel Dunbar09124252008-11-12 08:21:33 +0000599void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000600 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
601
Daniel Dunbar09124252008-11-12 08:21:33 +0000602 // FIXME: Implement continue in @try or @catch blocks.
Anders Carlssone21269b2008-12-13 22:52:24 +0000603 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000604 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
605 return;
606 }
607
Eli Friedman20c802b2008-12-20 23:18:29 +0000608 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
609 if (StackSaveValues[i]) {
610 CGM.ErrorUnsupported(&S, "continue inside scope with VLA");
611 return;
612 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000613 }
614
Daniel Dunbar09124252008-11-12 08:21:33 +0000615 // If this code is reachable then emit a stop point (if generating
616 // debug info). We have to do this ourselves because we are on the
617 // "simple" statement path.
618 if (HaveInsertPoint())
619 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000620 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000621 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000622}
Devang Patel51b09f22007-10-04 23:45:31 +0000623
Devang Patelc049e4f2007-10-08 20:57:48 +0000624/// EmitCaseStmtRange - If case statement range is not too big then
625/// add multiple cases to switch instruction, one for each value within
626/// the range. If range is too big then emit "if" condition check.
627void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000628 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000629
Anders Carlsson51fe9962008-11-22 21:04:56 +0000630 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
631 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000632
Daniel Dunbar16f23572008-07-25 01:11:38 +0000633 // Emit the code for this case. We do this first to make sure it is
634 // properly chained from our predecessor before generating the
635 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000636 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000637 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
638 EmitStmt(S.getSubStmt());
639
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000640 // If range is empty, do nothing.
641 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
642 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000643
644 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000645 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000646 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
647 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000648 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000649 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
650 LHS++;
651 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000652 return;
653 }
654
Daniel Dunbar16f23572008-07-25 01:11:38 +0000655 // The range is too big. Emit "if" condition into a new block,
656 // making sure to save and restore the current insertion point.
657 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000658
Daniel Dunbar16f23572008-07-25 01:11:38 +0000659 // Push this test onto the chain of range checks (which terminates
660 // in the default basic block). The switch's default will be changed
661 // to the top of this chain after switch emission is complete.
662 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000663 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000664
Daniel Dunbar16f23572008-07-25 01:11:38 +0000665 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
666 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000667
668 // Emit range check.
669 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000670 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
671 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000672 llvm::Value *Cond =
673 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
674 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
675
Daniel Dunbar16f23572008-07-25 01:11:38 +0000676 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000677 if (RestoreBB)
678 Builder.SetInsertPoint(RestoreBB);
679 else
680 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000681}
682
683void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
684 if (S.getRHS()) {
685 EmitCaseStmtRange(S);
686 return;
687 }
688
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000689 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000690 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000691 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000692 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000693 EmitStmt(S.getSubStmt());
694}
695
696void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000697 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000698 assert(DefaultBlock->empty() &&
699 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000700 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000701 EmitStmt(S.getSubStmt());
702}
703
704void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
705 llvm::Value *CondV = EmitScalarExpr(S.getCond());
706
707 // Handle nested switch statements.
708 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000709 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000710
Daniel Dunbar16f23572008-07-25 01:11:38 +0000711 // Create basic block to hold stuff that comes after switch
712 // statement. We also need to create a default block now so that
713 // explicit case ranges tests can have a place to jump to on
714 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000715 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
716 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000717 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
718 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000719
Daniel Dunbar09124252008-11-12 08:21:33 +0000720 // Clear the insertion point to indicate we are in unreachable code.
721 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000722
Devang Patele9b8c0a2007-10-30 20:59:40 +0000723 // All break statements jump to NextBlock. If BreakContinueStack is non empty
724 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000725 llvm::BasicBlock *ContinueBlock = NULL;
726 if (!BreakContinueStack.empty())
727 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Mike Stump36a2ada2009-02-07 12:52:26 +0000728 BreakContinuePush(NextBlock, ContinueBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000729
730 // Emit switch body.
731 EmitStmt(S.getBody());
Mike Stump36a2ada2009-02-07 12:52:26 +0000732 BreakContinuePop();
Devang Patel51b09f22007-10-04 23:45:31 +0000733
Daniel Dunbar16f23572008-07-25 01:11:38 +0000734 // Update the default block in case explicit case range tests have
735 // been chained on top.
736 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000737
Daniel Dunbar16f23572008-07-25 01:11:38 +0000738 // If a default was never emitted then reroute any jumps to it and
739 // discard.
740 if (!DefaultBlock->getParent()) {
741 DefaultBlock->replaceAllUsesWith(NextBlock);
742 delete DefaultBlock;
743 }
Devang Patel51b09f22007-10-04 23:45:31 +0000744
Daniel Dunbar16f23572008-07-25 01:11:38 +0000745 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000746 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000747
Devang Patel51b09f22007-10-04 23:45:31 +0000748 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000749 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000750}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000751
Anders Carlssonce179ab2008-11-09 18:54:14 +0000752static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
753{
754 // FIXME: No need to create new std::string here, we could just make sure
755 // that we don't read past the end of the string data.
756 std::string str(S.getAsmString()->getStrData(),
757 S.getAsmString()->getByteLength());
758 const char *Start = str.c_str();
759
760 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
761 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000762 Failed = false;
763
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000764 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000765 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000766 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000767 if (IsSimple) {
768 while (*Start) {
769 switch (*Start) {
770 default:
771 Result += *Start;
772 break;
773 case '$':
774 Result += "$$";
775 break;
776 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000777 Start++;
778 }
779
780 return Result;
781 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000782
783 while (*Start) {
784 switch (*Start) {
785 default:
786 Result += *Start;
787 break;
788 case '$':
789 Result += "$$";
790 break;
791 case '%':
792 // Escaped character
793 Start++;
794 if (!*Start) {
795 // FIXME: This should be caught during Sema.
796 assert(0 && "Trailing '%' in asm string.");
797 }
798
799 char EscapedChar = *Start;
800 if (EscapedChar == '%') {
801 // Escaped percentage sign.
802 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000803 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000804 // Generate an unique ID.
805 Result += llvm::utostr(AsmCounter);
806 } else if (isdigit(EscapedChar)) {
807 // %n - Assembler operand n
808 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000809 unsigned long n = strtoul(Start, &End, 10);
810 if (Start == End) {
811 // FIXME: This should be caught during Sema.
812 assert(0 && "Missing operand!");
813 } else if (n >= NumOperands) {
814 // FIXME: This should be caught during Sema.
815 assert(0 && "Operand number out of range!");
816 }
817
818 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000819 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000820 } else if (isalpha(EscapedChar)) {
821 char *End;
822
823 unsigned long n = strtoul(Start + 1, &End, 10);
824 if (Start == End) {
825 // FIXME: This should be caught during Sema.
826 assert(0 && "Missing operand!");
827 } else if (n >= NumOperands) {
828 // FIXME: This should be caught during Sema.
829 assert(0 && "Operand number out of range!");
830 }
831
832 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000833 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000834 } else if (EscapedChar == '[') {
835 std::string SymbolicName;
836
837 Start++;
838
839 while (*Start && *Start != ']') {
840 SymbolicName += *Start;
841
842 Start++;
843 }
844
845 if (!Start) {
846 // FIXME: Should be caught by sema.
847 assert(0 && "Could not parse symbolic name");
848 }
849
850 assert(*Start == ']' && "Error parsing symbolic name");
851
852 int Index = -1;
853
854 // Check if this is an output operand.
855 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
856 if (S.getOutputName(i) == SymbolicName) {
857 Index = i;
858 break;
859 }
860 }
861
862 if (Index == -1) {
863 for (unsigned i = 0; i < S.getNumInputs(); i++) {
864 if (S.getInputName(i) == SymbolicName) {
865 Index = S.getNumOutputs() + i;
866 }
867 }
868 }
869
870 assert(Index != -1 && "Did not find right operand!");
871
872 Result += '$' + llvm::utostr(Index);
873
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000874 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000875 Failed = true;
876 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000877 }
878 }
879 Start++;
880 }
881
882 return Result;
883}
884
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000885static std::string SimplifyConstraint(const char* Constraint,
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000886 TargetInfo &Target,
887 const std::string *OutputNamesBegin = 0,
888 const std::string *OutputNamesEnd = 0)
889{
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000890 std::string Result;
891
892 while (*Constraint) {
893 switch (*Constraint) {
894 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000895 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000896 break;
897 // Ignore these
898 case '*':
899 case '?':
900 case '!':
901 break;
902 case 'g':
903 Result += "imr";
904 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000905 case '[': {
906 assert(OutputNamesBegin && OutputNamesEnd &&
907 "Must pass output names to constraints with a symbolic name");
908 unsigned Index;
909 bool result = Target.resolveSymbolicName(Constraint,
910 OutputNamesBegin,
911 OutputNamesEnd, Index);
Chris Lattner53637652009-01-21 07:35:26 +0000912 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000913 Result += llvm::utostr(Index);
914 break;
915 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000916 }
917
918 Constraint++;
919 }
920
921 return Result;
922}
923
Anders Carlsson63471722009-01-11 19:32:54 +0000924llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
925 TargetInfo::ConstraintInfo Info,
926 const Expr *InputExpr,
927 std::string &ConstraintStr)
928{
929 llvm::Value *Arg;
930 if ((Info & TargetInfo::CI_AllowsRegister) ||
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000931 !(Info & TargetInfo::CI_AllowsMemory)) {
932 const llvm::Type *Ty = ConvertType(InputExpr->getType());
933
934 if (Ty->isSingleValueType()) {
Anders Carlsson63471722009-01-11 19:32:54 +0000935 Arg = EmitScalarExpr(InputExpr);
936 } else {
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000937 LValue Dest = EmitLValue(InputExpr);
938
939 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
940 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
941 Ty = llvm::IntegerType::get(Size);
942 Ty = llvm::PointerType::getUnqual(Ty);
943
944 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
945 } else {
946 Arg = Dest.getAddress();
947 ConstraintStr += '*';
948 }
Anders Carlsson63471722009-01-11 19:32:54 +0000949 }
950 } else {
951 LValue Dest = EmitLValue(InputExpr);
952 Arg = Dest.getAddress();
953 ConstraintStr += '*';
954 }
955
956 return Arg;
957}
958
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000959void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000960 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000961 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000962 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000963
964 if (Failed) {
965 ErrorUnsupported(&S, "asm string");
966 return;
967 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000968
969 std::string Constraints;
970
971 llvm::Value *ResultAddr = 0;
972 const llvm::Type *ResultType = llvm::Type::VoidTy;
973
974 std::vector<const llvm::Type*> ArgTypes;
975 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000976
977 // Keep track of inout constraints.
978 std::string InOutConstraints;
979 std::vector<llvm::Value*> InOutArgs;
980 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +0000981
982 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
983
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000984 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
985 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
986 S.getOutputConstraint(i)->getByteLength());
987
988 TargetInfo::ConstraintInfo Info;
989 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
990 Info);
Chris Lattner3304e552008-10-12 00:31:50 +0000991 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000992
Anders Carlsson03eb5432009-01-27 20:38:24 +0000993 OutputConstraintInfos.push_back(Info);
994
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000995 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000996 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000997
998 LValue Dest = EmitLValue(S.getOutputExpr(i));
999 const llvm::Type *DestValueType =
1000 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
1001
1002 // If the first output operand is not a memory dest, we'll
1003 // make it the return value.
1004 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +00001005 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001006 ResultAddr = Dest.getAddress();
1007 ResultType = DestValueType;
1008 Constraints += "=" + OutputConstraint;
1009 } else {
1010 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +00001011 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001012 if (i != 0)
1013 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +00001014 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001015 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001016 }
1017
1018 if (Info & TargetInfo::CI_ReadWrite) {
Anders Carlssonf39a4212008-02-05 20:01:53 +00001019 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +00001020
Anders Carlssonf39a4212008-02-05 20:01:53 +00001021 const Expr *InputExpr = S.getOutputExpr(i);
Anders Carlsson63471722009-01-11 19:32:54 +00001022 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001023
Anders Carlsson9f2505b2009-01-11 21:23:27 +00001024 if (Info & TargetInfo::CI_AllowsRegister)
1025 InOutConstraints += llvm::utostr(i);
1026 else
1027 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +00001028
Anders Carlssonf39a4212008-02-05 20:01:53 +00001029 InOutArgTypes.push_back(Arg->getType());
1030 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001031 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001032 }
1033
1034 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1035
1036 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1037 const Expr *InputExpr = S.getInputExpr(i);
1038
1039 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
1040 S.getInputConstraint(i)->getByteLength());
1041
1042 TargetInfo::ConstraintInfo Info;
1043 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Anders Carlsson45b050e2009-01-17 23:36:15 +00001044 S.begin_output_names(),
1045 S.end_output_names(),
Anders Carlsson03eb5432009-01-27 20:38:24 +00001046 &OutputConstraintInfos[0],
Chris Lattner53637652009-01-21 07:35:26 +00001047 Info); result=result;
Anders Carlsson42e1ee02009-01-18 01:56:57 +00001048 assert(result && "Failed to parse input constraint");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001049
1050 if (i != 0 || S.getNumOutputs() > 0)
1051 Constraints += ',';
1052
1053 // Simplify the input constraint.
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001054 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
1055 S.begin_output_names(),
1056 S.end_output_names());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001057
Anders Carlsson63471722009-01-11 19:32:54 +00001058 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001059
1060 ArgTypes.push_back(Arg->getType());
1061 Args.push_back(Arg);
1062 Constraints += InputConstraint;
1063 }
1064
Anders Carlssonf39a4212008-02-05 20:01:53 +00001065 // Append the "input" part of inout constraints last.
1066 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1067 ArgTypes.push_back(InOutArgTypes[i]);
1068 Args.push_back(InOutArgs[i]);
1069 }
1070 Constraints += InOutConstraints;
1071
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001072 // Clobbers
1073 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1074 std::string Clobber(S.getClobber(i)->getStrData(),
1075 S.getClobber(i)->getByteLength());
1076
1077 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
1078
Anders Carlssonea041752008-02-06 00:11:32 +00001079 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001080 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +00001081
1082 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001083 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001084 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001085 }
1086
1087 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +00001088 std::string MachineClobbers = Target.getClobbers();
1089 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001090 if (!Constraints.empty())
1091 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00001092 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001093 }
Anders Carlssonf39a4212008-02-05 20:01:53 +00001094
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001095 const llvm::FunctionType *FTy =
1096 llvm::FunctionType::get(ResultType, ArgTypes, false);
1097
1098 llvm::InlineAsm *IA =
1099 llvm::InlineAsm::get(FTy, AsmString, Constraints,
1100 S.isVolatile() || S.getNumOutputs() == 0);
1101 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +00001102 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001103 Builder.CreateStore(Result, ResultAddr);
1104}