blob: fc7a7c7f8f1e4d38aa1b6e7ddf043e484cd5e0bd [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) {
Anders Carlssonc71c8452009-02-07 23:50:39 +0000126
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 Carlssonc71c8452009-02-07 23:50:39 +0000134 // Keep track of the current cleanup stack depth.
135 size_t CleanupStackDepth = CleanupEntries.size();
136
Anders Carlsson17d28a32008-12-12 05:52:00 +0000137 // Push a null stack save value.
138 StackSaveValues.push_back(0);
139
Chris Lattner33793202007-08-31 22:09:40 +0000140 for (CompoundStmt::const_body_iterator I = S.body_begin(),
141 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000143
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000144 if (DI) {
Daniel Dunbara448fb22008-11-11 23:11:34 +0000145 EnsureInsertPoint();
Daniel Dunbar66031a52008-10-17 16:15:48 +0000146 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta1c6a38b2008-05-25 05:15:42 +0000147 DI->EmitRegionEnd(CurFn, Builder);
148 }
149
Anders Carlsson17d28a32008-12-12 05:52:00 +0000150 RValue RV;
151 if (!GetLast)
152 RV = RValue::get(0);
153 else {
154 // We have to special case labels here. They are statements, but when put
155 // at the end of a statement expression, they yield the value of their
156 // subexpression. Handle this by walking through all labels we encounter,
157 // emitting them before we evaluate the subexpr.
158 const Stmt *LastStmt = S.body_back();
159 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
160 EmitLabel(*LS);
161 LastStmt = LS->getSubStmt();
162 }
Chris Lattner9b655512007-08-31 22:49:20 +0000163
Anders Carlsson17d28a32008-12-12 05:52:00 +0000164 EnsureInsertPoint();
165
166 RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
167 }
168
169 if (llvm::Value *V = StackSaveValues.pop_back_val()) {
Mike Stump36a2ada2009-02-07 12:52:26 +0000170 StackDepth = V;
Anders Carlsson17d28a32008-12-12 05:52:00 +0000171 V = Builder.CreateLoad(V, "tmp");
172
173 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
174 Builder.CreateCall(F, V);
Chris Lattner91d723d2008-07-26 20:23:23 +0000175 }
176
Anders Carlssonc71c8452009-02-07 23:50:39 +0000177 EmitCleanupBlocks(CleanupStackDepth);
178
Anders Carlsson17d28a32008-12-12 05:52:00 +0000179 return RV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000180}
181
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000182void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbard57a8712008-11-11 09:41:28 +0000183 // Fall out of the current block (if necessary).
184 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000185
186 if (IsFinished && BB->use_empty()) {
187 delete BB;
188 return;
189 }
190
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 CurFn->getBasicBlockList().push_back(BB);
192 Builder.SetInsertPoint(BB);
193}
194
Mike Stump36a2ada2009-02-07 12:52:26 +0000195void CodeGenFunction::EmitStackUpdate(const LabelStmt &S) {
196 if (StackDepthMap.find(&S) == StackDepthMap.end()) {
197 // If we can't find it, just remember the depth now,
198 // so we can validate it later.
199 // FIXME: We need to save a place to insert the adjustment,
200 // if needed, here, sa that later in EmitLabel, we can
201 // backpatch the adjustment into that place, instead of
202 // saying unsupported.
203 StackDepthMap[&S] = StackDepth;
204 return;
205 }
206
207 // Find applicable stack depth, if any...
208 llvm::Value *V = StackDepthMap[&S];
209 // V can be 0 here, if it is, be sure to start searching from the
210 // top of the function, as we want the next save after that point.
211 for (unsigned int i = 0; i < StackSaveValues.size(); ++i)
212 if (StackSaveValues[i] == V) {
213 // The actual depth is actually in the next used slot, if any.
214 while (++i < StackSaveValues.size()
215 && (V = StackSaveValues[i]) == 0) ;
216 // If there were no other depth changes, we don't need any
217 // adjustments.
218 if (V) {
219 V = Builder.CreateLoad(V, "tmp");
220 // and restore it.
221 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
222 Builder.CreateCall(F, V);
223 }
224 } else
225 // FIXME: Move to semq and assert here, codegen isn't the right
226 // time to be checking.
227 CGM.ErrorUnsupported(&S, "invalid goto to VLA scope that has finished");
228}
229
Daniel Dunbard57a8712008-11-11 09:41:28 +0000230void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
231 // Emit a branch from the current block to the target one if this
232 // was a real block. If this was just a fall-through block after a
233 // terminator, don't emit it.
234 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
235
236 if (!CurBB || CurBB->getTerminator()) {
237 // If there is no insert point or the previous block is already
238 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000239 } else {
240 // Otherwise, create a fall-through branch.
241 Builder.CreateBr(Target);
242 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000243
244 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000245}
246
Chris Lattner91d723d2008-07-26 20:23:23 +0000247void CodeGenFunction::EmitLabel(const LabelStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000249 if (StackDepthMap.find(&S) == StackDepthMap.end()) {
250 // We need to remember the stack depth so that we can readjust the
251 // stack back to the right depth for this label if we want to
252 // transfer here from a different depth.
253 StackDepthMap[&S] = StackDepth;
254 } else {
255 if (StackDepthMap[&S] != StackDepth) {
256 // FIXME: Sema needs to ckeck for jumps that cross decls with
257 // initializations for C++, and all VLAs, not just the first in
258 // a block that does a stacksave.
259 // FIXME: We need to save a place to insert the adjustment
260 // when we do a EmitStackUpdate on a forward jump, and then
261 // backpatch the adjustment into that place.
262 CGM.ErrorUnsupported(&S, "forward goto inside scope with VLA");
263 }
264 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000265 EmitBlock(NextBB);
Chris Lattner91d723d2008-07-26 20:23:23 +0000266}
267
268
269void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
270 EmitLabel(S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000271 EmitStmt(S.getSubStmt());
272}
273
274void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000275 // FIXME: Implement goto out in @try or @catch blocks.
276 if (!ObjCEHStack.empty()) {
277 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
278 return;
279 }
280
Daniel Dunbar09124252008-11-12 08:21:33 +0000281 // If this code is reachable then emit a stop point (if generating
282 // debug info). We have to do this ourselves because we are on the
283 // "simple" statement path.
284 if (HaveInsertPoint())
285 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000286
287 // We need to adjust the stack, if the destination was (will be) at
288 // a different depth.
289 EmitStackUpdate(*S.getLabel());
290
Daniel Dunbard57a8712008-11-11 09:41:28 +0000291 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000292}
293
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000294void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbara4275d12008-10-02 18:02:06 +0000295 // FIXME: Implement indirect goto in @try or @catch blocks.
296 if (!ObjCEHStack.empty()) {
297 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
298 return;
299 }
300
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000301 // Emit initial switch which will be patched up later by
302 // EmitIndirectSwitches(). We need a default dest, so we use the
303 // current BB, but this is overwritten.
304 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
305 llvm::Type::Int32Ty,
306 "addr");
307 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
308 IndirectSwitches.push_back(I);
309
Daniel Dunbara448fb22008-11-11 23:11:34 +0000310 // Clear the insertion point to indicate we are in unreachable code.
311 Builder.ClearInsertionPoint();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000312}
313
Chris Lattner62b72f62008-11-11 07:24:28 +0000314void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000315 // C99 6.8.4.1: The first substatement is executed if the expression compares
316 // unequal to 0. The condition must be a scalar type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000317
Chris Lattner9bc47e22008-11-12 07:46:33 +0000318 // If the condition constant folds and can be elided, try to avoid emitting
319 // the condition and the dead arm of the if/else.
Chris Lattner31a09842008-11-12 08:04:58 +0000320 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000321 // Figure out which block (then or else) is executed.
322 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner9bc47e22008-11-12 07:46:33 +0000323 if (Cond == -1) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000324 std::swap(Executed, Skipped);
Chris Lattner9bc47e22008-11-12 07:46:33 +0000325
Chris Lattner62b72f62008-11-11 07:24:28 +0000326 // If the skipped block has no labels in it, just emit the executed block.
327 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner9bc47e22008-11-12 07:46:33 +0000328 if (!ContainsLabel(Skipped)) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000329 if (Executed)
330 EmitStmt(Executed);
331 return;
332 }
333 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000334
335 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
336 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000337 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
338 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
339 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000341 ElseBlock = createBasicBlock("if.else");
342 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000343
344 // Emit the 'then' code.
345 EmitBlock(ThenBlock);
346 EmitStmt(S.getThen());
Daniel Dunbard57a8712008-11-11 09:41:28 +0000347 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000348
349 // Emit the 'else' code if present.
350 if (const Stmt *Else = S.getElse()) {
351 EmitBlock(ElseBlock);
352 EmitStmt(Else);
Daniel Dunbard57a8712008-11-11 09:41:28 +0000353 EmitBranch(ContBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000354 }
355
356 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000357 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000358}
359
360void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 // Emit the header for the loop, insert it, which will create an uncond br to
362 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000363 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Reid Spencer5f016e22007-07-11 17:01:13 +0000364 EmitBlock(LoopHeader);
Mike Stump72cac2c2009-02-07 18:08:12 +0000365
366 // Create an exit block for when the condition fails, create a block for the
367 // body of the loop.
368 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
369 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
370
371 // Store the blocks to use for break and continue.
372 BreakContinuePush(ExitBlock, LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000373
Mike Stump16b16202009-02-07 17:18:33 +0000374 // Evaluate the conditional in the while header. C99 6.8.5.1: The
375 // evaluation of the controlling expression takes place before each
376 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000377 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel2c30d8f2007-10-09 20:51:27 +0000378
379 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000380 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000381 bool EmitBoolCondBranch = true;
382 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
383 if (C->isOne())
384 EmitBoolCondBranch = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000385
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 // As long as the condition is true, go to the loop body.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000387 if (EmitBoolCondBranch)
388 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000389
Reid Spencer5f016e22007-07-11 17:01:13 +0000390 // Emit the loop body.
391 EmitBlock(LoopBody);
392 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000393
Mike Stump36a2ada2009-02-07 12:52:26 +0000394 BreakContinuePop();
Reid Spencer5f016e22007-07-11 17:01:13 +0000395
396 // Cycle to the condition.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000397 EmitBranch(LoopHeader);
Reid Spencer5f016e22007-07-11 17:01:13 +0000398
399 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000400 EmitBlock(ExitBlock, true);
Devang Patel2c30d8f2007-10-09 20:51:27 +0000401
402 // If LoopHeader is a simple forwarding block then eliminate it.
403 if (!EmitBoolCondBranch
404 && &LoopHeader->front() == LoopHeader->getTerminator()) {
405 LoopHeader->replaceAllUsesWith(LoopBody);
406 LoopHeader->getTerminator()->eraseFromParent();
407 LoopHeader->eraseFromParent();
408 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000409}
410
411void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 // Emit the body for the loop, insert it, which will create an uncond br to
413 // it.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000414 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
415 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Reid Spencer5f016e22007-07-11 17:01:13 +0000416 EmitBlock(LoopBody);
Chris Lattnerda138702007-07-16 21:28:45 +0000417
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000418 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattnerda138702007-07-16 21:28:45 +0000419
420 // Store the blocks to use for break and continue.
Mike Stump36a2ada2009-02-07 12:52:26 +0000421 BreakContinuePush(AfterDo, DoCond);
Reid Spencer5f016e22007-07-11 17:01:13 +0000422
423 // Emit the body of the loop into the block.
424 EmitStmt(S.getBody());
425
Mike Stump36a2ada2009-02-07 12:52:26 +0000426 BreakContinuePop();
Chris Lattnerda138702007-07-16 21:28:45 +0000427
428 EmitBlock(DoCond);
429
Reid Spencer5f016e22007-07-11 17:01:13 +0000430 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
431 // after each execution of the loop body."
432
433 // Evaluate the conditional in the while header.
434 // C99 6.8.5p2/p4: The first substatement is executed if the expression
435 // compares unequal to 0. The condition must be a scalar type.
436 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000437
438 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
439 // to correctly handle break/continue though.
440 bool EmitBoolCondBranch = true;
441 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
442 if (C->isZero())
443 EmitBoolCondBranch = false;
444
Reid Spencer5f016e22007-07-11 17:01:13 +0000445 // As long as the condition is true, iterate the loop.
Devang Patel05f6e6b2007-10-09 20:33:39 +0000446 if (EmitBoolCondBranch)
447 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Reid Spencer5f016e22007-07-11 17:01:13 +0000448
449 // Emit the exit block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000450 EmitBlock(AfterDo, true);
Devang Patel05f6e6b2007-10-09 20:33:39 +0000451
452 // If DoCond is a simple forwarding block then eliminate it.
453 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
454 DoCond->replaceAllUsesWith(AfterDo);
455 DoCond->getTerminator()->eraseFromParent();
456 DoCond->eraseFromParent();
457 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000458}
459
460void CodeGenFunction::EmitForStmt(const ForStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000461 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
462 // which contains a continue/break?
Chris Lattnerda138702007-07-16 21:28:45 +0000463
Reid Spencer5f016e22007-07-11 17:01:13 +0000464 // Evaluate the first part before the loop.
465 if (S.getInit())
466 EmitStmt(S.getInit());
467
468 // Start the loop with a block that tests the condition.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000469 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
470 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattnerda138702007-07-16 21:28:45 +0000471
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 EmitBlock(CondBlock);
473
Mike Stump3e9da662009-02-07 23:02:10 +0000474 llvm::Value *saveStackDepth = StackDepth;
475
Mike Stump20926c62009-02-07 20:14:12 +0000476 // Evaluate the condition if present. If not, treat it as a
477 // non-zero-constant according to 6.8.5.3p2, aka, true.
Reid Spencer5f016e22007-07-11 17:01:13 +0000478 if (S.getCond()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000479 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000480 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner31a09842008-11-12 08:04:58 +0000481
482 // C99 6.8.5p2/p4: The first substatement is executed if the expression
483 // compares unequal to 0. The condition must be a scalar type.
484 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
485
Reid Spencer5f016e22007-07-11 17:01:13 +0000486 EmitBlock(ForBody);
487 } else {
488 // Treat it as a non-zero constant. Don't even create a new block for the
489 // body, just fall into it.
490 }
491
Chris Lattnerda138702007-07-16 21:28:45 +0000492 // If the for loop doesn't have an increment we can just use the
493 // condition as the continue block.
494 llvm::BasicBlock *ContinueBlock;
495 if (S.getInc())
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000496 ContinueBlock = createBasicBlock("for.inc");
Chris Lattnerda138702007-07-16 21:28:45 +0000497 else
498 ContinueBlock = CondBlock;
499
500 // Store the blocks to use for break and continue.
Mike Stump3e9da662009-02-07 23:02:10 +0000501 // Ensure any vlas created between there and here, are undone
502 BreakContinuePush(AfterFor, ContinueBlock,
503 saveStackDepth, saveStackDepth);
504
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 // If the condition is true, execute the body of the for stmt.
506 EmitStmt(S.getBody());
Chris Lattnerda138702007-07-16 21:28:45 +0000507
Mike Stump36a2ada2009-02-07 12:52:26 +0000508 BreakContinuePop();
Chris Lattnerda138702007-07-16 21:28:45 +0000509
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000511 if (S.getInc()) {
512 EmitBlock(ContinueBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000513 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000514 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000515
516 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000517 EmitBranch(CondBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000518
Chris Lattnerda138702007-07-16 21:28:45 +0000519 // Emit the fall-through block.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000520 EmitBlock(AfterFor, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000521}
522
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000523void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
524 if (RV.isScalar()) {
525 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
526 } else if (RV.isAggregate()) {
527 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
528 } else {
529 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
530 }
Daniel Dunbard57a8712008-11-11 09:41:28 +0000531 EmitBranch(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000532}
533
Reid Spencer5f016e22007-07-11 17:01:13 +0000534/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
535/// if the function returns void, or may be missing one if the function returns
536/// non-void. Fun stuff :).
537void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Eli Friedman20c802b2008-12-20 23:18:29 +0000538 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
Anders Carlsson7e63b852008-12-20 21:33:38 +0000539 if (StackSaveValues[i]) {
540 CGM.ErrorUnsupported(&S, "return inside scope with VLA");
541 return;
542 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000543 }
544
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 // Emit the result value, even if unused, to evalute the side effects.
546 const Expr *RV = S.getRetValue();
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000547
548 // FIXME: Clean this up by using an LValue for ReturnTemp,
549 // EmitStoreThroughLValue, and EmitAnyExpr.
550 if (!ReturnValue) {
551 // Make sure not to return anything, but evaluate the expression
552 // for side effects.
553 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +0000554 EmitAnyExpr(RV);
Reid Spencer5f016e22007-07-11 17:01:13 +0000555 } else if (RV == 0) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000556 // Do nothing (return value is left uninitialized)
Chris Lattner4b0029d2007-08-26 07:14:44 +0000557 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000558 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattner9b2dc282008-04-04 16:54:41 +0000559 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000560 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 } else {
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000562 EmitAggExpr(RV, ReturnValue, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000563 }
Eli Friedman144ac612008-05-22 01:22:33 +0000564
Daniel Dunbar898d5082008-09-30 01:06:03 +0000565 if (!ObjCEHStack.empty()) {
566 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
567 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar55e87422008-11-11 02:29:29 +0000568 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbar898d5082008-09-30 01:06:03 +0000569 EmitJumpThroughFinally(*i, ReturnPad);
570 EmitBlock(ReturnPad);
571 }
572 }
573
Daniel Dunbard57a8712008-11-11 09:41:28 +0000574 EmitBranch(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +0000575}
576
577void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneke4ea1f42008-10-06 18:42:27 +0000578 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
579 I != E; ++I)
580 EmitDecl(**I);
Chris Lattner6fa5f092007-07-12 15:43:07 +0000581}
Chris Lattnerda138702007-07-16 21:28:45 +0000582
Daniel Dunbar09124252008-11-12 08:21:33 +0000583void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000584 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
585
Daniel Dunbar09124252008-11-12 08:21:33 +0000586 // FIXME: Implement break in @try or @catch blocks.
Anders Carlssone21269b2008-12-13 22:52:24 +0000587 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000588 CGM.ErrorUnsupported(&S, "break inside an Obj-C exception block");
Daniel Dunbar09124252008-11-12 08:21:33 +0000589 return;
590 }
591
Eli Friedman20c802b2008-12-20 23:18:29 +0000592 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
593 if (StackSaveValues[i]) {
594 CGM.ErrorUnsupported(&S, "break inside scope with VLA");
595 return;
596 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000597 }
598
Daniel Dunbar09124252008-11-12 08:21:33 +0000599 // If this code is reachable then emit a stop point (if generating
600 // debug info). We have to do this ourselves because we are on the
601 // "simple" statement path.
602 if (HaveInsertPoint())
603 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000604 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000605 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000606}
607
Daniel Dunbar09124252008-11-12 08:21:33 +0000608void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +0000609 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
610
Daniel Dunbar09124252008-11-12 08:21:33 +0000611 // FIXME: Implement continue in @try or @catch blocks.
Anders Carlssone21269b2008-12-13 22:52:24 +0000612 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000613 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
614 return;
615 }
616
Eli Friedman20c802b2008-12-20 23:18:29 +0000617 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
618 if (StackSaveValues[i]) {
619 CGM.ErrorUnsupported(&S, "continue inside scope with VLA");
620 return;
621 }
Anders Carlssoneb91f0e2008-12-20 19:33:21 +0000622 }
623
Daniel Dunbar09124252008-11-12 08:21:33 +0000624 // If this code is reachable then emit a stop point (if generating
625 // debug info). We have to do this ourselves because we are on the
626 // "simple" statement path.
627 if (HaveInsertPoint())
628 EmitStopPoint(&S);
Chris Lattnerda138702007-07-16 21:28:45 +0000629 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbard57a8712008-11-11 09:41:28 +0000630 EmitBranch(Block);
Chris Lattnerda138702007-07-16 21:28:45 +0000631}
Devang Patel51b09f22007-10-04 23:45:31 +0000632
Devang Patelc049e4f2007-10-08 20:57:48 +0000633/// EmitCaseStmtRange - If case statement range is not too big then
634/// add multiple cases to switch instruction, one for each value within
635/// the range. If range is too big then emit "if" condition check.
636void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000637 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +0000638
Anders Carlsson51fe9962008-11-22 21:04:56 +0000639 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
640 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000641
Daniel Dunbar16f23572008-07-25 01:11:38 +0000642 // Emit the code for this case. We do this first to make sure it is
643 // properly chained from our predecessor before generating the
644 // switch machinery to enter this block.
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000645 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar16f23572008-07-25 01:11:38 +0000646 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
647 EmitStmt(S.getSubStmt());
648
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000649 // If range is empty, do nothing.
650 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
651 return;
Devang Patelc049e4f2007-10-08 20:57:48 +0000652
653 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +0000654 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +0000655 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
656 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000657 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patel2d79d0f2007-10-05 20:54:07 +0000658 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
659 LHS++;
660 }
Devang Patelc049e4f2007-10-08 20:57:48 +0000661 return;
662 }
663
Daniel Dunbar16f23572008-07-25 01:11:38 +0000664 // The range is too big. Emit "if" condition into a new block,
665 // making sure to save and restore the current insertion point.
666 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +0000667
Daniel Dunbar16f23572008-07-25 01:11:38 +0000668 // Push this test onto the chain of range checks (which terminates
669 // in the default basic block). The switch's default will be changed
670 // to the top of this chain after switch emission is complete.
671 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +0000672 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +0000673
Daniel Dunbar16f23572008-07-25 01:11:38 +0000674 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
675 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000676
677 // Emit range check.
678 llvm::Value *Diff =
Daniel Dunbar4efde8d2008-07-24 01:18:41 +0000679 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
680 "tmp");
Devang Patelc049e4f2007-10-08 20:57:48 +0000681 llvm::Value *Cond =
682 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
683 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
684
Daniel Dunbar16f23572008-07-25 01:11:38 +0000685 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +0000686 if (RestoreBB)
687 Builder.SetInsertPoint(RestoreBB);
688 else
689 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +0000690}
691
692void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
693 if (S.getRHS()) {
694 EmitCaseStmtRange(S);
695 return;
696 }
697
Daniel Dunbarf84dcda2008-11-11 04:12:31 +0000698 EmitBlock(createBasicBlock("sw.bb"));
Devang Patelc049e4f2007-10-08 20:57:48 +0000699 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlsson51fe9962008-11-22 21:04:56 +0000700 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Daniel Dunbar55e87422008-11-11 02:29:29 +0000701 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patel51b09f22007-10-04 23:45:31 +0000702 EmitStmt(S.getSubStmt());
703}
704
705void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +0000706 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar55e87422008-11-11 02:29:29 +0000707 assert(DefaultBlock->empty() &&
708 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000709 EmitBlock(DefaultBlock);
Devang Patel51b09f22007-10-04 23:45:31 +0000710 EmitStmt(S.getSubStmt());
711}
712
713void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
714 llvm::Value *CondV = EmitScalarExpr(S.getCond());
715
716 // Handle nested switch statements.
717 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000718 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000719
Mike Stump3e9da662009-02-07 23:02:10 +0000720 // Ensure any vlas created inside are destroyed on break.
721 llvm::Value *saveBreakStackDepth = StackDepth;
722
Daniel Dunbar16f23572008-07-25 01:11:38 +0000723 // Create basic block to hold stuff that comes after switch
724 // statement. We also need to create a default block now so that
725 // explicit case ranges tests can have a place to jump to on
726 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000727 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
728 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +0000729 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
730 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000731
Daniel Dunbar09124252008-11-12 08:21:33 +0000732 // Clear the insertion point to indicate we are in unreachable code.
733 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +0000734
Devang Patele9b8c0a2007-10-30 20:59:40 +0000735 // All break statements jump to NextBlock. If BreakContinueStack is non empty
736 // then reuse last ContinueBlock.
Devang Patel51b09f22007-10-04 23:45:31 +0000737 llvm::BasicBlock *ContinueBlock = NULL;
Mike Stump3e9da662009-02-07 23:02:10 +0000738 llvm::Value *saveContinueStackDepth = NULL;
739 if (!BreakContinueStack.empty()) {
Devang Patel51b09f22007-10-04 23:45:31 +0000740 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Mike Stump3e9da662009-02-07 23:02:10 +0000741 saveContinueStackDepth = BreakContinueStack.back().SaveContinueStackDepth;
742 }
743 // Ensure any vlas created between there and here, are undone
744 BreakContinuePush(NextBlock, ContinueBlock,
745 saveBreakStackDepth, saveContinueStackDepth);
Devang Patel51b09f22007-10-04 23:45:31 +0000746
747 // Emit switch body.
748 EmitStmt(S.getBody());
Mike Stump36a2ada2009-02-07 12:52:26 +0000749 BreakContinuePop();
Devang Patel51b09f22007-10-04 23:45:31 +0000750
Daniel Dunbar16f23572008-07-25 01:11:38 +0000751 // Update the default block in case explicit case range tests have
752 // been chained on top.
753 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +0000754
Daniel Dunbar16f23572008-07-25 01:11:38 +0000755 // If a default was never emitted then reroute any jumps to it and
756 // discard.
757 if (!DefaultBlock->getParent()) {
758 DefaultBlock->replaceAllUsesWith(NextBlock);
759 delete DefaultBlock;
760 }
Devang Patel51b09f22007-10-04 23:45:31 +0000761
Daniel Dunbar16f23572008-07-25 01:11:38 +0000762 // Emit continuation.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000763 EmitBlock(NextBlock, true);
Daniel Dunbar16f23572008-07-25 01:11:38 +0000764
Devang Patel51b09f22007-10-04 23:45:31 +0000765 SwitchInsn = SavedSwitchInsn;
Devang Patelc049e4f2007-10-08 20:57:48 +0000766 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +0000767}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000768
Anders Carlssonce179ab2008-11-09 18:54:14 +0000769static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
770{
771 // FIXME: No need to create new std::string here, we could just make sure
772 // that we don't read past the end of the string data.
773 std::string str(S.getAsmString()->getStrData(),
774 S.getAsmString()->getByteLength());
775 const char *Start = str.c_str();
776
777 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
778 bool IsSimple = S.isSimple();
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000779 Failed = false;
780
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000781 static unsigned AsmCounter = 0;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000782 AsmCounter++;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000783 std::string Result;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000784 if (IsSimple) {
785 while (*Start) {
786 switch (*Start) {
787 default:
788 Result += *Start;
789 break;
790 case '$':
791 Result += "$$";
792 break;
793 }
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000794 Start++;
795 }
796
797 return Result;
798 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000799
800 while (*Start) {
801 switch (*Start) {
802 default:
803 Result += *Start;
804 break;
805 case '$':
806 Result += "$$";
807 break;
808 case '%':
809 // Escaped character
810 Start++;
811 if (!*Start) {
812 // FIXME: This should be caught during Sema.
813 assert(0 && "Trailing '%' in asm string.");
814 }
815
816 char EscapedChar = *Start;
817 if (EscapedChar == '%') {
818 // Escaped percentage sign.
819 Result += '%';
Chris Lattner345f7202008-07-26 20:15:14 +0000820 } else if (EscapedChar == '=') {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000821 // Generate an unique ID.
822 Result += llvm::utostr(AsmCounter);
823 } else if (isdigit(EscapedChar)) {
824 // %n - Assembler operand n
825 char *End;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000826 unsigned long n = strtoul(Start, &End, 10);
827 if (Start == End) {
828 // FIXME: This should be caught during Sema.
829 assert(0 && "Missing operand!");
830 } else if (n >= NumOperands) {
831 // FIXME: This should be caught during Sema.
832 assert(0 && "Operand number out of range!");
833 }
834
835 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000836 Start = End - 1;
Anders Carlsson2abd25f2008-02-05 23:18:57 +0000837 } else if (isalpha(EscapedChar)) {
838 char *End;
839
840 unsigned long n = strtoul(Start + 1, &End, 10);
841 if (Start == End) {
842 // FIXME: This should be caught during Sema.
843 assert(0 && "Missing operand!");
844 } else if (n >= NumOperands) {
845 // FIXME: This should be caught during Sema.
846 assert(0 && "Operand number out of range!");
847 }
848
849 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancio7695f702008-02-26 19:19:58 +0000850 Start = End - 1;
Anders Carlssonce179ab2008-11-09 18:54:14 +0000851 } else if (EscapedChar == '[') {
852 std::string SymbolicName;
853
854 Start++;
855
856 while (*Start && *Start != ']') {
857 SymbolicName += *Start;
858
859 Start++;
860 }
861
862 if (!Start) {
863 // FIXME: Should be caught by sema.
864 assert(0 && "Could not parse symbolic name");
865 }
866
867 assert(*Start == ']' && "Error parsing symbolic name");
868
869 int Index = -1;
870
871 // Check if this is an output operand.
872 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
873 if (S.getOutputName(i) == SymbolicName) {
874 Index = i;
875 break;
876 }
877 }
878
879 if (Index == -1) {
880 for (unsigned i = 0; i < S.getNumInputs(); i++) {
881 if (S.getInputName(i) == SymbolicName) {
882 Index = S.getNumOutputs() + i;
883 }
884 }
885 }
886
887 assert(Index != -1 && "Did not find right operand!");
888
889 Result += '$' + llvm::utostr(Index);
890
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000891 } else {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000892 Failed = true;
893 return "";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000894 }
895 }
896 Start++;
897 }
898
899 return Result;
900}
901
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000902static std::string SimplifyConstraint(const char* Constraint,
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000903 TargetInfo &Target,
904 const std::string *OutputNamesBegin = 0,
905 const std::string *OutputNamesEnd = 0)
906{
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000907 std::string Result;
908
909 while (*Constraint) {
910 switch (*Constraint) {
911 default:
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +0000912 Result += Target.convertConstraint(*Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000913 break;
914 // Ignore these
915 case '*':
916 case '?':
917 case '!':
918 break;
919 case 'g':
920 Result += "imr";
921 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000922 case '[': {
923 assert(OutputNamesBegin && OutputNamesEnd &&
924 "Must pass output names to constraints with a symbolic name");
925 unsigned Index;
926 bool result = Target.resolveSymbolicName(Constraint,
927 OutputNamesBegin,
928 OutputNamesEnd, Index);
Chris Lattner53637652009-01-21 07:35:26 +0000929 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +0000930 Result += llvm::utostr(Index);
931 break;
932 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000933 }
934
935 Constraint++;
936 }
937
938 return Result;
939}
940
Anders Carlsson63471722009-01-11 19:32:54 +0000941llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
942 TargetInfo::ConstraintInfo Info,
943 const Expr *InputExpr,
944 std::string &ConstraintStr)
945{
946 llvm::Value *Arg;
947 if ((Info & TargetInfo::CI_AllowsRegister) ||
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000948 !(Info & TargetInfo::CI_AllowsMemory)) {
949 const llvm::Type *Ty = ConvertType(InputExpr->getType());
950
951 if (Ty->isSingleValueType()) {
Anders Carlsson63471722009-01-11 19:32:54 +0000952 Arg = EmitScalarExpr(InputExpr);
953 } else {
Anders Carlssonebaae2a2009-01-12 02:22:13 +0000954 LValue Dest = EmitLValue(InputExpr);
955
956 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
957 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
958 Ty = llvm::IntegerType::get(Size);
959 Ty = llvm::PointerType::getUnqual(Ty);
960
961 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
962 } else {
963 Arg = Dest.getAddress();
964 ConstraintStr += '*';
965 }
Anders Carlsson63471722009-01-11 19:32:54 +0000966 }
967 } else {
968 LValue Dest = EmitLValue(InputExpr);
969 Arg = Dest.getAddress();
970 ConstraintStr += '*';
971 }
972
973 return Arg;
974}
975
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000976void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000977 bool Failed;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000978 std::string AsmString =
Anders Carlssonce179ab2008-11-09 18:54:14 +0000979 ConvertAsmString(S, Failed);
Daniel Dunbar281f55c2008-10-17 20:58:01 +0000980
981 if (Failed) {
982 ErrorUnsupported(&S, "asm string");
983 return;
984 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +0000985
986 std::string Constraints;
987
988 llvm::Value *ResultAddr = 0;
989 const llvm::Type *ResultType = llvm::Type::VoidTy;
990
991 std::vector<const llvm::Type*> ArgTypes;
992 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +0000993
994 // Keep track of inout constraints.
995 std::string InOutConstraints;
996 std::vector<llvm::Value*> InOutArgs;
997 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +0000998
999 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1000
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001001 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1002 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
1003 S.getOutputConstraint(i)->getByteLength());
1004
1005 TargetInfo::ConstraintInfo Info;
1006 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
1007 Info);
Chris Lattner3304e552008-10-12 00:31:50 +00001008 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001009
Anders Carlsson03eb5432009-01-27 20:38:24 +00001010 OutputConstraintInfos.push_back(Info);
1011
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001012 // Simplify the output constraint.
Lauro Ramos Venancioa5694b82008-02-26 18:33:46 +00001013 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001014
1015 LValue Dest = EmitLValue(S.getOutputExpr(i));
1016 const llvm::Type *DestValueType =
1017 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
1018
1019 // If the first output operand is not a memory dest, we'll
1020 // make it the return value.
1021 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohmand79a7262008-05-22 22:12:56 +00001022 DestValueType->isSingleValueType()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001023 ResultAddr = Dest.getAddress();
1024 ResultType = DestValueType;
1025 Constraints += "=" + OutputConstraint;
1026 } else {
1027 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlssoncad3ab62008-02-05 16:57:38 +00001028 Args.push_back(Dest.getAddress());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001029 if (i != 0)
1030 Constraints += ',';
Anders Carlssonf39a4212008-02-05 20:01:53 +00001031 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001032 Constraints += OutputConstraint;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001033 }
1034
1035 if (Info & TargetInfo::CI_ReadWrite) {
Anders Carlssonf39a4212008-02-05 20:01:53 +00001036 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +00001037
Anders Carlssonf39a4212008-02-05 20:01:53 +00001038 const Expr *InputExpr = S.getOutputExpr(i);
Anders Carlsson63471722009-01-11 19:32:54 +00001039 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001040
Anders Carlsson9f2505b2009-01-11 21:23:27 +00001041 if (Info & TargetInfo::CI_AllowsRegister)
1042 InOutConstraints += llvm::utostr(i);
1043 else
1044 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +00001045
Anders Carlssonf39a4212008-02-05 20:01:53 +00001046 InOutArgTypes.push_back(Arg->getType());
1047 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001048 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001049 }
1050
1051 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1052
1053 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1054 const Expr *InputExpr = S.getInputExpr(i);
1055
1056 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
1057 S.getInputConstraint(i)->getByteLength());
1058
1059 TargetInfo::ConstraintInfo Info;
1060 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Anders Carlsson45b050e2009-01-17 23:36:15 +00001061 S.begin_output_names(),
1062 S.end_output_names(),
Anders Carlsson03eb5432009-01-27 20:38:24 +00001063 &OutputConstraintInfos[0],
Chris Lattner53637652009-01-21 07:35:26 +00001064 Info); result=result;
Anders Carlsson42e1ee02009-01-18 01:56:57 +00001065 assert(result && "Failed to parse input constraint");
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001066
1067 if (i != 0 || S.getNumOutputs() > 0)
1068 Constraints += ',';
1069
1070 // Simplify the input constraint.
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001071 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
1072 S.begin_output_names(),
1073 S.end_output_names());
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001074
Anders Carlsson63471722009-01-11 19:32:54 +00001075 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001076
1077 ArgTypes.push_back(Arg->getType());
1078 Args.push_back(Arg);
1079 Constraints += InputConstraint;
1080 }
1081
Anders Carlssonf39a4212008-02-05 20:01:53 +00001082 // Append the "input" part of inout constraints last.
1083 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1084 ArgTypes.push_back(InOutArgTypes[i]);
1085 Args.push_back(InOutArgs[i]);
1086 }
1087 Constraints += InOutConstraints;
1088
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001089 // Clobbers
1090 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1091 std::string Clobber(S.getClobber(i)->getStrData(),
1092 S.getClobber(i)->getByteLength());
1093
1094 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
1095
Anders Carlssonea041752008-02-06 00:11:32 +00001096 if (i != 0 || NumConstraints != 0)
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001097 Constraints += ',';
Anders Carlssonea041752008-02-06 00:11:32 +00001098
1099 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001100 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00001101 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001102 }
1103
1104 // Add machine specific clobbers
Eli Friedmanccf614c2008-12-21 01:15:32 +00001105 std::string MachineClobbers = Target.getClobbers();
1106 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001107 if (!Constraints.empty())
1108 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00001109 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001110 }
Anders Carlssonf39a4212008-02-05 20:01:53 +00001111
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001112 const llvm::FunctionType *FTy =
1113 llvm::FunctionType::get(ResultType, ArgTypes, false);
1114
1115 llvm::InlineAsm *IA =
1116 llvm::InlineAsm::get(FTy, AsmString, Constraints,
1117 S.isVolatile() || S.getNumOutputs() == 0);
1118 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman1e692ac2008-06-13 23:01:12 +00001119 if (ResultAddr) // FIXME: volatility
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001120 Builder.CreateStore(Result, ResultAddr);
1121}