blob: 4c634efb1064f9b251e7c02862335ab3ea8cb427 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Stmt nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
15#include "CodeGenModule.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "CodeGenFunction.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000017#include "clang/AST/StmtVisitor.h"
Anders Carlssonaf6a6c22008-02-05 16:35:33 +000018#include "clang/Basic/TargetInfo.h"
Anders Carlssonaf6a6c22008-02-05 16:35:33 +000019#include "llvm/ADT/StringExtras.h"
Anders Carlsson438ddd82008-12-12 05:52:00 +000020#include "llvm/InlineAsm.h"
21#include "llvm/Intrinsics.h"
Anders Carlssonfc12cfe2009-01-12 02:22:13 +000022#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023using namespace clang;
24using namespace CodeGen;
25
26//===----------------------------------------------------------------------===//
27// Statement Emission
28//===----------------------------------------------------------------------===//
29
Daniel Dunbar6c81e562008-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
Chris Lattner4b009652007-07-25 00:24:17 +000037void CodeGenFunction::EmitStmt(const Stmt *S) {
38 assert(S && "Null statement?");
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +000039
Daniel Dunbar6c81e562008-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 Dunbar5aa22bc2008-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();
Chris Lattner4b009652007-07-25 00:24:17 +000051
Daniel Dunbar6c81e562008-11-12 08:21:33 +000052 // Generate a stoppoint if we are emitting debug info.
53 EmitStopPoint(S);
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000054
Chris Lattner4b009652007-07-25 00:24:17 +000055 switch (S->getStmtClass()) {
56 default:
Chris Lattner35055b82007-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.
Chris Lattner4b009652007-07-25 00:24:17 +000059 if (const Expr *E = dyn_cast<Expr>(S)) {
Chris Lattner35055b82007-08-26 22:58:05 +000060 if (!hasAggregateLLVMType(E->getType()))
61 EmitScalarExpr(E);
Chris Lattnerde0908b2008-04-04 16:54:41 +000062 else if (E->getType()->isAnyComplexType())
Chris Lattner35055b82007-08-26 22:58:05 +000063 EmitComplexExpr(E);
64 else
65 EmitAggExpr(E, 0, false);
Chris Lattner4b009652007-07-25 00:24:17 +000066 } else {
Daniel Dunbar9503b782008-08-16 00:56:44 +000067 ErrorUnsupported(S, "statement");
Chris Lattner4b009652007-07-25 00:24:17 +000068 }
69 break;
Daniel Dunbar879788d2008-08-04 16:51:22 +000070 case Stmt::IndirectGotoStmtClass:
71 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Chris Lattner4b009652007-07-25 00:24:17 +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 Dunbar66e021e2008-10-02 18:02:06 +000080
Devang Patele58e0802007-10-04 23:45:31 +000081 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +000082 case Stmt::AsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Daniel Dunbar5e105892008-08-23 10:51:21 +000083
84 case Stmt::ObjCAtTryStmtClass:
Anders Carlssonb01a2112008-09-09 10:04:29 +000085 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
86 break;
Daniel Dunbar5e105892008-08-23 10:51:21 +000087 case Stmt::ObjCAtCatchStmtClass:
Anders Carlsson75d86732008-09-11 09:15:33 +000088 assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
89 break;
Daniel Dunbar5e105892008-08-23 10:51:21 +000090 case Stmt::ObjCAtFinallyStmtClass:
Anders Carlssonb01a2112008-09-09 10:04:29 +000091 assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar5e105892008-08-23 10:51:21 +000092 break;
93 case Stmt::ObjCAtThrowStmtClass:
Anders Carlssonb01a2112008-09-09 10:04:29 +000094 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar5e105892008-08-23 10:51:21 +000095 break;
96 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattnerdd978702008-11-15 21:26:17 +000097 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar5e105892008-08-23 10:51:21 +000098 break;
Anders Carlsson82b0d0c2008-08-30 19:51:14 +000099 case Stmt::ObjCForCollectionStmtClass:
100 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar5e105892008-08-23 10:51:21 +0000101 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000102 }
103}
104
Daniel Dunbar6c81e562008-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 Lattnerea6cdd72007-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 Lattnere24c4cf2007-08-31 22:49:20 +0000124RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
125 llvm::Value *AggLoc, bool isAggVol) {
Anders Carlsson883fa552009-02-07 23:50:39 +0000126
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000127 CGDebugInfo *DI = CGM.getDebugInfo();
128 if (DI) {
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000129 EnsureInsertPoint();
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000130 DI->setLocation(S.getLBracLoc());
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000131 DI->EmitRegionStart(CurFn, Builder);
132 }
133
Anders Carlsson883fa552009-02-07 23:50:39 +0000134 // Keep track of the current cleanup stack depth.
135 size_t CleanupStackDepth = CleanupEntries.size();
136
Anders Carlsson438ddd82008-12-12 05:52:00 +0000137 // Push a null stack save value.
138 StackSaveValues.push_back(0);
139
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000140 for (CompoundStmt::const_body_iterator I = S.body_begin(),
141 E = S.body_end()-GetLast; I != E; ++I)
Chris Lattner4b009652007-07-25 00:24:17 +0000142 EmitStmt(*I);
Sanjiv Gupta40e56a12008-05-08 08:54:20 +0000143
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000144 if (DI) {
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +0000145 EnsureInsertPoint();
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000146 DI->setLocation(S.getRBracLoc());
Sanjiv Gupta93eb8252008-05-25 05:15:42 +0000147 DI->EmitRegionEnd(CurFn, Builder);
148 }
149
Anders Carlsson438ddd82008-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 Lattnere24c4cf2007-08-31 22:49:20 +0000163
Anders Carlsson438ddd82008-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 Stump88ad9112009-02-07 12:52:26 +0000170 StackDepth = V;
Anders Carlsson438ddd82008-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 Lattner09cee852008-07-26 20:23:23 +0000175 }
176
Anders Carlsson883fa552009-02-07 23:50:39 +0000177 EmitCleanupBlocks(CleanupStackDepth);
178
Anders Carlsson438ddd82008-12-12 05:52:00 +0000179 return RV;
Chris Lattner4b009652007-07-25 00:24:17 +0000180}
181
Daniel Dunbare2202612008-11-13 01:24:05 +0000182void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000183 // Fall out of the current block (if necessary).
184 EmitBranch(BB);
Daniel Dunbare2202612008-11-13 01:24:05 +0000185
186 if (IsFinished && BB->use_empty()) {
187 delete BB;
188 return;
189 }
190
Anders Carlssone7de3522009-02-08 00:16:35 +0000191 // If necessary, associate the block with the cleanup stack size.
192 if (!CleanupEntries.empty()) {
193 BlockScopes[BB] = CleanupEntries.size() - 1;
194 CleanupEntries.back().Blocks.push_back(BB);
195 }
196
Chris Lattner4b009652007-07-25 00:24:17 +0000197 CurFn->getBasicBlockList().push_back(BB);
198 Builder.SetInsertPoint(BB);
199}
200
Mike Stump7e39f182009-02-08 09:22:19 +0000201bool CodeGenFunction::EmitStackUpdate(llvm::Value *V) {
Mike Stump2be787c2009-02-08 22:00:53 +0000202 // If we're already at the depth we want...
203 if (StackDepth == V)
204 return false;
205
Mike Stump88ad9112009-02-07 12:52:26 +0000206 // V can be 0 here, if it is, be sure to start searching from the
207 // top of the function, as we want the next save after that point.
208 for (unsigned int i = 0; i < StackSaveValues.size(); ++i)
209 if (StackSaveValues[i] == V) {
210 // The actual depth is actually in the next used slot, if any.
211 while (++i < StackSaveValues.size()
212 && (V = StackSaveValues[i]) == 0) ;
213 // If there were no other depth changes, we don't need any
214 // adjustments.
215 if (V) {
216 V = Builder.CreateLoad(V, "tmp");
217 // and restore it.
218 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
219 Builder.CreateCall(F, V);
220 }
Mike Stump7e39f182009-02-08 09:22:19 +0000221 } else return true;
222 return false;
223}
224
225bool CodeGenFunction::EmitStackUpdate(const void *S) {
226 if (StackDepthMap.find(S) == StackDepthMap.end()) {
227 // If we can't find it, just remember the depth now,
228 // so we can validate it later.
229 // FIXME: We need to save a place to insert the adjustment,
230 // if needed, here, sa that later in EmitLabel, we can
231 // backpatch the adjustment into that place, instead of
232 // saying unsupported.
233 StackDepthMap[S] = StackDepth;
234 return false;
235 }
236
237 // Find applicable stack depth, if any...
238 llvm::Value *V = StackDepthMap[S];
239 return EmitStackUpdate(V);
Mike Stump88ad9112009-02-07 12:52:26 +0000240}
241
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000242void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
243 // Emit a branch from the current block to the target one if this
244 // was a real block. If this was just a fall-through block after a
245 // terminator, don't emit it.
246 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
247
248 if (!CurBB || CurBB->getTerminator()) {
249 // If there is no insert point or the previous block is already
250 // terminated, don't touch it.
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000251 } else {
252 // Otherwise, create a fall-through branch.
253 Builder.CreateBr(Target);
254 }
Daniel Dunbarc55b7c52008-11-11 22:06:59 +0000255
256 Builder.ClearInsertionPoint();
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000257}
258
Mike Stump7e39f182009-02-08 09:22:19 +0000259bool CodeGenFunction::StackFixupAtLabel(const void *S) {
260 if (StackDepthMap.find(S) == StackDepthMap.end()) {
Mike Stump88ad9112009-02-07 12:52:26 +0000261 // We need to remember the stack depth so that we can readjust the
262 // stack back to the right depth for this label if we want to
263 // transfer here from a different depth.
Mike Stump7e39f182009-02-08 09:22:19 +0000264 StackDepthMap[S] = StackDepth;
Mike Stump88ad9112009-02-07 12:52:26 +0000265 } else {
Mike Stump7e39f182009-02-08 09:22:19 +0000266 if (StackDepthMap[S] != StackDepth) {
Mike Stump88ad9112009-02-07 12:52:26 +0000267 // FIXME: Sema needs to ckeck for jumps that cross decls with
268 // initializations for C++, and all VLAs, not just the first in
269 // a block that does a stacksave.
270 // FIXME: We need to save a place to insert the adjustment
271 // when we do a EmitStackUpdate on a forward jump, and then
272 // backpatch the adjustment into that place.
Mike Stump7e39f182009-02-08 09:22:19 +0000273 return true;
Mike Stump88ad9112009-02-07 12:52:26 +0000274 }
275 }
Mike Stump7e39f182009-02-08 09:22:19 +0000276 return false;
277}
278
279void CodeGenFunction::EmitLabel(const LabelStmt &S) {
280 llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
281 if (StackFixupAtLabel(&S))
282 CGM.ErrorUnsupported(&S, "forward goto inside scope with VLA");
Chris Lattner4b009652007-07-25 00:24:17 +0000283 EmitBlock(NextBB);
Chris Lattner09cee852008-07-26 20:23:23 +0000284}
285
286
287void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
288 EmitLabel(S);
Chris Lattner4b009652007-07-25 00:24:17 +0000289 EmitStmt(S.getSubStmt());
290}
291
292void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar66e021e2008-10-02 18:02:06 +0000293 // FIXME: Implement goto out in @try or @catch blocks.
294 if (!ObjCEHStack.empty()) {
295 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
296 return;
297 }
298
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000299 // If this code is reachable then emit a stop point (if generating
300 // debug info). We have to do this ourselves because we are on the
301 // "simple" statement path.
302 if (HaveInsertPoint())
303 EmitStopPoint(&S);
Mike Stump88ad9112009-02-07 12:52:26 +0000304
305 // We need to adjust the stack, if the destination was (will be) at
306 // a different depth.
Mike Stump7e39f182009-02-08 09:22:19 +0000307 if (EmitStackUpdate(S.getLabel()))
308 // FIXME: Move to semq and assert here, codegen isn't the right
309 // time to be checking.
310 CGM.ErrorUnsupported(S.getLabel(),
311 "invalid goto to VLA scope that has finished");
Mike Stump88ad9112009-02-07 12:52:26 +0000312
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000313 EmitBranch(getBasicBlockForLabel(S.getLabel()));
Chris Lattner4b009652007-07-25 00:24:17 +0000314}
315
Daniel Dunbar879788d2008-08-04 16:51:22 +0000316void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Daniel Dunbar66e021e2008-10-02 18:02:06 +0000317 // FIXME: Implement indirect goto in @try or @catch blocks.
318 if (!ObjCEHStack.empty()) {
319 CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
320 return;
321 }
322
Daniel Dunbar879788d2008-08-04 16:51:22 +0000323 // Emit initial switch which will be patched up later by
324 // EmitIndirectSwitches(). We need a default dest, so we use the
325 // current BB, but this is overwritten.
326 llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
327 llvm::Type::Int32Ty,
328 "addr");
329 llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
330 IndirectSwitches.push_back(I);
331
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +0000332 // Clear the insertion point to indicate we are in unreachable code.
333 Builder.ClearInsertionPoint();
Daniel Dunbar879788d2008-08-04 16:51:22 +0000334}
335
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000336void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000337 // C99 6.8.4.1: The first substatement is executed if the expression compares
338 // unequal to 0. The condition must be a scalar type.
Chris Lattner4b009652007-07-25 00:24:17 +0000339
Chris Lattner1875ba22008-11-12 07:46:33 +0000340 // If the condition constant folds and can be elided, try to avoid emitting
341 // the condition and the dead arm of the if/else.
Chris Lattner3d6606b2008-11-12 08:04:58 +0000342 if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000343 // Figure out which block (then or else) is executed.
344 const Stmt *Executed = S.getThen(), *Skipped = S.getElse();
Chris Lattner1875ba22008-11-12 07:46:33 +0000345 if (Cond == -1) // Condition false?
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000346 std::swap(Executed, Skipped);
Chris Lattner1875ba22008-11-12 07:46:33 +0000347
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000348 // If the skipped block has no labels in it, just emit the executed block.
349 // This avoids emitting dead code and simplifies the CFG substantially.
Chris Lattner1875ba22008-11-12 07:46:33 +0000350 if (!ContainsLabel(Skipped)) {
Chris Lattnerc72a6a32008-11-11 07:24:28 +0000351 if (Executed)
352 EmitStmt(Executed);
353 return;
354 }
355 }
Chris Lattner1875ba22008-11-12 07:46:33 +0000356
357 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
358 // the conditional branch.
Daniel Dunbarc70a5df2008-11-13 00:47:57 +0000359 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
360 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
361 llvm::BasicBlock *ElseBlock = ContBlock;
Chris Lattner4b009652007-07-25 00:24:17 +0000362 if (S.getElse())
Daniel Dunbarc70a5df2008-11-13 00:47:57 +0000363 ElseBlock = createBasicBlock("if.else");
364 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000365
366 // Emit the 'then' code.
367 EmitBlock(ThenBlock);
368 EmitStmt(S.getThen());
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000369 EmitBranch(ContBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000370
371 // Emit the 'else' code if present.
372 if (const Stmt *Else = S.getElse()) {
373 EmitBlock(ElseBlock);
374 EmitStmt(Else);
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000375 EmitBranch(ContBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000376 }
377
378 // Emit the continuation block for code after the if.
Daniel Dunbarf9f38e62008-11-13 01:54:24 +0000379 EmitBlock(ContBlock, true);
Chris Lattner4b009652007-07-25 00:24:17 +0000380}
381
382void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
383 // Emit the header for the loop, insert it, which will create an uncond br to
384 // it.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000385 llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
Chris Lattner4b009652007-07-25 00:24:17 +0000386 EmitBlock(LoopHeader);
Mike Stumpcfdf4c22009-02-07 18:08:12 +0000387
388 // Create an exit block for when the condition fails, create a block for the
389 // body of the loop.
390 llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
391 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
392
393 // Store the blocks to use for break and continue.
394 BreakContinuePush(ExitBlock, LoopHeader);
Chris Lattner4b009652007-07-25 00:24:17 +0000395
Mike Stump80225e12009-02-07 17:18:33 +0000396 // Evaluate the conditional in the while header. C99 6.8.5.1: The
397 // evaluation of the controlling expression takes place before each
398 // execution of the loop body.
Chris Lattner4b009652007-07-25 00:24:17 +0000399 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel706f8442007-10-09 20:51:27 +0000400
401 // while(1) is common, avoid extra exit blocks. Be sure
Chris Lattner4b009652007-07-25 00:24:17 +0000402 // to correctly handle break/continue though.
Devang Patel706f8442007-10-09 20:51:27 +0000403 bool EmitBoolCondBranch = true;
404 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
405 if (C->isOne())
406 EmitBoolCondBranch = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000407
Chris Lattner4b009652007-07-25 00:24:17 +0000408 // As long as the condition is true, go to the loop body.
Devang Patel706f8442007-10-09 20:51:27 +0000409 if (EmitBoolCondBranch)
410 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
Chris Lattner3d6606b2008-11-12 08:04:58 +0000411
Chris Lattner4b009652007-07-25 00:24:17 +0000412 // Emit the loop body.
413 EmitBlock(LoopBody);
414 EmitStmt(S.getBody());
415
Mike Stump88ad9112009-02-07 12:52:26 +0000416 BreakContinuePop();
Chris Lattner4b009652007-07-25 00:24:17 +0000417
418 // Cycle to the condition.
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000419 EmitBranch(LoopHeader);
Chris Lattner4b009652007-07-25 00:24:17 +0000420
421 // Emit the exit block.
Daniel Dunbarf9f38e62008-11-13 01:54:24 +0000422 EmitBlock(ExitBlock, true);
Devang Patel706f8442007-10-09 20:51:27 +0000423
424 // If LoopHeader is a simple forwarding block then eliminate it.
425 if (!EmitBoolCondBranch
426 && &LoopHeader->front() == LoopHeader->getTerminator()) {
427 LoopHeader->replaceAllUsesWith(LoopBody);
428 LoopHeader->getTerminator()->eraseFromParent();
429 LoopHeader->eraseFromParent();
430 }
Chris Lattner4b009652007-07-25 00:24:17 +0000431}
432
433void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000434 // Emit the body for the loop, insert it, which will create an uncond br to
435 // it.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000436 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
437 llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
Chris Lattner4b009652007-07-25 00:24:17 +0000438 EmitBlock(LoopBody);
439
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000440 llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
Chris Lattner4b009652007-07-25 00:24:17 +0000441
442 // Store the blocks to use for break and continue.
Mike Stump88ad9112009-02-07 12:52:26 +0000443 BreakContinuePush(AfterDo, DoCond);
Chris Lattner4b009652007-07-25 00:24:17 +0000444
445 // Emit the body of the loop into the block.
446 EmitStmt(S.getBody());
447
Mike Stump88ad9112009-02-07 12:52:26 +0000448 BreakContinuePop();
Chris Lattner4b009652007-07-25 00:24:17 +0000449
450 EmitBlock(DoCond);
451
452 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
453 // after each execution of the loop body."
454
455 // Evaluate the conditional in the while header.
456 // C99 6.8.5p2/p4: The first substatement is executed if the expression
457 // compares unequal to 0. The condition must be a scalar type.
458 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel716d02c2007-10-09 20:33:39 +0000459
460 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
461 // to correctly handle break/continue though.
462 bool EmitBoolCondBranch = true;
463 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
464 if (C->isZero())
465 EmitBoolCondBranch = false;
466
Chris Lattner4b009652007-07-25 00:24:17 +0000467 // As long as the condition is true, iterate the loop.
Devang Patel716d02c2007-10-09 20:33:39 +0000468 if (EmitBoolCondBranch)
469 Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
Chris Lattner4b009652007-07-25 00:24:17 +0000470
471 // Emit the exit block.
Daniel Dunbarf9f38e62008-11-13 01:54:24 +0000472 EmitBlock(AfterDo, true);
Devang Patel716d02c2007-10-09 20:33:39 +0000473
474 // If DoCond is a simple forwarding block then eliminate it.
475 if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
476 DoCond->replaceAllUsesWith(AfterDo);
477 DoCond->getTerminator()->eraseFromParent();
478 DoCond->eraseFromParent();
479 }
Chris Lattner4b009652007-07-25 00:24:17 +0000480}
481
482void CodeGenFunction::EmitForStmt(const ForStmt &S) {
483 // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
484 // which contains a continue/break?
Chris Lattner4b009652007-07-25 00:24:17 +0000485
486 // Evaluate the first part before the loop.
487 if (S.getInit())
488 EmitStmt(S.getInit());
489
490 // Start the loop with a block that tests the condition.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000491 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
492 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
Chris Lattner4b009652007-07-25 00:24:17 +0000493
494 EmitBlock(CondBlock);
495
Mike Stumpa1ac4772009-02-07 23:02:10 +0000496 llvm::Value *saveStackDepth = StackDepth;
497
Mike Stump024c71f2009-02-07 20:14:12 +0000498 // Evaluate the condition if present. If not, treat it as a
499 // non-zero-constant according to 6.8.5.3p2, aka, true.
Chris Lattner4b009652007-07-25 00:24:17 +0000500 if (S.getCond()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000501 // As long as the condition is true, iterate the loop.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000502 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Chris Lattner3d6606b2008-11-12 08:04:58 +0000503
504 // C99 6.8.5p2/p4: The first substatement is executed if the expression
505 // compares unequal to 0. The condition must be a scalar type.
506 EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
507
Chris Lattner4b009652007-07-25 00:24:17 +0000508 EmitBlock(ForBody);
509 } else {
510 // Treat it as a non-zero constant. Don't even create a new block for the
511 // body, just fall into it.
512 }
513
514 // If the for loop doesn't have an increment we can just use the
515 // condition as the continue block.
516 llvm::BasicBlock *ContinueBlock;
517 if (S.getInc())
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000518 ContinueBlock = createBasicBlock("for.inc");
Chris Lattner4b009652007-07-25 00:24:17 +0000519 else
520 ContinueBlock = CondBlock;
521
522 // Store the blocks to use for break and continue.
Mike Stumpa1ac4772009-02-07 23:02:10 +0000523 // Ensure any vlas created between there and here, are undone
524 BreakContinuePush(AfterFor, ContinueBlock,
525 saveStackDepth, saveStackDepth);
526
Chris Lattner4b009652007-07-25 00:24:17 +0000527 // If the condition is true, execute the body of the for stmt.
528 EmitStmt(S.getBody());
529
Mike Stump88ad9112009-02-07 12:52:26 +0000530 BreakContinuePop();
Chris Lattner4b009652007-07-25 00:24:17 +0000531
Chris Lattner4b009652007-07-25 00:24:17 +0000532 // If there is an increment, emit it next.
Daniel Dunbar8ca61b22008-09-28 00:19:22 +0000533 if (S.getInc()) {
534 EmitBlock(ContinueBlock);
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000535 EmitStmt(S.getInc());
Daniel Dunbar8ca61b22008-09-28 00:19:22 +0000536 }
Chris Lattner4b009652007-07-25 00:24:17 +0000537
538 // Finally, branch back up to the condition for the next iteration.
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000539 EmitBranch(CondBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000540
541 // Emit the fall-through block.
Daniel Dunbarf9f38e62008-11-13 01:54:24 +0000542 EmitBlock(AfterFor, true);
Chris Lattner4b009652007-07-25 00:24:17 +0000543}
544
Daniel Dunbare856ac22008-09-24 04:00:38 +0000545void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
546 if (RV.isScalar()) {
547 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
548 } else if (RV.isAggregate()) {
549 EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
550 } else {
551 StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
552 }
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000553 EmitBranch(ReturnBlock);
Daniel Dunbare856ac22008-09-24 04:00:38 +0000554}
555
Chris Lattner4b009652007-07-25 00:24:17 +0000556/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
557/// if the function returns void, or may be missing one if the function returns
558/// non-void. Fun stuff :).
559void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Eli Friedmana97dc012008-12-20 23:18:29 +0000560 for (unsigned i = 0; i < StackSaveValues.size(); i++) {
Anders Carlssonbdb0f922008-12-20 21:33:38 +0000561 if (StackSaveValues[i]) {
562 CGM.ErrorUnsupported(&S, "return inside scope with VLA");
563 return;
564 }
Anders Carlsson842a36d2008-12-20 19:33:21 +0000565 }
566
Chris Lattner4b009652007-07-25 00:24:17 +0000567 // Emit the result value, even if unused, to evalute the side effects.
568 const Expr *RV = S.getRetValue();
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000569
570 // FIXME: Clean this up by using an LValue for ReturnTemp,
571 // EmitStoreThroughLValue, and EmitAnyExpr.
572 if (!ReturnValue) {
573 // Make sure not to return anything, but evaluate the expression
574 // for side effects.
575 if (RV)
Eli Friedman56977312008-05-22 01:22:33 +0000576 EmitAnyExpr(RV);
Chris Lattner4b009652007-07-25 00:24:17 +0000577 } else if (RV == 0) {
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000578 // Do nothing (return value is left uninitialized)
Chris Lattner74b93032007-08-26 07:14:44 +0000579 } else if (!hasAggregateLLVMType(RV->getType())) {
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000580 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
Chris Lattnerde0908b2008-04-04 16:54:41 +0000581 } else if (RV->getType()->isAnyComplexType()) {
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000582 EmitComplexExprIntoAddr(RV, ReturnValue, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000583 } else {
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000584 EmitAggExpr(RV, ReturnValue, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000585 }
Eli Friedman56977312008-05-22 01:22:33 +0000586
Daniel Dunbare9900eb2008-09-30 01:06:03 +0000587 if (!ObjCEHStack.empty()) {
588 for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
589 e = ObjCEHStack.rend(); i != e; ++i) {
Daniel Dunbar72f96552008-11-11 02:29:29 +0000590 llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
Daniel Dunbare9900eb2008-09-30 01:06:03 +0000591 EmitJumpThroughFinally(*i, ReturnPad);
592 EmitBlock(ReturnPad);
593 }
594 }
595
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000596 EmitBranch(ReturnBlock);
Chris Lattner4b009652007-07-25 00:24:17 +0000597}
598
599void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Ted Kremeneka6b2b272008-10-06 18:42:27 +0000600 for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
601 I != E; ++I)
602 EmitDecl(**I);
Chris Lattner4b009652007-07-25 00:24:17 +0000603}
604
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000605void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000606 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
607
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000608 // FIXME: Implement break in @try or @catch blocks.
Anders Carlssonc2176192008-12-13 22:52:24 +0000609 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Anders Carlsson842a36d2008-12-20 19:33:21 +0000610 CGM.ErrorUnsupported(&S, "break inside an Obj-C exception block");
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000611 return;
612 }
613
614 // If this code is reachable then emit a stop point (if generating
615 // debug info). We have to do this ourselves because we are on the
616 // "simple" statement path.
617 if (HaveInsertPoint())
618 EmitStopPoint(&S);
Mike Stump7e39f182009-02-08 09:22:19 +0000619
620 // We need to adjust the stack, if the destination was (will be) at
621 // a different depth.
622 if (EmitStackUpdate(BreakContinueStack.back().SaveBreakStackDepth))
623 assert (0 && "break vla botch");
624
Chris Lattner4b009652007-07-25 00:24:17 +0000625 llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000626 EmitBranch(Block);
Chris Lattner4b009652007-07-25 00:24:17 +0000627}
628
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000629void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000630 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
631
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000632 // FIXME: Implement continue in @try or @catch blocks.
Anders Carlssonc2176192008-12-13 22:52:24 +0000633 if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000634 CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
635 return;
636 }
637
638 // If this code is reachable then emit a stop point (if generating
639 // debug info). We have to do this ourselves because we are on the
640 // "simple" statement path.
641 if (HaveInsertPoint())
642 EmitStopPoint(&S);
Mike Stump7e39f182009-02-08 09:22:19 +0000643
644 // We need to adjust the stack, if the destination was (will be) at
645 // a different depth.
646 if (EmitStackUpdate(BreakContinueStack.back().SaveContinueStackDepth))
647 assert (0 && "continue vla botch");
648
Chris Lattner4b009652007-07-25 00:24:17 +0000649 llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
Daniel Dunbar5276caa2008-11-11 09:41:28 +0000650 EmitBranch(Block);
Chris Lattner4b009652007-07-25 00:24:17 +0000651}
Devang Patele58e0802007-10-04 23:45:31 +0000652
Devang Patel347ca322007-10-08 20:57:48 +0000653/// EmitCaseStmtRange - If case statement range is not too big then
654/// add multiple cases to switch instruction, one for each value within
655/// the range. If range is too big then emit "if" condition check.
656void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000657 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patel347ca322007-10-08 20:57:48 +0000658
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000659 llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
660 llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000661
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000662 // Emit the code for this case. We do this first to make sure it is
663 // properly chained from our predecessor before generating the
664 // switch machinery to enter this block.
Daniel Dunbar42bd06a2008-11-11 04:12:31 +0000665 EmitBlock(createBasicBlock("sw.bb"));
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000666 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
667 EmitStmt(S.getSubStmt());
668
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000669 // If range is empty, do nothing.
670 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
671 return;
Devang Patel347ca322007-10-08 20:57:48 +0000672
673 llvm::APInt Range = RHS - LHS;
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000674 // FIXME: parameters such as this should not be hardcoded.
Devang Patel347ca322007-10-08 20:57:48 +0000675 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
676 // Range is small enough to add multiple switch instruction cases.
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000677 for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
Devang Patelcf9dbf22007-10-05 20:54:07 +0000678 SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
679 LHS++;
680 }
Devang Patel347ca322007-10-08 20:57:48 +0000681 return;
682 }
683
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000684 // The range is too big. Emit "if" condition into a new block,
685 // making sure to save and restore the current insertion point.
686 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patelcf9dbf22007-10-05 20:54:07 +0000687
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000688 // Push this test onto the chain of range checks (which terminates
689 // in the default basic block). The switch's default will be changed
690 // to the top of this chain after switch emission is complete.
691 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar72f96552008-11-11 02:29:29 +0000692 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patel347ca322007-10-08 20:57:48 +0000693
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000694 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
695 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patel347ca322007-10-08 20:57:48 +0000696
697 // Emit range check.
698 llvm::Value *Diff =
Daniel Dunbar5c9ee142008-07-24 01:18:41 +0000699 Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
700 "tmp");
Devang Patel347ca322007-10-08 20:57:48 +0000701 llvm::Value *Cond =
702 Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
703 Builder.CreateCondBr(Cond, CaseDest, FalseDest);
704
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000705 // Restore the appropriate insertion point.
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +0000706 if (RestoreBB)
707 Builder.SetInsertPoint(RestoreBB);
708 else
709 Builder.ClearInsertionPoint();
Devang Patel347ca322007-10-08 20:57:48 +0000710}
711
712void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
713 if (S.getRHS()) {
714 EmitCaseStmtRange(S);
715 return;
716 }
717
Daniel Dunbar42bd06a2008-11-11 04:12:31 +0000718 EmitBlock(createBasicBlock("sw.bb"));
Devang Patel347ca322007-10-08 20:57:48 +0000719 llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000720 llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
Daniel Dunbar72f96552008-11-11 02:29:29 +0000721 SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
Devang Patele58e0802007-10-04 23:45:31 +0000722 EmitStmt(S.getSubStmt());
723}
724
725void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000726 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Daniel Dunbar72f96552008-11-11 02:29:29 +0000727 assert(DefaultBlock->empty() &&
728 "EmitDefaultStmt: Default block already defined?");
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000729 EmitBlock(DefaultBlock);
Devang Patele58e0802007-10-04 23:45:31 +0000730 EmitStmt(S.getSubStmt());
731}
732
733void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
734 llvm::Value *CondV = EmitScalarExpr(S.getCond());
735
736 // Handle nested switch statements.
737 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Devang Patel347ca322007-10-08 20:57:48 +0000738 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
Devang Patele58e0802007-10-04 23:45:31 +0000739
Mike Stumpa1ac4772009-02-07 23:02:10 +0000740 // Ensure any vlas created inside are destroyed on break.
741 llvm::Value *saveBreakStackDepth = StackDepth;
742
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000743 // Create basic block to hold stuff that comes after switch
744 // statement. We also need to create a default block now so that
745 // explicit case ranges tests can have a place to jump to on
746 // failure.
Daniel Dunbar72f96552008-11-11 02:29:29 +0000747 llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
748 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000749 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
750 CaseRangeBlock = DefaultBlock;
Devang Patele58e0802007-10-04 23:45:31 +0000751
Daniel Dunbar6c81e562008-11-12 08:21:33 +0000752 // Clear the insertion point to indicate we are in unreachable code.
753 Builder.ClearInsertionPoint();
Eli Friedman51eaf1b2008-05-12 16:08:04 +0000754
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000755 // All break statements jump to NextBlock. If BreakContinueStack is non empty
756 // then reuse last ContinueBlock.
Devang Patele58e0802007-10-04 23:45:31 +0000757 llvm::BasicBlock *ContinueBlock = NULL;
Mike Stumpa1ac4772009-02-07 23:02:10 +0000758 llvm::Value *saveContinueStackDepth = NULL;
759 if (!BreakContinueStack.empty()) {
Devang Patele58e0802007-10-04 23:45:31 +0000760 ContinueBlock = BreakContinueStack.back().ContinueBlock;
Mike Stumpa1ac4772009-02-07 23:02:10 +0000761 saveContinueStackDepth = BreakContinueStack.back().SaveContinueStackDepth;
762 }
763 // Ensure any vlas created between there and here, are undone
764 BreakContinuePush(NextBlock, ContinueBlock,
765 saveBreakStackDepth, saveContinueStackDepth);
Devang Patele58e0802007-10-04 23:45:31 +0000766
767 // Emit switch body.
768 EmitStmt(S.getBody());
Mike Stump88ad9112009-02-07 12:52:26 +0000769 BreakContinuePop();
Devang Patele58e0802007-10-04 23:45:31 +0000770
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000771 // Update the default block in case explicit case range tests have
772 // been chained on top.
773 SwitchInsn->setSuccessor(0, CaseRangeBlock);
Devang Patel347ca322007-10-08 20:57:48 +0000774
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000775 // If a default was never emitted then reroute any jumps to it and
776 // discard.
777 if (!DefaultBlock->getParent()) {
778 DefaultBlock->replaceAllUsesWith(NextBlock);
779 delete DefaultBlock;
780 }
Devang Patele58e0802007-10-04 23:45:31 +0000781
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000782 // Emit continuation.
Daniel Dunbarf9f38e62008-11-13 01:54:24 +0000783 EmitBlock(NextBlock, true);
Daniel Dunbar7a7458c2008-07-25 01:11:38 +0000784
Devang Patele58e0802007-10-04 23:45:31 +0000785 SwitchInsn = SavedSwitchInsn;
Devang Patel347ca322007-10-08 20:57:48 +0000786 CaseRangeBlock = SavedCRBlock;
Devang Patele58e0802007-10-04 23:45:31 +0000787}
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000788
Anders Carlssondf8f3042008-11-09 18:54:14 +0000789static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
790{
791 // FIXME: No need to create new std::string here, we could just make sure
792 // that we don't read past the end of the string data.
793 std::string str(S.getAsmString()->getStrData(),
794 S.getAsmString()->getByteLength());
795 const char *Start = str.c_str();
796
797 unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
798 bool IsSimple = S.isSimple();
Daniel Dunbar33cd0ff2008-10-17 20:58:01 +0000799 Failed = false;
800
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000801 static unsigned AsmCounter = 0;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000802 AsmCounter++;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000803 std::string Result;
Anders Carlsson52234522008-02-05 23:18:57 +0000804 if (IsSimple) {
805 while (*Start) {
806 switch (*Start) {
807 default:
808 Result += *Start;
809 break;
810 case '$':
811 Result += "$$";
812 break;
813 }
Anders Carlsson52234522008-02-05 23:18:57 +0000814 Start++;
815 }
816
817 return Result;
818 }
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000819
820 while (*Start) {
821 switch (*Start) {
822 default:
823 Result += *Start;
824 break;
825 case '$':
826 Result += "$$";
827 break;
828 case '%':
829 // Escaped character
830 Start++;
831 if (!*Start) {
832 // FIXME: This should be caught during Sema.
833 assert(0 && "Trailing '%' in asm string.");
834 }
835
836 char EscapedChar = *Start;
837 if (EscapedChar == '%') {
838 // Escaped percentage sign.
839 Result += '%';
Chris Lattnera23eb7b2008-07-26 20:15:14 +0000840 } else if (EscapedChar == '=') {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000841 // Generate an unique ID.
842 Result += llvm::utostr(AsmCounter);
843 } else if (isdigit(EscapedChar)) {
844 // %n - Assembler operand n
845 char *End;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000846 unsigned long n = strtoul(Start, &End, 10);
847 if (Start == End) {
848 // FIXME: This should be caught during Sema.
849 assert(0 && "Missing operand!");
850 } else if (n >= NumOperands) {
851 // FIXME: This should be caught during Sema.
852 assert(0 && "Operand number out of range!");
853 }
854
855 Result += '$' + llvm::utostr(n);
Lauro Ramos Venancioee48f3f2008-02-26 19:19:58 +0000856 Start = End - 1;
Anders Carlsson52234522008-02-05 23:18:57 +0000857 } else if (isalpha(EscapedChar)) {
858 char *End;
859
860 unsigned long n = strtoul(Start + 1, &End, 10);
861 if (Start == End) {
862 // FIXME: This should be caught during Sema.
863 assert(0 && "Missing operand!");
864 } else if (n >= NumOperands) {
865 // FIXME: This should be caught during Sema.
866 assert(0 && "Operand number out of range!");
867 }
868
869 Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
Lauro Ramos Venancioee48f3f2008-02-26 19:19:58 +0000870 Start = End - 1;
Anders Carlssondf8f3042008-11-09 18:54:14 +0000871 } else if (EscapedChar == '[') {
872 std::string SymbolicName;
873
874 Start++;
875
876 while (*Start && *Start != ']') {
877 SymbolicName += *Start;
878
879 Start++;
880 }
881
882 if (!Start) {
883 // FIXME: Should be caught by sema.
884 assert(0 && "Could not parse symbolic name");
885 }
886
887 assert(*Start == ']' && "Error parsing symbolic name");
888
889 int Index = -1;
890
891 // Check if this is an output operand.
892 for (unsigned i = 0; i < S.getNumOutputs(); i++) {
893 if (S.getOutputName(i) == SymbolicName) {
894 Index = i;
895 break;
896 }
897 }
898
899 if (Index == -1) {
900 for (unsigned i = 0; i < S.getNumInputs(); i++) {
901 if (S.getInputName(i) == SymbolicName) {
902 Index = S.getNumOutputs() + i;
903 }
904 }
905 }
906
907 assert(Index != -1 && "Did not find right operand!");
908
909 Result += '$' + llvm::utostr(Index);
910
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000911 } else {
Daniel Dunbar33cd0ff2008-10-17 20:58:01 +0000912 Failed = true;
913 return "";
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000914 }
915 }
916 Start++;
917 }
918
919 return Result;
920}
921
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +0000922static std::string SimplifyConstraint(const char* Constraint,
Anders Carlsson9363d792009-01-18 02:06:20 +0000923 TargetInfo &Target,
924 const std::string *OutputNamesBegin = 0,
925 const std::string *OutputNamesEnd = 0)
926{
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000927 std::string Result;
928
929 while (*Constraint) {
930 switch (*Constraint) {
931 default:
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +0000932 Result += Target.convertConstraint(*Constraint);
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000933 break;
934 // Ignore these
935 case '*':
936 case '?':
937 case '!':
938 break;
939 case 'g':
940 Result += "imr";
941 break;
Anders Carlsson9363d792009-01-18 02:06:20 +0000942 case '[': {
943 assert(OutputNamesBegin && OutputNamesEnd &&
944 "Must pass output names to constraints with a symbolic name");
945 unsigned Index;
946 bool result = Target.resolveSymbolicName(Constraint,
947 OutputNamesBegin,
948 OutputNamesEnd, Index);
Chris Lattner64e8d332009-01-21 07:35:26 +0000949 assert(result && "Could not resolve symbolic name"); result=result;
Anders Carlsson9363d792009-01-18 02:06:20 +0000950 Result += llvm::utostr(Index);
951 break;
952 }
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000953 }
954
955 Constraint++;
956 }
957
958 return Result;
959}
960
Anders Carlsson054f9962009-01-11 19:32:54 +0000961llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
962 TargetInfo::ConstraintInfo Info,
963 const Expr *InputExpr,
964 std::string &ConstraintStr)
965{
966 llvm::Value *Arg;
967 if ((Info & TargetInfo::CI_AllowsRegister) ||
Anders Carlssonfc12cfe2009-01-12 02:22:13 +0000968 !(Info & TargetInfo::CI_AllowsMemory)) {
969 const llvm::Type *Ty = ConvertType(InputExpr->getType());
970
971 if (Ty->isSingleValueType()) {
Anders Carlsson054f9962009-01-11 19:32:54 +0000972 Arg = EmitScalarExpr(InputExpr);
973 } else {
Anders Carlssonfc12cfe2009-01-12 02:22:13 +0000974 LValue Dest = EmitLValue(InputExpr);
975
976 uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
977 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
978 Ty = llvm::IntegerType::get(Size);
979 Ty = llvm::PointerType::getUnqual(Ty);
980
981 Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
982 } else {
983 Arg = Dest.getAddress();
984 ConstraintStr += '*';
985 }
Anders Carlsson054f9962009-01-11 19:32:54 +0000986 }
987 } else {
988 LValue Dest = EmitLValue(InputExpr);
989 Arg = Dest.getAddress();
990 ConstraintStr += '*';
991 }
992
993 return Arg;
994}
995
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000996void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Daniel Dunbar33cd0ff2008-10-17 20:58:01 +0000997 bool Failed;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +0000998 std::string AsmString =
Anders Carlssondf8f3042008-11-09 18:54:14 +0000999 ConvertAsmString(S, Failed);
Daniel Dunbar33cd0ff2008-10-17 20:58:01 +00001000
1001 if (Failed) {
1002 ErrorUnsupported(&S, "asm string");
1003 return;
1004 }
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001005
1006 std::string Constraints;
1007
1008 llvm::Value *ResultAddr = 0;
1009 const llvm::Type *ResultType = llvm::Type::VoidTy;
1010
1011 std::vector<const llvm::Type*> ArgTypes;
1012 std::vector<llvm::Value*> Args;
Anders Carlsson0d3019e2008-02-05 20:01:53 +00001013
1014 // Keep track of inout constraints.
1015 std::string InOutConstraints;
1016 std::vector<llvm::Value*> InOutArgs;
1017 std::vector<const llvm::Type*> InOutArgTypes;
Anders Carlssondd3a4fe2009-01-27 20:38:24 +00001018
1019 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1020
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001021 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1022 std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
1023 S.getOutputConstraint(i)->getByteLength());
1024
1025 TargetInfo::ConstraintInfo Info;
1026 bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
1027 Info);
Chris Lattner94c4b2d2008-10-12 00:31:50 +00001028 assert(result && "Failed to parse output constraint"); result=result;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001029
Anders Carlssondd3a4fe2009-01-27 20:38:24 +00001030 OutputConstraintInfos.push_back(Info);
1031
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001032 // Simplify the output constraint.
Lauro Ramos Venanciobb37a042008-02-26 18:33:46 +00001033 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001034
1035 LValue Dest = EmitLValue(S.getOutputExpr(i));
1036 const llvm::Type *DestValueType =
1037 cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
1038
1039 // If the first output operand is not a memory dest, we'll
1040 // make it the return value.
1041 if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
Dan Gohman377ba9f2008-05-22 22:12:56 +00001042 DestValueType->isSingleValueType()) {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001043 ResultAddr = Dest.getAddress();
1044 ResultType = DestValueType;
1045 Constraints += "=" + OutputConstraint;
1046 } else {
1047 ArgTypes.push_back(Dest.getAddress()->getType());
Anders Carlsson78725072008-02-05 16:57:38 +00001048 Args.push_back(Dest.getAddress());
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001049 if (i != 0)
1050 Constraints += ',';
Anders Carlsson0d3019e2008-02-05 20:01:53 +00001051 Constraints += "=*";
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001052 Constraints += OutputConstraint;
Anders Carlsson0d3019e2008-02-05 20:01:53 +00001053 }
1054
1055 if (Info & TargetInfo::CI_ReadWrite) {
Anders Carlsson0d3019e2008-02-05 20:01:53 +00001056 InOutConstraints += ',';
Anders Carlsson054f9962009-01-11 19:32:54 +00001057
Anders Carlsson0d3019e2008-02-05 20:01:53 +00001058 const Expr *InputExpr = S.getOutputExpr(i);
Anders Carlsson054f9962009-01-11 19:32:54 +00001059 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
Anders Carlsson0d3019e2008-02-05 20:01:53 +00001060
Anders Carlsson7ff60572009-01-11 21:23:27 +00001061 if (Info & TargetInfo::CI_AllowsRegister)
1062 InOutConstraints += llvm::utostr(i);
1063 else
1064 InOutConstraints += OutputConstraint;
Anders Carlssonc180e8e2009-01-11 19:46:50 +00001065
Anders Carlsson0d3019e2008-02-05 20:01:53 +00001066 InOutArgTypes.push_back(Arg->getType());
1067 InOutArgs.push_back(Arg);
Anders Carlsson0d3019e2008-02-05 20:01:53 +00001068 }
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001069 }
1070
1071 unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1072
1073 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1074 const Expr *InputExpr = S.getInputExpr(i);
1075
1076 std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
1077 S.getInputConstraint(i)->getByteLength());
1078
1079 TargetInfo::ConstraintInfo Info;
1080 bool result = Target.validateInputConstraint(InputConstraint.c_str(),
Anders Carlsson7b49cec2009-01-17 23:36:15 +00001081 S.begin_output_names(),
1082 S.end_output_names(),
Anders Carlssondd3a4fe2009-01-27 20:38:24 +00001083 &OutputConstraintInfos[0],
Chris Lattner64e8d332009-01-21 07:35:26 +00001084 Info); result=result;
Anders Carlssonb5c85692009-01-18 01:56:57 +00001085 assert(result && "Failed to parse input constraint");
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001086
1087 if (i != 0 || S.getNumOutputs() > 0)
1088 Constraints += ',';
1089
1090 // Simplify the input constraint.
Anders Carlsson9363d792009-01-18 02:06:20 +00001091 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
1092 S.begin_output_names(),
1093 S.end_output_names());
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001094
Anders Carlsson054f9962009-01-11 19:32:54 +00001095 llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001096
1097 ArgTypes.push_back(Arg->getType());
1098 Args.push_back(Arg);
1099 Constraints += InputConstraint;
1100 }
1101
Anders Carlsson0d3019e2008-02-05 20:01:53 +00001102 // Append the "input" part of inout constraints last.
1103 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1104 ArgTypes.push_back(InOutArgTypes[i]);
1105 Args.push_back(InOutArgs[i]);
1106 }
1107 Constraints += InOutConstraints;
1108
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001109 // Clobbers
1110 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1111 std::string Clobber(S.getClobber(i)->getStrData(),
1112 S.getClobber(i)->getByteLength());
1113
1114 Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
1115
Anders Carlsson74385982008-02-06 00:11:32 +00001116 if (i != 0 || NumConstraints != 0)
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001117 Constraints += ',';
Anders Carlsson74385982008-02-06 00:11:32 +00001118
1119 Constraints += "~{";
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001120 Constraints += Clobber;
Anders Carlsson74385982008-02-06 00:11:32 +00001121 Constraints += '}';
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001122 }
1123
1124 // Add machine specific clobbers
Eli Friedmand5e9d1e2008-12-21 01:15:32 +00001125 std::string MachineClobbers = Target.getClobbers();
1126 if (!MachineClobbers.empty()) {
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001127 if (!Constraints.empty())
1128 Constraints += ',';
Eli Friedmand5e9d1e2008-12-21 01:15:32 +00001129 Constraints += MachineClobbers;
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001130 }
Anders Carlsson0d3019e2008-02-05 20:01:53 +00001131
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001132 const llvm::FunctionType *FTy =
1133 llvm::FunctionType::get(ResultType, ArgTypes, false);
1134
1135 llvm::InlineAsm *IA =
1136 llvm::InlineAsm::get(FTy, AsmString, Constraints,
1137 S.isVolatile() || S.getNumOutputs() == 0);
1138 llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
Eli Friedman2e630542008-06-13 23:01:12 +00001139 if (ResultAddr) // FIXME: volatility
Anders Carlssonaf6a6c22008-02-05 16:35:33 +00001140 Builder.CreateStore(Result, ResultAddr);
1141}