CGStmt.cpp revision ec9771d57f94cc204491b3174e88069d08cdd684
1//===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Stmt nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
17#include "clang/AST/StmtVisitor.h"
18#include "clang/Basic/TargetInfo.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/InlineAsm.h"
21#include "llvm/Intrinsics.h"
22#include "llvm/Target/TargetData.h"
23using namespace clang;
24using namespace CodeGen;
25
26//===----------------------------------------------------------------------===//
27//                              Statement Emission
28//===----------------------------------------------------------------------===//
29
30void CodeGenFunction::EmitStopPoint(const Stmt *S) {
31  if (CGDebugInfo *DI = CGM.getDebugInfo()) {
32    DI->setLocation(S->getLocStart());
33    DI->EmitStopPoint(CurFn, Builder);
34  }
35}
36
37void CodeGenFunction::EmitStmt(const Stmt *S) {
38  assert(S && "Null statement?");
39
40  // Check if we can handle this without bothering to generate an
41  // insert point or debug info.
42  if (EmitSimpleStmt(S))
43    return;
44
45  // 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();
51
52  // Generate a stoppoint if we are emitting debug info.
53  EmitStopPoint(S);
54
55  switch (S->getStmtClass()) {
56  default:
57    // Must be an expression in a stmt context.  Emit the value (to get
58    // side-effects) and ignore the result.
59    if (const Expr *E = dyn_cast<Expr>(S)) {
60      if (!hasAggregateLLVMType(E->getType()))
61        EmitScalarExpr(E);
62      else if (E->getType()->isAnyComplexType())
63        EmitComplexExpr(E);
64      else
65        EmitAggExpr(E, 0, false);
66    } else {
67      ErrorUnsupported(S, "statement");
68    }
69    break;
70  case Stmt::IndirectGotoStmtClass:
71    EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
72
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;
80
81  case Stmt::SwitchStmtClass:   EmitSwitchStmt(cast<SwitchStmt>(*S));     break;
82  case Stmt::AsmStmtClass:      EmitAsmStmt(cast<AsmStmt>(*S));           break;
83
84  case Stmt::ObjCAtTryStmtClass:
85    EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
86    break;
87  case Stmt::ObjCAtCatchStmtClass:
88    assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
89    break;
90  case Stmt::ObjCAtFinallyStmtClass:
91    assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
92    break;
93  case Stmt::ObjCAtThrowStmtClass:
94    EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
95    break;
96  case Stmt::ObjCAtSynchronizedStmtClass:
97    EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
98    break;
99  case Stmt::ObjCForCollectionStmtClass:
100    EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
101    break;
102  }
103}
104
105bool 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
121/// 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).
124RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
125                                         llvm::Value *AggLoc, bool isAggVol) {
126
127  CGDebugInfo *DI = CGM.getDebugInfo();
128  if (DI) {
129    EnsureInsertPoint();
130    DI->setLocation(S.getLBracLoc());
131    DI->EmitRegionStart(CurFn, Builder);
132  }
133
134  // Keep track of the current cleanup stack depth.
135  size_t CleanupStackDepth = CleanupEntries.size();
136
137  // Push a null stack save value.
138  StackSaveValues.push_back(0);
139
140  for (CompoundStmt::const_body_iterator I = S.body_begin(),
141       E = S.body_end()-GetLast; I != E; ++I)
142    EmitStmt(*I);
143
144  if (DI) {
145    EnsureInsertPoint();
146    DI->setLocation(S.getRBracLoc());
147    DI->EmitRegionEnd(CurFn, Builder);
148  }
149
150  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    }
163
164    EnsureInsertPoint();
165
166    RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
167  }
168
169  if (llvm::Value *V = StackSaveValues.pop_back_val()) {
170    StackDepth = V;
171    V = Builder.CreateLoad(V, "tmp");
172
173    llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
174    Builder.CreateCall(F, V);
175  }
176
177  EmitCleanupBlocks(CleanupStackDepth);
178
179  return RV;
180}
181
182void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
183  // Fall out of the current block (if necessary).
184  EmitBranch(BB);
185
186  if (IsFinished && BB->use_empty()) {
187    delete BB;
188    return;
189  }
190
191  // 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
197  CurFn->getBasicBlockList().push_back(BB);
198  Builder.SetInsertPoint(BB);
199}
200
201bool CodeGenFunction::EmitStackUpdate(llvm::Value *V) {
202  // V can be 0 here, if it is, be sure to start searching from the
203  // top of the function, as we want the next save after that point.
204  for (unsigned int i = 0; i < StackSaveValues.size(); ++i)
205    if (StackSaveValues[i] == V) {
206      // The actual depth is actually in the next used slot, if any.
207      while (++i < StackSaveValues.size()
208             && (V = StackSaveValues[i]) == 0) ;
209      // If there were no other depth changes, we don't need any
210      // adjustments.
211      if (V) {
212        V = Builder.CreateLoad(V, "tmp");
213        // and restore it.
214        llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
215        Builder.CreateCall(F, V);
216      }
217    } else return true;
218  return false;
219}
220
221bool CodeGenFunction::EmitStackUpdate(const void  *S) {
222  if (StackDepthMap.find(S) == StackDepthMap.end()) {
223    // If we can't find it, just remember the depth now,
224    // so we can validate it later.
225    // FIXME: We need to save a place to insert the adjustment,
226    // if needed, here, sa that later in EmitLabel, we can
227    // backpatch the adjustment into that place, instead of
228    // saying unsupported.
229    StackDepthMap[S] = StackDepth;
230    return false;
231  }
232
233  // Find applicable stack depth, if any...
234  llvm::Value *V = StackDepthMap[S];
235  return EmitStackUpdate(V);
236}
237
238void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
239  // Emit a branch from the current block to the target one if this
240  // was a real block.  If this was just a fall-through block after a
241  // terminator, don't emit it.
242  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
243
244  if (!CurBB || CurBB->getTerminator()) {
245    // If there is no insert point or the previous block is already
246    // terminated, don't touch it.
247  } else {
248    // Otherwise, create a fall-through branch.
249    Builder.CreateBr(Target);
250  }
251
252  Builder.ClearInsertionPoint();
253}
254
255bool CodeGenFunction::StackFixupAtLabel(const void *S) {
256  if (StackDepthMap.find(S) == StackDepthMap.end()) {
257    // We need to remember the stack depth so that we can readjust the
258    // stack back to the right depth for this label if we want to
259    // transfer here from a different depth.
260    StackDepthMap[S] = StackDepth;
261  } else {
262    if (StackDepthMap[S] != StackDepth) {
263      // FIXME: Sema needs to ckeck for jumps that cross decls with
264      // initializations for C++, and all VLAs, not just the first in
265      // a block that does a stacksave.
266      // FIXME: We need to save a place to insert the adjustment
267      // when we do a EmitStackUpdate on a forward jump, and then
268      // backpatch the adjustment into that place.
269      return true;
270    }
271  }
272  return false;
273}
274
275void CodeGenFunction::EmitLabel(const LabelStmt &S) {
276  llvm::BasicBlock *NextBB = getBasicBlockForLabel(&S);
277  if (StackFixupAtLabel(&S))
278    CGM.ErrorUnsupported(&S, "forward goto inside scope with VLA");
279  EmitBlock(NextBB);
280}
281
282
283void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
284  EmitLabel(S);
285  EmitStmt(S.getSubStmt());
286}
287
288void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
289  // FIXME: Implement goto out in @try or @catch blocks.
290  if (!ObjCEHStack.empty()) {
291    CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
292    return;
293  }
294
295  // If this code is reachable then emit a stop point (if generating
296  // debug info). We have to do this ourselves because we are on the
297  // "simple" statement path.
298  if (HaveInsertPoint())
299    EmitStopPoint(&S);
300
301  // We need to adjust the stack, if the destination was (will be) at
302  // a different depth.
303  if (EmitStackUpdate(S.getLabel()))
304    // FIXME: Move to semq and assert here, codegen isn't the right
305    // time to be checking.
306    CGM.ErrorUnsupported(S.getLabel(),
307                         "invalid goto to VLA scope that has finished");
308
309  EmitBranch(getBasicBlockForLabel(S.getLabel()));
310}
311
312void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
313  // FIXME: Implement indirect goto in @try or @catch blocks.
314  if (!ObjCEHStack.empty()) {
315    CGM.ErrorUnsupported(&S, "goto inside an Obj-C exception block");
316    return;
317  }
318
319  // Emit initial switch which will be patched up later by
320  // EmitIndirectSwitches(). We need a default dest, so we use the
321  // current BB, but this is overwritten.
322  llvm::Value *V = Builder.CreatePtrToInt(EmitScalarExpr(S.getTarget()),
323                                          llvm::Type::Int32Ty,
324                                          "addr");
325  llvm::SwitchInst *I = Builder.CreateSwitch(V, Builder.GetInsertBlock());
326  IndirectSwitches.push_back(I);
327
328  // Clear the insertion point to indicate we are in unreachable code.
329  Builder.ClearInsertionPoint();
330}
331
332void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
333  // C99 6.8.4.1: The first substatement is executed if the expression compares
334  // unequal to 0.  The condition must be a scalar type.
335
336  // If the condition constant folds and can be elided, try to avoid emitting
337  // the condition and the dead arm of the if/else.
338  if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
339    // Figure out which block (then or else) is executed.
340    const Stmt *Executed = S.getThen(), *Skipped  = S.getElse();
341    if (Cond == -1)  // Condition false?
342      std::swap(Executed, Skipped);
343
344    // If the skipped block has no labels in it, just emit the executed block.
345    // This avoids emitting dead code and simplifies the CFG substantially.
346    if (!ContainsLabel(Skipped)) {
347      if (Executed)
348        EmitStmt(Executed);
349      return;
350    }
351  }
352
353  // Otherwise, the condition did not fold, or we couldn't elide it.  Just emit
354  // the conditional branch.
355  llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
356  llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
357  llvm::BasicBlock *ElseBlock = ContBlock;
358  if (S.getElse())
359    ElseBlock = createBasicBlock("if.else");
360  EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
361
362  // Emit the 'then' code.
363  EmitBlock(ThenBlock);
364  EmitStmt(S.getThen());
365  EmitBranch(ContBlock);
366
367  // Emit the 'else' code if present.
368  if (const Stmt *Else = S.getElse()) {
369    EmitBlock(ElseBlock);
370    EmitStmt(Else);
371    EmitBranch(ContBlock);
372  }
373
374  // Emit the continuation block for code after the if.
375  EmitBlock(ContBlock, true);
376}
377
378void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
379  // Emit the header for the loop, insert it, which will create an uncond br to
380  // it.
381  llvm::BasicBlock *LoopHeader = createBasicBlock("while.cond");
382  EmitBlock(LoopHeader);
383
384  // Create an exit block for when the condition fails, create a block for the
385  // body of the loop.
386  llvm::BasicBlock *ExitBlock = createBasicBlock("while.end");
387  llvm::BasicBlock *LoopBody  = createBasicBlock("while.body");
388
389  // Store the blocks to use for break and continue.
390  BreakContinuePush(ExitBlock, LoopHeader);
391
392  // Evaluate the conditional in the while header.  C99 6.8.5.1: The
393  // evaluation of the controlling expression takes place before each
394  // execution of the loop body.
395  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
396
397  // while(1) is common, avoid extra exit blocks.  Be sure
398  // to correctly handle break/continue though.
399  bool EmitBoolCondBranch = true;
400  if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
401    if (C->isOne())
402      EmitBoolCondBranch = false;
403
404  // As long as the condition is true, go to the loop body.
405  if (EmitBoolCondBranch)
406    Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
407
408  // Emit the loop body.
409  EmitBlock(LoopBody);
410  EmitStmt(S.getBody());
411
412  BreakContinuePop();
413
414  // Cycle to the condition.
415  EmitBranch(LoopHeader);
416
417  // Emit the exit block.
418  EmitBlock(ExitBlock, true);
419
420  // If LoopHeader is a simple forwarding block then eliminate it.
421  if (!EmitBoolCondBranch
422      && &LoopHeader->front() == LoopHeader->getTerminator()) {
423    LoopHeader->replaceAllUsesWith(LoopBody);
424    LoopHeader->getTerminator()->eraseFromParent();
425    LoopHeader->eraseFromParent();
426  }
427}
428
429void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
430  // Emit the body for the loop, insert it, which will create an uncond br to
431  // it.
432  llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
433  llvm::BasicBlock *AfterDo = createBasicBlock("do.end");
434  EmitBlock(LoopBody);
435
436  llvm::BasicBlock *DoCond = createBasicBlock("do.cond");
437
438  // Store the blocks to use for break and continue.
439  BreakContinuePush(AfterDo, DoCond);
440
441  // Emit the body of the loop into the block.
442  EmitStmt(S.getBody());
443
444  BreakContinuePop();
445
446  EmitBlock(DoCond);
447
448  // C99 6.8.5.2: "The evaluation of the controlling expression takes place
449  // after each execution of the loop body."
450
451  // Evaluate the conditional in the while header.
452  // C99 6.8.5p2/p4: The first substatement is executed if the expression
453  // compares unequal to 0.  The condition must be a scalar type.
454  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
455
456  // "do {} while (0)" is common in macros, avoid extra blocks.  Be sure
457  // to correctly handle break/continue though.
458  bool EmitBoolCondBranch = true;
459  if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
460    if (C->isZero())
461      EmitBoolCondBranch = false;
462
463  // As long as the condition is true, iterate the loop.
464  if (EmitBoolCondBranch)
465    Builder.CreateCondBr(BoolCondVal, LoopBody, AfterDo);
466
467  // Emit the exit block.
468  EmitBlock(AfterDo, true);
469
470  // If DoCond is a simple forwarding block then eliminate it.
471  if (!EmitBoolCondBranch && &DoCond->front() == DoCond->getTerminator()) {
472    DoCond->replaceAllUsesWith(AfterDo);
473    DoCond->getTerminator()->eraseFromParent();
474    DoCond->eraseFromParent();
475  }
476}
477
478void CodeGenFunction::EmitForStmt(const ForStmt &S) {
479  // FIXME: What do we do if the increment (f.e.) contains a stmt expression,
480  // which contains a continue/break?
481
482  // Evaluate the first part before the loop.
483  if (S.getInit())
484    EmitStmt(S.getInit());
485
486  // Start the loop with a block that tests the condition.
487  llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
488  llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
489
490  EmitBlock(CondBlock);
491
492  llvm::Value *saveStackDepth = StackDepth;
493
494  // Evaluate the condition if present.  If not, treat it as a
495  // non-zero-constant according to 6.8.5.3p2, aka, true.
496  if (S.getCond()) {
497    // As long as the condition is true, iterate the loop.
498    llvm::BasicBlock *ForBody = createBasicBlock("for.body");
499
500    // C99 6.8.5p2/p4: The first substatement is executed if the expression
501    // compares unequal to 0.  The condition must be a scalar type.
502    EmitBranchOnBoolExpr(S.getCond(), ForBody, AfterFor);
503
504    EmitBlock(ForBody);
505  } else {
506    // Treat it as a non-zero constant.  Don't even create a new block for the
507    // body, just fall into it.
508  }
509
510  // If the for loop doesn't have an increment we can just use the
511  // condition as the continue block.
512  llvm::BasicBlock *ContinueBlock;
513  if (S.getInc())
514    ContinueBlock = createBasicBlock("for.inc");
515  else
516    ContinueBlock = CondBlock;
517
518  // Store the blocks to use for break and continue.
519  // Ensure any vlas created between there and here, are undone
520  BreakContinuePush(AfterFor, ContinueBlock,
521                    saveStackDepth, saveStackDepth);
522
523  // If the condition is true, execute the body of the for stmt.
524  EmitStmt(S.getBody());
525
526  BreakContinuePop();
527
528  // If there is an increment, emit it next.
529  if (S.getInc()) {
530    EmitBlock(ContinueBlock);
531    EmitStmt(S.getInc());
532  }
533
534  // Finally, branch back up to the condition for the next iteration.
535  EmitBranch(CondBlock);
536
537  // Emit the fall-through block.
538  EmitBlock(AfterFor, true);
539}
540
541void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
542  if (RV.isScalar()) {
543    Builder.CreateStore(RV.getScalarVal(), ReturnValue);
544  } else if (RV.isAggregate()) {
545    EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
546  } else {
547    StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
548  }
549  EmitBranch(ReturnBlock);
550}
551
552/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
553/// if the function returns void, or may be missing one if the function returns
554/// non-void.  Fun stuff :).
555void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
556  for (unsigned i = 0; i < StackSaveValues.size(); i++) {
557    if (StackSaveValues[i]) {
558      CGM.ErrorUnsupported(&S, "return inside scope with VLA");
559      return;
560    }
561  }
562
563  // Emit the result value, even if unused, to evalute the side effects.
564  const Expr *RV = S.getRetValue();
565
566  // FIXME: Clean this up by using an LValue for ReturnTemp,
567  // EmitStoreThroughLValue, and EmitAnyExpr.
568  if (!ReturnValue) {
569    // Make sure not to return anything, but evaluate the expression
570    // for side effects.
571    if (RV)
572      EmitAnyExpr(RV);
573  } else if (RV == 0) {
574    // Do nothing (return value is left uninitialized)
575  } else if (!hasAggregateLLVMType(RV->getType())) {
576    Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
577  } else if (RV->getType()->isAnyComplexType()) {
578    EmitComplexExprIntoAddr(RV, ReturnValue, false);
579  } else {
580    EmitAggExpr(RV, ReturnValue, false);
581  }
582
583  if (!ObjCEHStack.empty()) {
584    for (ObjCEHStackType::reverse_iterator i = ObjCEHStack.rbegin(),
585           e = ObjCEHStack.rend(); i != e; ++i) {
586      llvm::BasicBlock *ReturnPad = createBasicBlock("return.pad");
587      EmitJumpThroughFinally(*i, ReturnPad);
588      EmitBlock(ReturnPad);
589    }
590  }
591
592  EmitBranch(ReturnBlock);
593}
594
595void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
596  for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
597       I != E; ++I)
598    EmitDecl(**I);
599}
600
601void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
602  assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
603
604  // FIXME: Implement break in @try or @catch blocks.
605  if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
606    CGM.ErrorUnsupported(&S, "break inside an Obj-C exception block");
607    return;
608  }
609
610  // If this code is reachable then emit a stop point (if generating
611  // debug info). We have to do this ourselves because we are on the
612  // "simple" statement path.
613  if (HaveInsertPoint())
614    EmitStopPoint(&S);
615
616  // We need to adjust the stack, if the destination was (will be) at
617  // a different depth.
618  if (EmitStackUpdate(BreakContinueStack.back().SaveBreakStackDepth))
619    assert (0 && "break vla botch");
620
621  llvm::BasicBlock *Block = BreakContinueStack.back().BreakBlock;
622  EmitBranch(Block);
623}
624
625void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
626  assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
627
628  // FIXME: Implement continue in @try or @catch blocks.
629  if (ObjCEHStack.size() != BreakContinueStack.back().EHStackSize) {
630    CGM.ErrorUnsupported(&S, "continue inside an Obj-C exception block");
631    return;
632  }
633
634  // If this code is reachable then emit a stop point (if generating
635  // debug info). We have to do this ourselves because we are on the
636  // "simple" statement path.
637  if (HaveInsertPoint())
638    EmitStopPoint(&S);
639
640  // We need to adjust the stack, if the destination was (will be) at
641  // a different depth.
642  if (EmitStackUpdate(BreakContinueStack.back().SaveContinueStackDepth))
643    assert (0 && "continue vla botch");
644
645  llvm::BasicBlock *Block = BreakContinueStack.back().ContinueBlock;
646  EmitBranch(Block);
647}
648
649/// EmitCaseStmtRange - If case statement range is not too big then
650/// add multiple cases to switch instruction, one for each value within
651/// the range. If range is too big then emit "if" condition check.
652void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
653  assert(S.getRHS() && "Expected RHS value in CaseStmt");
654
655  llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
656  llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
657
658  // Emit the code for this case. We do this first to make sure it is
659  // properly chained from our predecessor before generating the
660  // switch machinery to enter this block.
661  EmitBlock(createBasicBlock("sw.bb"));
662  llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
663  EmitStmt(S.getSubStmt());
664
665  // If range is empty, do nothing.
666  if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
667    return;
668
669  llvm::APInt Range = RHS - LHS;
670  // FIXME: parameters such as this should not be hardcoded.
671  if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
672    // Range is small enough to add multiple switch instruction cases.
673    for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
674      SwitchInsn->addCase(llvm::ConstantInt::get(LHS), CaseDest);
675      LHS++;
676    }
677    return;
678  }
679
680  // The range is too big. Emit "if" condition into a new block,
681  // making sure to save and restore the current insertion point.
682  llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
683
684  // Push this test onto the chain of range checks (which terminates
685  // in the default basic block). The switch's default will be changed
686  // to the top of this chain after switch emission is complete.
687  llvm::BasicBlock *FalseDest = CaseRangeBlock;
688  CaseRangeBlock = createBasicBlock("sw.caserange");
689
690  CurFn->getBasicBlockList().push_back(CaseRangeBlock);
691  Builder.SetInsertPoint(CaseRangeBlock);
692
693  // Emit range check.
694  llvm::Value *Diff =
695    Builder.CreateSub(SwitchInsn->getCondition(), llvm::ConstantInt::get(LHS),
696                      "tmp");
697  llvm::Value *Cond =
698    Builder.CreateICmpULE(Diff, llvm::ConstantInt::get(Range), "tmp");
699  Builder.CreateCondBr(Cond, CaseDest, FalseDest);
700
701  // Restore the appropriate insertion point.
702  if (RestoreBB)
703    Builder.SetInsertPoint(RestoreBB);
704  else
705    Builder.ClearInsertionPoint();
706}
707
708void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
709  if (S.getRHS()) {
710    EmitCaseStmtRange(S);
711    return;
712  }
713
714  EmitBlock(createBasicBlock("sw.bb"));
715  llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
716  llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
717  SwitchInsn->addCase(llvm::ConstantInt::get(CaseVal), CaseDest);
718  EmitStmt(S.getSubStmt());
719}
720
721void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
722  llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
723  assert(DefaultBlock->empty() &&
724         "EmitDefaultStmt: Default block already defined?");
725  EmitBlock(DefaultBlock);
726  EmitStmt(S.getSubStmt());
727}
728
729void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
730  llvm::Value *CondV = EmitScalarExpr(S.getCond());
731
732  // Handle nested switch statements.
733  llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
734  llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
735
736  // Ensure any vlas created inside are destroyed on break.
737  llvm::Value *saveBreakStackDepth = StackDepth;
738
739  // Create basic block to hold stuff that comes after switch
740  // statement. We also need to create a default block now so that
741  // explicit case ranges tests can have a place to jump to on
742  // failure.
743  llvm::BasicBlock *NextBlock = createBasicBlock("sw.epilog");
744  llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
745  SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
746  CaseRangeBlock = DefaultBlock;
747
748  // Clear the insertion point to indicate we are in unreachable code.
749  Builder.ClearInsertionPoint();
750
751  // All break statements jump to NextBlock. If BreakContinueStack is non empty
752  // then reuse last ContinueBlock.
753  llvm::BasicBlock *ContinueBlock = NULL;
754  llvm::Value *saveContinueStackDepth = NULL;
755  if (!BreakContinueStack.empty()) {
756    ContinueBlock = BreakContinueStack.back().ContinueBlock;
757    saveContinueStackDepth = BreakContinueStack.back().SaveContinueStackDepth;
758  }
759  // Ensure any vlas created between there and here, are undone
760  BreakContinuePush(NextBlock, ContinueBlock,
761                    saveBreakStackDepth, saveContinueStackDepth);
762
763  // Emit switch body.
764  EmitStmt(S.getBody());
765  BreakContinuePop();
766
767  // Update the default block in case explicit case range tests have
768  // been chained on top.
769  SwitchInsn->setSuccessor(0, CaseRangeBlock);
770
771  // If a default was never emitted then reroute any jumps to it and
772  // discard.
773  if (!DefaultBlock->getParent()) {
774    DefaultBlock->replaceAllUsesWith(NextBlock);
775    delete DefaultBlock;
776  }
777
778  // Emit continuation.
779  EmitBlock(NextBlock, true);
780
781  SwitchInsn = SavedSwitchInsn;
782  CaseRangeBlock = SavedCRBlock;
783}
784
785static std::string ConvertAsmString(const AsmStmt& S, bool &Failed)
786{
787  // FIXME: No need to create new std::string here, we could just make sure
788  // that we don't read past the end of the string data.
789  std::string str(S.getAsmString()->getStrData(),
790                  S.getAsmString()->getByteLength());
791  const char *Start = str.c_str();
792
793  unsigned NumOperands = S.getNumOutputs() + S.getNumInputs();
794  bool IsSimple = S.isSimple();
795  Failed = false;
796
797  static unsigned AsmCounter = 0;
798  AsmCounter++;
799  std::string Result;
800  if (IsSimple) {
801    while (*Start) {
802      switch (*Start) {
803      default:
804        Result += *Start;
805        break;
806      case '$':
807        Result += "$$";
808        break;
809      }
810      Start++;
811    }
812
813    return Result;
814  }
815
816  while (*Start) {
817    switch (*Start) {
818    default:
819      Result += *Start;
820      break;
821    case '$':
822      Result += "$$";
823      break;
824    case '%':
825      // Escaped character
826      Start++;
827      if (!*Start) {
828        // FIXME: This should be caught during Sema.
829        assert(0 && "Trailing '%' in asm string.");
830      }
831
832      char EscapedChar = *Start;
833      if (EscapedChar == '%') {
834        // Escaped percentage sign.
835        Result += '%';
836      } else if (EscapedChar == '=') {
837        // Generate an unique ID.
838        Result += llvm::utostr(AsmCounter);
839      } else if (isdigit(EscapedChar)) {
840        // %n - Assembler operand n
841        char *End;
842        unsigned long n = strtoul(Start, &End, 10);
843        if (Start == End) {
844          // FIXME: This should be caught during Sema.
845          assert(0 && "Missing operand!");
846        } else if (n >= NumOperands) {
847          // FIXME: This should be caught during Sema.
848          assert(0 && "Operand number out of range!");
849        }
850
851        Result += '$' + llvm::utostr(n);
852        Start = End - 1;
853      } else if (isalpha(EscapedChar)) {
854        char *End;
855
856        unsigned long n = strtoul(Start + 1, &End, 10);
857        if (Start == End) {
858          // FIXME: This should be caught during Sema.
859          assert(0 && "Missing operand!");
860        } else if (n >= NumOperands) {
861          // FIXME: This should be caught during Sema.
862          assert(0 && "Operand number out of range!");
863        }
864
865        Result += "${" + llvm::utostr(n) + ':' + EscapedChar + '}';
866        Start = End - 1;
867      } else if (EscapedChar == '[') {
868        std::string SymbolicName;
869
870        Start++;
871
872        while (*Start && *Start != ']') {
873          SymbolicName += *Start;
874
875          Start++;
876        }
877
878        if (!Start) {
879          // FIXME: Should be caught by sema.
880          assert(0 && "Could not parse symbolic name");
881        }
882
883        assert(*Start == ']' && "Error parsing symbolic name");
884
885        int Index = -1;
886
887        // Check if this is an output operand.
888        for (unsigned i = 0; i < S.getNumOutputs(); i++) {
889          if (S.getOutputName(i) == SymbolicName) {
890            Index = i;
891            break;
892          }
893        }
894
895        if (Index == -1) {
896          for (unsigned i = 0; i < S.getNumInputs(); i++) {
897            if (S.getInputName(i) == SymbolicName) {
898              Index = S.getNumOutputs() + i;
899            }
900          }
901        }
902
903        assert(Index != -1 && "Did not find right operand!");
904
905        Result += '$' + llvm::utostr(Index);
906
907      } else {
908        Failed = true;
909        return "";
910      }
911    }
912    Start++;
913  }
914
915  return Result;
916}
917
918static std::string SimplifyConstraint(const char* Constraint,
919                                      TargetInfo &Target,
920                                      const std::string *OutputNamesBegin = 0,
921                                      const std::string *OutputNamesEnd = 0)
922{
923  std::string Result;
924
925  while (*Constraint) {
926    switch (*Constraint) {
927    default:
928      Result += Target.convertConstraint(*Constraint);
929      break;
930    // Ignore these
931    case '*':
932    case '?':
933    case '!':
934      break;
935    case 'g':
936      Result += "imr";
937      break;
938    case '[': {
939      assert(OutputNamesBegin && OutputNamesEnd &&
940             "Must pass output names to constraints with a symbolic name");
941      unsigned Index;
942      bool result = Target.resolveSymbolicName(Constraint,
943                                               OutputNamesBegin,
944                                               OutputNamesEnd, Index);
945      assert(result && "Could not resolve symbolic name"); result=result;
946      Result += llvm::utostr(Index);
947      break;
948    }
949    }
950
951    Constraint++;
952  }
953
954  return Result;
955}
956
957llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
958                                           TargetInfo::ConstraintInfo Info,
959                                           const Expr *InputExpr,
960                                           std::string &ConstraintStr)
961{
962  llvm::Value *Arg;
963  if ((Info & TargetInfo::CI_AllowsRegister) ||
964      !(Info & TargetInfo::CI_AllowsMemory)) {
965    const llvm::Type *Ty = ConvertType(InputExpr->getType());
966
967    if (Ty->isSingleValueType()) {
968      Arg = EmitScalarExpr(InputExpr);
969    } else {
970      LValue Dest = EmitLValue(InputExpr);
971
972      uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
973      if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
974        Ty = llvm::IntegerType::get(Size);
975        Ty = llvm::PointerType::getUnqual(Ty);
976
977        Arg = Builder.CreateLoad(Builder.CreateBitCast(Dest.getAddress(), Ty));
978      } else {
979        Arg = Dest.getAddress();
980        ConstraintStr += '*';
981      }
982    }
983  } else {
984    LValue Dest = EmitLValue(InputExpr);
985    Arg = Dest.getAddress();
986    ConstraintStr += '*';
987  }
988
989  return Arg;
990}
991
992void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
993  bool Failed;
994  std::string AsmString =
995    ConvertAsmString(S, Failed);
996
997  if (Failed) {
998    ErrorUnsupported(&S, "asm string");
999    return;
1000  }
1001
1002  std::string Constraints;
1003
1004  llvm::Value *ResultAddr = 0;
1005  const llvm::Type *ResultType = llvm::Type::VoidTy;
1006
1007  std::vector<const llvm::Type*> ArgTypes;
1008  std::vector<llvm::Value*> Args;
1009
1010  // Keep track of inout constraints.
1011  std::string InOutConstraints;
1012  std::vector<llvm::Value*> InOutArgs;
1013  std::vector<const llvm::Type*> InOutArgTypes;
1014
1015  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1016
1017  for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1018    std::string OutputConstraint(S.getOutputConstraint(i)->getStrData(),
1019                                 S.getOutputConstraint(i)->getByteLength());
1020
1021    TargetInfo::ConstraintInfo Info;
1022    bool result = Target.validateOutputConstraint(OutputConstraint.c_str(),
1023                                                  Info);
1024    assert(result && "Failed to parse output constraint"); result=result;
1025
1026    OutputConstraintInfos.push_back(Info);
1027
1028    // Simplify the output constraint.
1029    OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
1030
1031    LValue Dest = EmitLValue(S.getOutputExpr(i));
1032    const llvm::Type *DestValueType =
1033      cast<llvm::PointerType>(Dest.getAddress()->getType())->getElementType();
1034
1035    // If the first output operand is not a memory dest, we'll
1036    // make it the return value.
1037    if (i == 0 && !(Info & TargetInfo::CI_AllowsMemory) &&
1038        DestValueType->isSingleValueType()) {
1039      ResultAddr = Dest.getAddress();
1040      ResultType = DestValueType;
1041      Constraints += "=" + OutputConstraint;
1042    } else {
1043      ArgTypes.push_back(Dest.getAddress()->getType());
1044      Args.push_back(Dest.getAddress());
1045      if (i != 0)
1046        Constraints += ',';
1047      Constraints += "=*";
1048      Constraints += OutputConstraint;
1049    }
1050
1051    if (Info & TargetInfo::CI_ReadWrite) {
1052      InOutConstraints += ',';
1053
1054      const Expr *InputExpr = S.getOutputExpr(i);
1055      llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, InOutConstraints);
1056
1057      if (Info & TargetInfo::CI_AllowsRegister)
1058        InOutConstraints += llvm::utostr(i);
1059      else
1060        InOutConstraints += OutputConstraint;
1061
1062      InOutArgTypes.push_back(Arg->getType());
1063      InOutArgs.push_back(Arg);
1064    }
1065  }
1066
1067  unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1068
1069  for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1070    const Expr *InputExpr = S.getInputExpr(i);
1071
1072    std::string InputConstraint(S.getInputConstraint(i)->getStrData(),
1073                                S.getInputConstraint(i)->getByteLength());
1074
1075    TargetInfo::ConstraintInfo Info;
1076    bool result = Target.validateInputConstraint(InputConstraint.c_str(),
1077                                                 S.begin_output_names(),
1078                                                 S.end_output_names(),
1079                                                 &OutputConstraintInfos[0],
1080                                                 Info); result=result;
1081    assert(result && "Failed to parse input constraint");
1082
1083    if (i != 0 || S.getNumOutputs() > 0)
1084      Constraints += ',';
1085
1086    // Simplify the input constraint.
1087    InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
1088                                         S.begin_output_names(),
1089                                         S.end_output_names());
1090
1091    llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
1092
1093    ArgTypes.push_back(Arg->getType());
1094    Args.push_back(Arg);
1095    Constraints += InputConstraint;
1096  }
1097
1098  // Append the "input" part of inout constraints last.
1099  for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1100    ArgTypes.push_back(InOutArgTypes[i]);
1101    Args.push_back(InOutArgs[i]);
1102  }
1103  Constraints += InOutConstraints;
1104
1105  // Clobbers
1106  for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1107    std::string Clobber(S.getClobber(i)->getStrData(),
1108                        S.getClobber(i)->getByteLength());
1109
1110    Clobber = Target.getNormalizedGCCRegisterName(Clobber.c_str());
1111
1112    if (i != 0 || NumConstraints != 0)
1113      Constraints += ',';
1114
1115    Constraints += "~{";
1116    Constraints += Clobber;
1117    Constraints += '}';
1118  }
1119
1120  // Add machine specific clobbers
1121  std::string MachineClobbers = Target.getClobbers();
1122  if (!MachineClobbers.empty()) {
1123    if (!Constraints.empty())
1124      Constraints += ',';
1125    Constraints += MachineClobbers;
1126  }
1127
1128  const llvm::FunctionType *FTy =
1129    llvm::FunctionType::get(ResultType, ArgTypes, false);
1130
1131  llvm::InlineAsm *IA =
1132    llvm::InlineAsm::get(FTy, AsmString, Constraints,
1133                         S.isVolatile() || S.getNumOutputs() == 0);
1134  llvm::Value *Result = Builder.CreateCall(IA, Args.begin(), Args.end(), "");
1135  if (ResultAddr) // FIXME: volatility
1136    Builder.CreateStore(Result, ResultAddr);
1137}
1138