CGStmt.cpp revision 4008088b002ba98ecbafdcc2d1f2ef1f41236b09
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 "CodeGenFunction.h"
15#include "CGDebugInfo.h"
16#include "CodeGenModule.h"
17#include "TargetInfo.h"
18#include "clang/AST/StmtVisitor.h"
19#include "clang/Basic/PrettyStackTrace.h"
20#include "clang/Basic/TargetInfo.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/InlineAsm.h"
24#include "llvm/IR/Intrinsics.h"
25using namespace clang;
26using namespace CodeGen;
27
28//===----------------------------------------------------------------------===//
29//                              Statement Emission
30//===----------------------------------------------------------------------===//
31
32void CodeGenFunction::EmitStopPoint(const Stmt *S) {
33  if (CGDebugInfo *DI = getDebugInfo()) {
34    SourceLocation Loc;
35    if (isa<DeclStmt>(S))
36      Loc = S->getLocEnd();
37    else
38      Loc = S->getLocStart();
39    DI->EmitLocation(Builder, Loc);
40
41    LastStopPoint = Loc;
42  }
43}
44
45void CodeGenFunction::EmitStmt(const Stmt *S) {
46  assert(S && "Null statement?");
47
48  // These statements have their own debug info handling.
49  if (EmitSimpleStmt(S))
50    return;
51
52  // Check if we are generating unreachable code.
53  if (!HaveInsertPoint()) {
54    // If so, and the statement doesn't contain a label, then we do not need to
55    // generate actual code. This is safe because (1) the current point is
56    // unreachable, so we don't need to execute the code, and (2) we've already
57    // handled the statements which update internal data structures (like the
58    // local variable map) which could be used by subsequent statements.
59    if (!ContainsLabel(S)) {
60      // Verify that any decl statements were handled as simple, they may be in
61      // scope of subsequent reachable statements.
62      assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
63      return;
64    }
65
66    // Otherwise, make a new block to hold the code.
67    EnsureInsertPoint();
68  }
69
70  // Generate a stoppoint if we are emitting debug info.
71  EmitStopPoint(S);
72
73  switch (S->getStmtClass()) {
74  case Stmt::NoStmtClass:
75  case Stmt::CXXCatchStmtClass:
76  case Stmt::SEHExceptStmtClass:
77  case Stmt::SEHFinallyStmtClass:
78  case Stmt::MSDependentExistsStmtClass:
79    llvm_unreachable("invalid statement class to emit generically");
80  case Stmt::NullStmtClass:
81  case Stmt::CompoundStmtClass:
82  case Stmt::DeclStmtClass:
83  case Stmt::LabelStmtClass:
84  case Stmt::AttributedStmtClass:
85  case Stmt::GotoStmtClass:
86  case Stmt::BreakStmtClass:
87  case Stmt::ContinueStmtClass:
88  case Stmt::DefaultStmtClass:
89  case Stmt::CaseStmtClass:
90    llvm_unreachable("should have emitted these statements as simple");
91
92#define STMT(Type, Base)
93#define ABSTRACT_STMT(Op)
94#define EXPR(Type, Base) \
95  case Stmt::Type##Class:
96#include "clang/AST/StmtNodes.inc"
97  {
98    // Remember the block we came in on.
99    llvm::BasicBlock *incoming = Builder.GetInsertBlock();
100    assert(incoming && "expression emission must have an insertion point");
101
102    EmitIgnoredExpr(cast<Expr>(S));
103
104    llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
105    assert(outgoing && "expression emission cleared block!");
106
107    // The expression emitters assume (reasonably!) that the insertion
108    // point is always set.  To maintain that, the call-emission code
109    // for noreturn functions has to enter a new block with no
110    // predecessors.  We want to kill that block and mark the current
111    // insertion point unreachable in the common case of a call like
112    // "exit();".  Since expression emission doesn't otherwise create
113    // blocks with no predecessors, we can just test for that.
114    // However, we must be careful not to do this to our incoming
115    // block, because *statement* emission does sometimes create
116    // reachable blocks which will have no predecessors until later in
117    // the function.  This occurs with, e.g., labels that are not
118    // reachable by fallthrough.
119    if (incoming != outgoing && outgoing->use_empty()) {
120      outgoing->eraseFromParent();
121      Builder.ClearInsertionPoint();
122    }
123    break;
124  }
125
126  case Stmt::IndirectGotoStmtClass:
127    EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
128
129  case Stmt::IfStmtClass:       EmitIfStmt(cast<IfStmt>(*S));             break;
130  case Stmt::WhileStmtClass:    EmitWhileStmt(cast<WhileStmt>(*S));       break;
131  case Stmt::DoStmtClass:       EmitDoStmt(cast<DoStmt>(*S));             break;
132  case Stmt::ForStmtClass:      EmitForStmt(cast<ForStmt>(*S));           break;
133
134  case Stmt::ReturnStmtClass:   EmitReturnStmt(cast<ReturnStmt>(*S));     break;
135
136  case Stmt::SwitchStmtClass:   EmitSwitchStmt(cast<SwitchStmt>(*S));     break;
137  case Stmt::GCCAsmStmtClass:   // Intentional fall-through.
138  case Stmt::MSAsmStmtClass:    EmitAsmStmt(cast<AsmStmt>(*S));           break;
139  case Stmt::CapturedStmtClass:
140    EmitCapturedStmt(cast<CapturedStmt>(*S));
141    break;
142  case Stmt::ObjCAtTryStmtClass:
143    EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
144    break;
145  case Stmt::ObjCAtCatchStmtClass:
146    llvm_unreachable(
147                    "@catch statements should be handled by EmitObjCAtTryStmt");
148  case Stmt::ObjCAtFinallyStmtClass:
149    llvm_unreachable(
150                  "@finally statements should be handled by EmitObjCAtTryStmt");
151  case Stmt::ObjCAtThrowStmtClass:
152    EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
153    break;
154  case Stmt::ObjCAtSynchronizedStmtClass:
155    EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
156    break;
157  case Stmt::ObjCForCollectionStmtClass:
158    EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
159    break;
160  case Stmt::ObjCAutoreleasePoolStmtClass:
161    EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
162    break;
163
164  case Stmt::CXXTryStmtClass:
165    EmitCXXTryStmt(cast<CXXTryStmt>(*S));
166    break;
167  case Stmt::CXXForRangeStmtClass:
168    EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
169  case Stmt::SEHTryStmtClass:
170    // FIXME Not yet implemented
171    break;
172  }
173}
174
175bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
176  switch (S->getStmtClass()) {
177  default: return false;
178  case Stmt::NullStmtClass: break;
179  case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
180  case Stmt::DeclStmtClass:     EmitDeclStmt(cast<DeclStmt>(*S));         break;
181  case Stmt::LabelStmtClass:    EmitLabelStmt(cast<LabelStmt>(*S));       break;
182  case Stmt::AttributedStmtClass:
183                            EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
184  case Stmt::GotoStmtClass:     EmitGotoStmt(cast<GotoStmt>(*S));         break;
185  case Stmt::BreakStmtClass:    EmitBreakStmt(cast<BreakStmt>(*S));       break;
186  case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
187  case Stmt::DefaultStmtClass:  EmitDefaultStmt(cast<DefaultStmt>(*S));   break;
188  case Stmt::CaseStmtClass:     EmitCaseStmt(cast<CaseStmt>(*S));         break;
189  }
190
191  return true;
192}
193
194/// EmitCompoundStmt - Emit a compound statement {..} node.  If GetLast is true,
195/// this captures the expression result of the last sub-statement and returns it
196/// (for use by the statement expression extension).
197RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
198                                         AggValueSlot AggSlot) {
199  PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
200                             "LLVM IR generation of compound statement ('{}')");
201
202  // Keep track of the current cleanup stack depth, including debug scopes.
203  LexicalScope Scope(*this, S.getSourceRange());
204
205  return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
206}
207
208RValue CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast,
209                                         AggValueSlot AggSlot) {
210
211  for (CompoundStmt::const_body_iterator I = S.body_begin(),
212       E = S.body_end()-GetLast; I != E; ++I)
213    EmitStmt(*I);
214
215  RValue RV;
216  if (!GetLast)
217    RV = RValue::get(0);
218  else {
219    // We have to special case labels here.  They are statements, but when put
220    // at the end of a statement expression, they yield the value of their
221    // subexpression.  Handle this by walking through all labels we encounter,
222    // emitting them before we evaluate the subexpr.
223    const Stmt *LastStmt = S.body_back();
224    while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
225      EmitLabel(LS->getDecl());
226      LastStmt = LS->getSubStmt();
227    }
228
229    EnsureInsertPoint();
230
231    RV = EmitAnyExpr(cast<Expr>(LastStmt), AggSlot);
232  }
233
234  return RV;
235}
236
237void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
238  llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
239
240  // If there is a cleanup stack, then we it isn't worth trying to
241  // simplify this block (we would need to remove it from the scope map
242  // and cleanup entry).
243  if (!EHStack.empty())
244    return;
245
246  // Can only simplify direct branches.
247  if (!BI || !BI->isUnconditional())
248    return;
249
250  // Can only simplify empty blocks.
251  if (BI != BB->begin())
252    return;
253
254  BB->replaceAllUsesWith(BI->getSuccessor(0));
255  BI->eraseFromParent();
256  BB->eraseFromParent();
257}
258
259void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
260  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
261
262  // Fall out of the current block (if necessary).
263  EmitBranch(BB);
264
265  if (IsFinished && BB->use_empty()) {
266    delete BB;
267    return;
268  }
269
270  // Place the block after the current block, if possible, or else at
271  // the end of the function.
272  if (CurBB && CurBB->getParent())
273    CurFn->getBasicBlockList().insertAfter(CurBB, BB);
274  else
275    CurFn->getBasicBlockList().push_back(BB);
276  Builder.SetInsertPoint(BB);
277}
278
279void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
280  // Emit a branch from the current block to the target one if this
281  // was a real block.  If this was just a fall-through block after a
282  // terminator, don't emit it.
283  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
284
285  if (!CurBB || CurBB->getTerminator()) {
286    // If there is no insert point or the previous block is already
287    // terminated, don't touch it.
288  } else {
289    // Otherwise, create a fall-through branch.
290    Builder.CreateBr(Target);
291  }
292
293  Builder.ClearInsertionPoint();
294}
295
296void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
297  bool inserted = false;
298  for (llvm::BasicBlock::use_iterator
299         i = block->use_begin(), e = block->use_end(); i != e; ++i) {
300    if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(*i)) {
301      CurFn->getBasicBlockList().insertAfter(insn->getParent(), block);
302      inserted = true;
303      break;
304    }
305  }
306
307  if (!inserted)
308    CurFn->getBasicBlockList().push_back(block);
309
310  Builder.SetInsertPoint(block);
311}
312
313CodeGenFunction::JumpDest
314CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
315  JumpDest &Dest = LabelMap[D];
316  if (Dest.isValid()) return Dest;
317
318  // Create, but don't insert, the new block.
319  Dest = JumpDest(createBasicBlock(D->getName()),
320                  EHScopeStack::stable_iterator::invalid(),
321                  NextCleanupDestIndex++);
322  return Dest;
323}
324
325void CodeGenFunction::EmitLabel(const LabelDecl *D) {
326  // Add this label to the current lexical scope if we're within any
327  // normal cleanups.  Jumps "in" to this label --- when permitted by
328  // the language --- may need to be routed around such cleanups.
329  if (EHStack.hasNormalCleanups() && CurLexicalScope)
330    CurLexicalScope->addLabel(D);
331
332  JumpDest &Dest = LabelMap[D];
333
334  // If we didn't need a forward reference to this label, just go
335  // ahead and create a destination at the current scope.
336  if (!Dest.isValid()) {
337    Dest = getJumpDestInCurrentScope(D->getName());
338
339  // Otherwise, we need to give this label a target depth and remove
340  // it from the branch-fixups list.
341  } else {
342    assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
343    Dest.setScopeDepth(EHStack.stable_begin());
344    ResolveBranchFixups(Dest.getBlock());
345  }
346
347  EmitBlock(Dest.getBlock());
348}
349
350/// Change the cleanup scope of the labels in this lexical scope to
351/// match the scope of the enclosing context.
352void CodeGenFunction::LexicalScope::rescopeLabels() {
353  assert(!Labels.empty());
354  EHScopeStack::stable_iterator innermostScope
355    = CGF.EHStack.getInnermostNormalCleanup();
356
357  // Change the scope depth of all the labels.
358  for (SmallVectorImpl<const LabelDecl*>::const_iterator
359         i = Labels.begin(), e = Labels.end(); i != e; ++i) {
360    assert(CGF.LabelMap.count(*i));
361    JumpDest &dest = CGF.LabelMap.find(*i)->second;
362    assert(dest.getScopeDepth().isValid());
363    assert(innermostScope.encloses(dest.getScopeDepth()));
364    dest.setScopeDepth(innermostScope);
365  }
366
367  // Reparent the labels if the new scope also has cleanups.
368  if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
369    ParentScope->Labels.append(Labels.begin(), Labels.end());
370  }
371}
372
373
374void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
375  EmitLabel(S.getDecl());
376  EmitStmt(S.getSubStmt());
377}
378
379void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
380  EmitStmt(S.getSubStmt());
381}
382
383void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
384  // If this code is reachable then emit a stop point (if generating
385  // debug info). We have to do this ourselves because we are on the
386  // "simple" statement path.
387  if (HaveInsertPoint())
388    EmitStopPoint(&S);
389
390  EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
391}
392
393
394void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
395  if (const LabelDecl *Target = S.getConstantTarget()) {
396    EmitBranchThroughCleanup(getJumpDestForLabel(Target));
397    return;
398  }
399
400  // Ensure that we have an i8* for our PHI node.
401  llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
402                                         Int8PtrTy, "addr");
403  llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
404
405  // Get the basic block for the indirect goto.
406  llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
407
408  // The first instruction in the block has to be the PHI for the switch dest,
409  // add an entry for this branch.
410  cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
411
412  EmitBranch(IndGotoBB);
413}
414
415void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
416  // C99 6.8.4.1: The first substatement is executed if the expression compares
417  // unequal to 0.  The condition must be a scalar type.
418  RunCleanupsScope ConditionScope(*this);
419
420  if (S.getConditionVariable())
421    EmitAutoVarDecl(*S.getConditionVariable());
422
423  // If the condition constant folds and can be elided, try to avoid emitting
424  // the condition and the dead arm of the if/else.
425  bool CondConstant;
426  if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) {
427    // Figure out which block (then or else) is executed.
428    const Stmt *Executed = S.getThen();
429    const Stmt *Skipped  = S.getElse();
430    if (!CondConstant)  // Condition false?
431      std::swap(Executed, Skipped);
432
433    // If the skipped block has no labels in it, just emit the executed block.
434    // This avoids emitting dead code and simplifies the CFG substantially.
435    if (!ContainsLabel(Skipped)) {
436      if (Executed) {
437        RunCleanupsScope ExecutedScope(*this);
438        EmitStmt(Executed);
439      }
440      return;
441    }
442  }
443
444  // Otherwise, the condition did not fold, or we couldn't elide it.  Just emit
445  // the conditional branch.
446  llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
447  llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
448  llvm::BasicBlock *ElseBlock = ContBlock;
449  if (S.getElse())
450    ElseBlock = createBasicBlock("if.else");
451  EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
452
453  // Emit the 'then' code.
454  EmitBlock(ThenBlock);
455  {
456    RunCleanupsScope ThenScope(*this);
457    EmitStmt(S.getThen());
458  }
459  EmitBranch(ContBlock);
460
461  // Emit the 'else' code if present.
462  if (const Stmt *Else = S.getElse()) {
463    // There is no need to emit line number for unconditional branch.
464    if (getDebugInfo())
465      Builder.SetCurrentDebugLocation(llvm::DebugLoc());
466    EmitBlock(ElseBlock);
467    {
468      RunCleanupsScope ElseScope(*this);
469      EmitStmt(Else);
470    }
471    // There is no need to emit line number for unconditional branch.
472    if (getDebugInfo())
473      Builder.SetCurrentDebugLocation(llvm::DebugLoc());
474    EmitBranch(ContBlock);
475  }
476
477  // Emit the continuation block for code after the if.
478  EmitBlock(ContBlock, true);
479}
480
481void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
482  // Emit the header for the loop, which will also become
483  // the continue target.
484  JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
485  EmitBlock(LoopHeader.getBlock());
486
487  // Create an exit block for when the condition fails, which will
488  // also become the break target.
489  JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
490
491  // Store the blocks to use for break and continue.
492  BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
493
494  // C++ [stmt.while]p2:
495  //   When the condition of a while statement is a declaration, the
496  //   scope of the variable that is declared extends from its point
497  //   of declaration (3.3.2) to the end of the while statement.
498  //   [...]
499  //   The object created in a condition is destroyed and created
500  //   with each iteration of the loop.
501  RunCleanupsScope ConditionScope(*this);
502
503  if (S.getConditionVariable())
504    EmitAutoVarDecl(*S.getConditionVariable());
505
506  // Evaluate the conditional in the while header.  C99 6.8.5.1: The
507  // evaluation of the controlling expression takes place before each
508  // execution of the loop body.
509  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
510
511  // while(1) is common, avoid extra exit blocks.  Be sure
512  // to correctly handle break/continue though.
513  bool EmitBoolCondBranch = true;
514  if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
515    if (C->isOne())
516      EmitBoolCondBranch = false;
517
518  // As long as the condition is true, go to the loop body.
519  llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
520  if (EmitBoolCondBranch) {
521    llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
522    if (ConditionScope.requiresCleanups())
523      ExitBlock = createBasicBlock("while.exit");
524
525    Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
526
527    if (ExitBlock != LoopExit.getBlock()) {
528      EmitBlock(ExitBlock);
529      EmitBranchThroughCleanup(LoopExit);
530    }
531  }
532
533  // Emit the loop body.  We have to emit this in a cleanup scope
534  // because it might be a singleton DeclStmt.
535  {
536    RunCleanupsScope BodyScope(*this);
537    EmitBlock(LoopBody);
538    EmitStmt(S.getBody());
539  }
540
541  BreakContinueStack.pop_back();
542
543  // Immediately force cleanup.
544  ConditionScope.ForceCleanup();
545
546  // Branch to the loop header again.
547  EmitBranch(LoopHeader.getBlock());
548
549  // Emit the exit block.
550  EmitBlock(LoopExit.getBlock(), true);
551
552  // The LoopHeader typically is just a branch if we skipped emitting
553  // a branch, try to erase it.
554  if (!EmitBoolCondBranch)
555    SimplifyForwardingBlocks(LoopHeader.getBlock());
556}
557
558void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
559  JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
560  JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
561
562  // Store the blocks to use for break and continue.
563  BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
564
565  // Emit the body of the loop.
566  llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
567  EmitBlock(LoopBody);
568  {
569    RunCleanupsScope BodyScope(*this);
570    EmitStmt(S.getBody());
571  }
572
573  BreakContinueStack.pop_back();
574
575  EmitBlock(LoopCond.getBlock());
576
577  // C99 6.8.5.2: "The evaluation of the controlling expression takes place
578  // after each execution of the loop body."
579
580  // Evaluate the conditional in the while header.
581  // C99 6.8.5p2/p4: The first substatement is executed if the expression
582  // compares unequal to 0.  The condition must be a scalar type.
583  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
584
585  // "do {} while (0)" is common in macros, avoid extra blocks.  Be sure
586  // to correctly handle break/continue though.
587  bool EmitBoolCondBranch = true;
588  if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
589    if (C->isZero())
590      EmitBoolCondBranch = false;
591
592  // As long as the condition is true, iterate the loop.
593  if (EmitBoolCondBranch)
594    Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock());
595
596  // Emit the exit block.
597  EmitBlock(LoopExit.getBlock());
598
599  // The DoCond block typically is just a branch if we skipped
600  // emitting a branch, try to erase it.
601  if (!EmitBoolCondBranch)
602    SimplifyForwardingBlocks(LoopCond.getBlock());
603}
604
605void CodeGenFunction::EmitForStmt(const ForStmt &S) {
606  JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
607
608  RunCleanupsScope ForScope(*this);
609
610  CGDebugInfo *DI = getDebugInfo();
611  if (DI)
612    DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
613
614  // Evaluate the first part before the loop.
615  if (S.getInit())
616    EmitStmt(S.getInit());
617
618  // Start the loop with a block that tests the condition.
619  // If there's an increment, the continue scope will be overwritten
620  // later.
621  JumpDest Continue = getJumpDestInCurrentScope("for.cond");
622  llvm::BasicBlock *CondBlock = Continue.getBlock();
623  EmitBlock(CondBlock);
624
625  // Create a cleanup scope for the condition variable cleanups.
626  RunCleanupsScope ConditionScope(*this);
627
628  llvm::Value *BoolCondVal = 0;
629  if (S.getCond()) {
630    // If the for statement has a condition scope, emit the local variable
631    // declaration.
632    llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
633    if (S.getConditionVariable()) {
634      EmitAutoVarDecl(*S.getConditionVariable());
635    }
636
637    // If there are any cleanups between here and the loop-exit scope,
638    // create a block to stage a loop exit along.
639    if (ForScope.requiresCleanups())
640      ExitBlock = createBasicBlock("for.cond.cleanup");
641
642    // As long as the condition is true, iterate the loop.
643    llvm::BasicBlock *ForBody = createBasicBlock("for.body");
644
645    // C99 6.8.5p2/p4: The first substatement is executed if the expression
646    // compares unequal to 0.  The condition must be a scalar type.
647    BoolCondVal = EvaluateExprAsBool(S.getCond());
648    Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
649
650    if (ExitBlock != LoopExit.getBlock()) {
651      EmitBlock(ExitBlock);
652      EmitBranchThroughCleanup(LoopExit);
653    }
654
655    EmitBlock(ForBody);
656  } else {
657    // Treat it as a non-zero constant.  Don't even create a new block for the
658    // body, just fall into it.
659  }
660
661  // If the for loop doesn't have an increment we can just use the
662  // condition as the continue block.  Otherwise we'll need to create
663  // a block for it (in the current scope, i.e. in the scope of the
664  // condition), and that we will become our continue block.
665  if (S.getInc())
666    Continue = getJumpDestInCurrentScope("for.inc");
667
668  // Store the blocks to use for break and continue.
669  BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
670
671  {
672    // Create a separate cleanup scope for the body, in case it is not
673    // a compound statement.
674    RunCleanupsScope BodyScope(*this);
675    EmitStmt(S.getBody());
676  }
677
678  // If there is an increment, emit it next.
679  if (S.getInc()) {
680    EmitBlock(Continue.getBlock());
681    EmitStmt(S.getInc());
682  }
683
684  BreakContinueStack.pop_back();
685
686  ConditionScope.ForceCleanup();
687  EmitBranch(CondBlock);
688
689  ForScope.ForceCleanup();
690
691  if (DI)
692    DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
693
694  // Emit the fall-through block.
695  EmitBlock(LoopExit.getBlock(), true);
696}
697
698void CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S) {
699  JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
700
701  RunCleanupsScope ForScope(*this);
702
703  CGDebugInfo *DI = getDebugInfo();
704  if (DI)
705    DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
706
707  // Evaluate the first pieces before the loop.
708  EmitStmt(S.getRangeStmt());
709  EmitStmt(S.getBeginEndStmt());
710
711  // Start the loop with a block that tests the condition.
712  // If there's an increment, the continue scope will be overwritten
713  // later.
714  llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
715  EmitBlock(CondBlock);
716
717  // If there are any cleanups between here and the loop-exit scope,
718  // create a block to stage a loop exit along.
719  llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
720  if (ForScope.requiresCleanups())
721    ExitBlock = createBasicBlock("for.cond.cleanup");
722
723  // The loop body, consisting of the specified body and the loop variable.
724  llvm::BasicBlock *ForBody = createBasicBlock("for.body");
725
726  // The body is executed if the expression, contextually converted
727  // to bool, is true.
728  llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
729  Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
730
731  if (ExitBlock != LoopExit.getBlock()) {
732    EmitBlock(ExitBlock);
733    EmitBranchThroughCleanup(LoopExit);
734  }
735
736  EmitBlock(ForBody);
737
738  // Create a block for the increment. In case of a 'continue', we jump there.
739  JumpDest Continue = getJumpDestInCurrentScope("for.inc");
740
741  // Store the blocks to use for break and continue.
742  BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
743
744  {
745    // Create a separate cleanup scope for the loop variable and body.
746    RunCleanupsScope BodyScope(*this);
747    EmitStmt(S.getLoopVarStmt());
748    EmitStmt(S.getBody());
749  }
750
751  // If there is an increment, emit it next.
752  EmitBlock(Continue.getBlock());
753  EmitStmt(S.getInc());
754
755  BreakContinueStack.pop_back();
756
757  EmitBranch(CondBlock);
758
759  ForScope.ForceCleanup();
760
761  if (DI)
762    DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
763
764  // Emit the fall-through block.
765  EmitBlock(LoopExit.getBlock(), true);
766}
767
768void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
769  if (RV.isScalar()) {
770    Builder.CreateStore(RV.getScalarVal(), ReturnValue);
771  } else if (RV.isAggregate()) {
772    EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
773  } else {
774    EmitStoreOfComplex(RV.getComplexVal(),
775                       MakeNaturalAlignAddrLValue(ReturnValue, Ty),
776                       /*init*/ true);
777  }
778  EmitBranchThroughCleanup(ReturnBlock);
779}
780
781/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
782/// if the function returns void, or may be missing one if the function returns
783/// non-void.  Fun stuff :).
784void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
785  // Emit the result value, even if unused, to evalute the side effects.
786  const Expr *RV = S.getRetValue();
787
788  // Treat block literals in a return expression as if they appeared
789  // in their own scope.  This permits a small, easily-implemented
790  // exception to our over-conservative rules about not jumping to
791  // statements following block literals with non-trivial cleanups.
792  RunCleanupsScope cleanupScope(*this);
793  if (const ExprWithCleanups *cleanups =
794        dyn_cast_or_null<ExprWithCleanups>(RV)) {
795    enterFullExpression(cleanups);
796    RV = cleanups->getSubExpr();
797  }
798
799  // FIXME: Clean this up by using an LValue for ReturnTemp,
800  // EmitStoreThroughLValue, and EmitAnyExpr.
801  if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) {
802    // Apply the named return value optimization for this return statement,
803    // which means doing nothing: the appropriate result has already been
804    // constructed into the NRVO variable.
805
806    // If there is an NRVO flag for this variable, set it to 1 into indicate
807    // that the cleanup code should not destroy the variable.
808    if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
809      Builder.CreateStore(Builder.getTrue(), NRVOFlag);
810  } else if (!ReturnValue) {
811    // Make sure not to return anything, but evaluate the expression
812    // for side effects.
813    if (RV)
814      EmitAnyExpr(RV);
815  } else if (RV == 0) {
816    // Do nothing (return value is left uninitialized)
817  } else if (FnRetTy->isReferenceType()) {
818    // If this function returns a reference, take the address of the expression
819    // rather than the value.
820    RValue Result = EmitReferenceBindingToExpr(RV, /*InitializedDecl=*/0);
821    Builder.CreateStore(Result.getScalarVal(), ReturnValue);
822  } else {
823    switch (getEvaluationKind(RV->getType())) {
824    case TEK_Scalar:
825      Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
826      break;
827    case TEK_Complex:
828      EmitComplexExprIntoLValue(RV,
829                     MakeNaturalAlignAddrLValue(ReturnValue, RV->getType()),
830                                /*isInit*/ true);
831      break;
832    case TEK_Aggregate: {
833      CharUnits Alignment = getContext().getTypeAlignInChars(RV->getType());
834      EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Alignment,
835                                            Qualifiers(),
836                                            AggValueSlot::IsDestructed,
837                                            AggValueSlot::DoesNotNeedGCBarriers,
838                                            AggValueSlot::IsNotAliased));
839      break;
840    }
841    }
842  }
843
844  NumReturnExprs += 1;
845  if (RV == 0 || RV->isEvaluatable(getContext()))
846    NumSimpleReturnExprs += 1;
847
848  cleanupScope.ForceCleanup();
849  EmitBranchThroughCleanup(ReturnBlock);
850}
851
852void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
853  // As long as debug info is modeled with instructions, we have to ensure we
854  // have a place to insert here and write the stop point here.
855  if (HaveInsertPoint())
856    EmitStopPoint(&S);
857
858  for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
859       I != E; ++I)
860    EmitDecl(**I);
861}
862
863void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
864  assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
865
866  // If this code is reachable then emit a stop point (if generating
867  // debug info). We have to do this ourselves because we are on the
868  // "simple" statement path.
869  if (HaveInsertPoint())
870    EmitStopPoint(&S);
871
872  JumpDest Block = BreakContinueStack.back().BreakBlock;
873  EmitBranchThroughCleanup(Block);
874}
875
876void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
877  assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
878
879  // If this code is reachable then emit a stop point (if generating
880  // debug info). We have to do this ourselves because we are on the
881  // "simple" statement path.
882  if (HaveInsertPoint())
883    EmitStopPoint(&S);
884
885  JumpDest Block = BreakContinueStack.back().ContinueBlock;
886  EmitBranchThroughCleanup(Block);
887}
888
889/// EmitCaseStmtRange - If case statement range is not too big then
890/// add multiple cases to switch instruction, one for each value within
891/// the range. If range is too big then emit "if" condition check.
892void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
893  assert(S.getRHS() && "Expected RHS value in CaseStmt");
894
895  llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
896  llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
897
898  // Emit the code for this case. We do this first to make sure it is
899  // properly chained from our predecessor before generating the
900  // switch machinery to enter this block.
901  EmitBlock(createBasicBlock("sw.bb"));
902  llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
903  EmitStmt(S.getSubStmt());
904
905  // If range is empty, do nothing.
906  if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
907    return;
908
909  llvm::APInt Range = RHS - LHS;
910  // FIXME: parameters such as this should not be hardcoded.
911  if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
912    // Range is small enough to add multiple switch instruction cases.
913    for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
914      SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
915      LHS++;
916    }
917    return;
918  }
919
920  // The range is too big. Emit "if" condition into a new block,
921  // making sure to save and restore the current insertion point.
922  llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
923
924  // Push this test onto the chain of range checks (which terminates
925  // in the default basic block). The switch's default will be changed
926  // to the top of this chain after switch emission is complete.
927  llvm::BasicBlock *FalseDest = CaseRangeBlock;
928  CaseRangeBlock = createBasicBlock("sw.caserange");
929
930  CurFn->getBasicBlockList().push_back(CaseRangeBlock);
931  Builder.SetInsertPoint(CaseRangeBlock);
932
933  // Emit range check.
934  llvm::Value *Diff =
935    Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
936  llvm::Value *Cond =
937    Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
938  Builder.CreateCondBr(Cond, CaseDest, FalseDest);
939
940  // Restore the appropriate insertion point.
941  if (RestoreBB)
942    Builder.SetInsertPoint(RestoreBB);
943  else
944    Builder.ClearInsertionPoint();
945}
946
947void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
948  // If there is no enclosing switch instance that we're aware of, then this
949  // case statement and its block can be elided.  This situation only happens
950  // when we've constant-folded the switch, are emitting the constant case,
951  // and part of the constant case includes another case statement.  For
952  // instance: switch (4) { case 4: do { case 5: } while (1); }
953  if (!SwitchInsn) {
954    EmitStmt(S.getSubStmt());
955    return;
956  }
957
958  // Handle case ranges.
959  if (S.getRHS()) {
960    EmitCaseStmtRange(S);
961    return;
962  }
963
964  llvm::ConstantInt *CaseVal =
965    Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
966
967  // If the body of the case is just a 'break', and if there was no fallthrough,
968  // try to not emit an empty block.
969  if ((CGM.getCodeGenOpts().OptimizationLevel > 0) &&
970      isa<BreakStmt>(S.getSubStmt())) {
971    JumpDest Block = BreakContinueStack.back().BreakBlock;
972
973    // Only do this optimization if there are no cleanups that need emitting.
974    if (isObviouslyBranchWithoutCleanups(Block)) {
975      SwitchInsn->addCase(CaseVal, Block.getBlock());
976
977      // If there was a fallthrough into this case, make sure to redirect it to
978      // the end of the switch as well.
979      if (Builder.GetInsertBlock()) {
980        Builder.CreateBr(Block.getBlock());
981        Builder.ClearInsertionPoint();
982      }
983      return;
984    }
985  }
986
987  EmitBlock(createBasicBlock("sw.bb"));
988  llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
989  SwitchInsn->addCase(CaseVal, CaseDest);
990
991  // Recursively emitting the statement is acceptable, but is not wonderful for
992  // code where we have many case statements nested together, i.e.:
993  //  case 1:
994  //    case 2:
995  //      case 3: etc.
996  // Handling this recursively will create a new block for each case statement
997  // that falls through to the next case which is IR intensive.  It also causes
998  // deep recursion which can run into stack depth limitations.  Handle
999  // sequential non-range case statements specially.
1000  const CaseStmt *CurCase = &S;
1001  const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1002
1003  // Otherwise, iteratively add consecutive cases to this switch stmt.
1004  while (NextCase && NextCase->getRHS() == 0) {
1005    CurCase = NextCase;
1006    llvm::ConstantInt *CaseVal =
1007      Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
1008    SwitchInsn->addCase(CaseVal, CaseDest);
1009    NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1010  }
1011
1012  // Normal default recursion for non-cases.
1013  EmitStmt(CurCase->getSubStmt());
1014}
1015
1016void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
1017  llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1018  assert(DefaultBlock->empty() &&
1019         "EmitDefaultStmt: Default block already defined?");
1020  EmitBlock(DefaultBlock);
1021  EmitStmt(S.getSubStmt());
1022}
1023
1024/// CollectStatementsForCase - Given the body of a 'switch' statement and a
1025/// constant value that is being switched on, see if we can dead code eliminate
1026/// the body of the switch to a simple series of statements to emit.  Basically,
1027/// on a switch (5) we want to find these statements:
1028///    case 5:
1029///      printf(...);    <--
1030///      ++i;            <--
1031///      break;
1032///
1033/// and add them to the ResultStmts vector.  If it is unsafe to do this
1034/// transformation (for example, one of the elided statements contains a label
1035/// that might be jumped to), return CSFC_Failure.  If we handled it and 'S'
1036/// should include statements after it (e.g. the printf() line is a substmt of
1037/// the case) then return CSFC_FallThrough.  If we handled it and found a break
1038/// statement, then return CSFC_Success.
1039///
1040/// If Case is non-null, then we are looking for the specified case, checking
1041/// that nothing we jump over contains labels.  If Case is null, then we found
1042/// the case and are looking for the break.
1043///
1044/// If the recursive walk actually finds our Case, then we set FoundCase to
1045/// true.
1046///
1047enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
1048static CSFC_Result CollectStatementsForCase(const Stmt *S,
1049                                            const SwitchCase *Case,
1050                                            bool &FoundCase,
1051                              SmallVectorImpl<const Stmt*> &ResultStmts) {
1052  // If this is a null statement, just succeed.
1053  if (S == 0)
1054    return Case ? CSFC_Success : CSFC_FallThrough;
1055
1056  // If this is the switchcase (case 4: or default) that we're looking for, then
1057  // we're in business.  Just add the substatement.
1058  if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
1059    if (S == Case) {
1060      FoundCase = true;
1061      return CollectStatementsForCase(SC->getSubStmt(), 0, FoundCase,
1062                                      ResultStmts);
1063    }
1064
1065    // Otherwise, this is some other case or default statement, just ignore it.
1066    return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
1067                                    ResultStmts);
1068  }
1069
1070  // If we are in the live part of the code and we found our break statement,
1071  // return a success!
1072  if (Case == 0 && isa<BreakStmt>(S))
1073    return CSFC_Success;
1074
1075  // If this is a switch statement, then it might contain the SwitchCase, the
1076  // break, or neither.
1077  if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1078    // Handle this as two cases: we might be looking for the SwitchCase (if so
1079    // the skipped statements must be skippable) or we might already have it.
1080    CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
1081    if (Case) {
1082      // Keep track of whether we see a skipped declaration.  The code could be
1083      // using the declaration even if it is skipped, so we can't optimize out
1084      // the decl if the kept statements might refer to it.
1085      bool HadSkippedDecl = false;
1086
1087      // If we're looking for the case, just see if we can skip each of the
1088      // substatements.
1089      for (; Case && I != E; ++I) {
1090        HadSkippedDecl |= isa<DeclStmt>(*I);
1091
1092        switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1093        case CSFC_Failure: return CSFC_Failure;
1094        case CSFC_Success:
1095          // A successful result means that either 1) that the statement doesn't
1096          // have the case and is skippable, or 2) does contain the case value
1097          // and also contains the break to exit the switch.  In the later case,
1098          // we just verify the rest of the statements are elidable.
1099          if (FoundCase) {
1100            // If we found the case and skipped declarations, we can't do the
1101            // optimization.
1102            if (HadSkippedDecl)
1103              return CSFC_Failure;
1104
1105            for (++I; I != E; ++I)
1106              if (CodeGenFunction::ContainsLabel(*I, true))
1107                return CSFC_Failure;
1108            return CSFC_Success;
1109          }
1110          break;
1111        case CSFC_FallThrough:
1112          // If we have a fallthrough condition, then we must have found the
1113          // case started to include statements.  Consider the rest of the
1114          // statements in the compound statement as candidates for inclusion.
1115          assert(FoundCase && "Didn't find case but returned fallthrough?");
1116          // We recursively found Case, so we're not looking for it anymore.
1117          Case = 0;
1118
1119          // If we found the case and skipped declarations, we can't do the
1120          // optimization.
1121          if (HadSkippedDecl)
1122            return CSFC_Failure;
1123          break;
1124        }
1125      }
1126    }
1127
1128    // If we have statements in our range, then we know that the statements are
1129    // live and need to be added to the set of statements we're tracking.
1130    for (; I != E; ++I) {
1131      switch (CollectStatementsForCase(*I, 0, FoundCase, ResultStmts)) {
1132      case CSFC_Failure: return CSFC_Failure;
1133      case CSFC_FallThrough:
1134        // A fallthrough result means that the statement was simple and just
1135        // included in ResultStmt, keep adding them afterwards.
1136        break;
1137      case CSFC_Success:
1138        // A successful result means that we found the break statement and
1139        // stopped statement inclusion.  We just ensure that any leftover stmts
1140        // are skippable and return success ourselves.
1141        for (++I; I != E; ++I)
1142          if (CodeGenFunction::ContainsLabel(*I, true))
1143            return CSFC_Failure;
1144        return CSFC_Success;
1145      }
1146    }
1147
1148    return Case ? CSFC_Success : CSFC_FallThrough;
1149  }
1150
1151  // Okay, this is some other statement that we don't handle explicitly, like a
1152  // for statement or increment etc.  If we are skipping over this statement,
1153  // just verify it doesn't have labels, which would make it invalid to elide.
1154  if (Case) {
1155    if (CodeGenFunction::ContainsLabel(S, true))
1156      return CSFC_Failure;
1157    return CSFC_Success;
1158  }
1159
1160  // Otherwise, we want to include this statement.  Everything is cool with that
1161  // so long as it doesn't contain a break out of the switch we're in.
1162  if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1163
1164  // Otherwise, everything is great.  Include the statement and tell the caller
1165  // that we fall through and include the next statement as well.
1166  ResultStmts.push_back(S);
1167  return CSFC_FallThrough;
1168}
1169
1170/// FindCaseStatementsForValue - Find the case statement being jumped to and
1171/// then invoke CollectStatementsForCase to find the list of statements to emit
1172/// for a switch on constant.  See the comment above CollectStatementsForCase
1173/// for more details.
1174static bool FindCaseStatementsForValue(const SwitchStmt &S,
1175                                       const llvm::APSInt &ConstantCondValue,
1176                                SmallVectorImpl<const Stmt*> &ResultStmts,
1177                                       ASTContext &C) {
1178  // First step, find the switch case that is being branched to.  We can do this
1179  // efficiently by scanning the SwitchCase list.
1180  const SwitchCase *Case = S.getSwitchCaseList();
1181  const DefaultStmt *DefaultCase = 0;
1182
1183  for (; Case; Case = Case->getNextSwitchCase()) {
1184    // It's either a default or case.  Just remember the default statement in
1185    // case we're not jumping to any numbered cases.
1186    if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1187      DefaultCase = DS;
1188      continue;
1189    }
1190
1191    // Check to see if this case is the one we're looking for.
1192    const CaseStmt *CS = cast<CaseStmt>(Case);
1193    // Don't handle case ranges yet.
1194    if (CS->getRHS()) return false;
1195
1196    // If we found our case, remember it as 'case'.
1197    if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
1198      break;
1199  }
1200
1201  // If we didn't find a matching case, we use a default if it exists, or we
1202  // elide the whole switch body!
1203  if (Case == 0) {
1204    // It is safe to elide the body of the switch if it doesn't contain labels
1205    // etc.  If it is safe, return successfully with an empty ResultStmts list.
1206    if (DefaultCase == 0)
1207      return !CodeGenFunction::ContainsLabel(&S);
1208    Case = DefaultCase;
1209  }
1210
1211  // Ok, we know which case is being jumped to, try to collect all the
1212  // statements that follow it.  This can fail for a variety of reasons.  Also,
1213  // check to see that the recursive walk actually found our case statement.
1214  // Insane cases like this can fail to find it in the recursive walk since we
1215  // don't handle every stmt kind:
1216  // switch (4) {
1217  //   while (1) {
1218  //     case 4: ...
1219  bool FoundCase = false;
1220  return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1221                                  ResultStmts) != CSFC_Failure &&
1222         FoundCase;
1223}
1224
1225void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1226  JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1227
1228  RunCleanupsScope ConditionScope(*this);
1229
1230  if (S.getConditionVariable())
1231    EmitAutoVarDecl(*S.getConditionVariable());
1232
1233  // Handle nested switch statements.
1234  llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1235  llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1236
1237  // See if we can constant fold the condition of the switch and therefore only
1238  // emit the live case statement (if any) of the switch.
1239  llvm::APSInt ConstantCondValue;
1240  if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1241    SmallVector<const Stmt*, 4> CaseStmts;
1242    if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1243                                   getContext())) {
1244      RunCleanupsScope ExecutedScope(*this);
1245
1246      // At this point, we are no longer "within" a switch instance, so
1247      // we can temporarily enforce this to ensure that any embedded case
1248      // statements are not emitted.
1249      SwitchInsn = 0;
1250
1251      // Okay, we can dead code eliminate everything except this case.  Emit the
1252      // specified series of statements and we're good.
1253      for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1254        EmitStmt(CaseStmts[i]);
1255
1256      // Now we want to restore the saved switch instance so that nested
1257      // switches continue to function properly
1258      SwitchInsn = SavedSwitchInsn;
1259
1260      return;
1261    }
1262  }
1263
1264  llvm::Value *CondV = EmitScalarExpr(S.getCond());
1265
1266  // Create basic block to hold stuff that comes after switch
1267  // statement. We also need to create a default block now so that
1268  // explicit case ranges tests can have a place to jump to on
1269  // failure.
1270  llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1271  SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1272  CaseRangeBlock = DefaultBlock;
1273
1274  // Clear the insertion point to indicate we are in unreachable code.
1275  Builder.ClearInsertionPoint();
1276
1277  // All break statements jump to NextBlock. If BreakContinueStack is non empty
1278  // then reuse last ContinueBlock.
1279  JumpDest OuterContinue;
1280  if (!BreakContinueStack.empty())
1281    OuterContinue = BreakContinueStack.back().ContinueBlock;
1282
1283  BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1284
1285  // Emit switch body.
1286  EmitStmt(S.getBody());
1287
1288  BreakContinueStack.pop_back();
1289
1290  // Update the default block in case explicit case range tests have
1291  // been chained on top.
1292  SwitchInsn->setDefaultDest(CaseRangeBlock);
1293
1294  // If a default was never emitted:
1295  if (!DefaultBlock->getParent()) {
1296    // If we have cleanups, emit the default block so that there's a
1297    // place to jump through the cleanups from.
1298    if (ConditionScope.requiresCleanups()) {
1299      EmitBlock(DefaultBlock);
1300
1301    // Otherwise, just forward the default block to the switch end.
1302    } else {
1303      DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1304      delete DefaultBlock;
1305    }
1306  }
1307
1308  ConditionScope.ForceCleanup();
1309
1310  // Emit continuation.
1311  EmitBlock(SwitchExit.getBlock(), true);
1312
1313  SwitchInsn = SavedSwitchInsn;
1314  CaseRangeBlock = SavedCRBlock;
1315}
1316
1317static std::string
1318SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1319                 SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
1320  std::string Result;
1321
1322  while (*Constraint) {
1323    switch (*Constraint) {
1324    default:
1325      Result += Target.convertConstraint(Constraint);
1326      break;
1327    // Ignore these
1328    case '*':
1329    case '?':
1330    case '!':
1331    case '=': // Will see this and the following in mult-alt constraints.
1332    case '+':
1333      break;
1334    case '#': // Ignore the rest of the constraint alternative.
1335      while (Constraint[1] && Constraint[1] != ',')
1336	Constraint++;
1337      break;
1338    case ',':
1339      Result += "|";
1340      break;
1341    case 'g':
1342      Result += "imr";
1343      break;
1344    case '[': {
1345      assert(OutCons &&
1346             "Must pass output names to constraints with a symbolic name");
1347      unsigned Index;
1348      bool result = Target.resolveSymbolicName(Constraint,
1349                                               &(*OutCons)[0],
1350                                               OutCons->size(), Index);
1351      assert(result && "Could not resolve symbolic name"); (void)result;
1352      Result += llvm::utostr(Index);
1353      break;
1354    }
1355    }
1356
1357    Constraint++;
1358  }
1359
1360  return Result;
1361}
1362
1363/// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1364/// as using a particular register add that as a constraint that will be used
1365/// in this asm stmt.
1366static std::string
1367AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1368                       const TargetInfo &Target, CodeGenModule &CGM,
1369                       const AsmStmt &Stmt) {
1370  const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1371  if (!AsmDeclRef)
1372    return Constraint;
1373  const ValueDecl &Value = *AsmDeclRef->getDecl();
1374  const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1375  if (!Variable)
1376    return Constraint;
1377  if (Variable->getStorageClass() != SC_Register)
1378    return Constraint;
1379  AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1380  if (!Attr)
1381    return Constraint;
1382  StringRef Register = Attr->getLabel();
1383  assert(Target.isValidGCCRegisterName(Register));
1384  // We're using validateOutputConstraint here because we only care if
1385  // this is a register constraint.
1386  TargetInfo::ConstraintInfo Info(Constraint, "");
1387  if (Target.validateOutputConstraint(Info) &&
1388      !Info.allowsRegister()) {
1389    CGM.ErrorUnsupported(&Stmt, "__asm__");
1390    return Constraint;
1391  }
1392  // Canonicalize the register here before returning it.
1393  Register = Target.getNormalizedGCCRegisterName(Register);
1394  return "{" + Register.str() + "}";
1395}
1396
1397llvm::Value*
1398CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
1399                                    LValue InputValue, QualType InputType,
1400                                    std::string &ConstraintStr) {
1401  llvm::Value *Arg;
1402  if (Info.allowsRegister() || !Info.allowsMemory()) {
1403    if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
1404      Arg = EmitLoadOfLValue(InputValue).getScalarVal();
1405    } else {
1406      llvm::Type *Ty = ConvertType(InputType);
1407      uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
1408      if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
1409        Ty = llvm::IntegerType::get(getLLVMContext(), Size);
1410        Ty = llvm::PointerType::getUnqual(Ty);
1411
1412        Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1413                                                       Ty));
1414      } else {
1415        Arg = InputValue.getAddress();
1416        ConstraintStr += '*';
1417      }
1418    }
1419  } else {
1420    Arg = InputValue.getAddress();
1421    ConstraintStr += '*';
1422  }
1423
1424  return Arg;
1425}
1426
1427llvm::Value* CodeGenFunction::EmitAsmInput(
1428                                         const TargetInfo::ConstraintInfo &Info,
1429                                           const Expr *InputExpr,
1430                                           std::string &ConstraintStr) {
1431  if (Info.allowsRegister() || !Info.allowsMemory())
1432    if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
1433      return EmitScalarExpr(InputExpr);
1434
1435  InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1436  LValue Dest = EmitLValue(InputExpr);
1437  return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr);
1438}
1439
1440/// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
1441/// asm call instruction.  The !srcloc MDNode contains a list of constant
1442/// integers which are the source locations of the start of each line in the
1443/// asm.
1444static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1445                                      CodeGenFunction &CGF) {
1446  SmallVector<llvm::Value *, 8> Locs;
1447  // Add the location of the first line to the MDNode.
1448  Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1449                                        Str->getLocStart().getRawEncoding()));
1450  StringRef StrVal = Str->getString();
1451  if (!StrVal.empty()) {
1452    const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1453    const LangOptions &LangOpts = CGF.CGM.getLangOpts();
1454
1455    // Add the location of the start of each subsequent line of the asm to the
1456    // MDNode.
1457    for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
1458      if (StrVal[i] != '\n') continue;
1459      SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
1460                                                      CGF.getTarget());
1461      Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1462                                            LineLoc.getRawEncoding()));
1463    }
1464  }
1465
1466  return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
1467}
1468
1469void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
1470  // Assemble the final asm string.
1471  std::string AsmString = S.generateAsmString(getContext());
1472
1473  // Get all the output and input constraints together.
1474  SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1475  SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1476
1477  for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1478    StringRef Name;
1479    if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1480      Name = GAS->getOutputName(i);
1481    TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
1482    bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
1483    assert(IsValid && "Failed to parse output constraint");
1484    OutputConstraintInfos.push_back(Info);
1485  }
1486
1487  for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1488    StringRef Name;
1489    if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1490      Name = GAS->getInputName(i);
1491    TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
1492    bool IsValid =
1493      getTarget().validateInputConstraint(OutputConstraintInfos.data(),
1494                                          S.getNumOutputs(), Info);
1495    assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1496    InputConstraintInfos.push_back(Info);
1497  }
1498
1499  std::string Constraints;
1500
1501  std::vector<LValue> ResultRegDests;
1502  std::vector<QualType> ResultRegQualTys;
1503  std::vector<llvm::Type *> ResultRegTypes;
1504  std::vector<llvm::Type *> ResultTruncRegTypes;
1505  std::vector<llvm::Type *> ArgTypes;
1506  std::vector<llvm::Value*> Args;
1507
1508  // Keep track of inout constraints.
1509  std::string InOutConstraints;
1510  std::vector<llvm::Value*> InOutArgs;
1511  std::vector<llvm::Type*> InOutArgTypes;
1512
1513  for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1514    TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1515
1516    // Simplify the output constraint.
1517    std::string OutputConstraint(S.getOutputConstraint(i));
1518    OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
1519                                          getTarget());
1520
1521    const Expr *OutExpr = S.getOutputExpr(i);
1522    OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1523
1524    OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
1525                                              getTarget(), CGM, S);
1526
1527    LValue Dest = EmitLValue(OutExpr);
1528    if (!Constraints.empty())
1529      Constraints += ',';
1530
1531    // If this is a register output, then make the inline asm return it
1532    // by-value.  If this is a memory result, return the value by-reference.
1533    if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
1534      Constraints += "=" + OutputConstraint;
1535      ResultRegQualTys.push_back(OutExpr->getType());
1536      ResultRegDests.push_back(Dest);
1537      ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1538      ResultTruncRegTypes.push_back(ResultRegTypes.back());
1539
1540      // If this output is tied to an input, and if the input is larger, then
1541      // we need to set the actual result type of the inline asm node to be the
1542      // same as the input type.
1543      if (Info.hasMatchingInput()) {
1544        unsigned InputNo;
1545        for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1546          TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1547          if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1548            break;
1549        }
1550        assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1551
1552        QualType InputTy = S.getInputExpr(InputNo)->getType();
1553        QualType OutputType = OutExpr->getType();
1554
1555        uint64_t InputSize = getContext().getTypeSize(InputTy);
1556        if (getContext().getTypeSize(OutputType) < InputSize) {
1557          // Form the asm to return the value as a larger integer or fp type.
1558          ResultRegTypes.back() = ConvertType(InputTy);
1559        }
1560      }
1561      if (llvm::Type* AdjTy =
1562            getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1563                                                 ResultRegTypes.back()))
1564        ResultRegTypes.back() = AdjTy;
1565    } else {
1566      ArgTypes.push_back(Dest.getAddress()->getType());
1567      Args.push_back(Dest.getAddress());
1568      Constraints += "=*";
1569      Constraints += OutputConstraint;
1570    }
1571
1572    if (Info.isReadWrite()) {
1573      InOutConstraints += ',';
1574
1575      const Expr *InputExpr = S.getOutputExpr(i);
1576      llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
1577                                            InOutConstraints);
1578
1579      if (llvm::Type* AdjTy =
1580            getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1581                                                 Arg->getType()))
1582        Arg = Builder.CreateBitCast(Arg, AdjTy);
1583
1584      if (Info.allowsRegister())
1585        InOutConstraints += llvm::utostr(i);
1586      else
1587        InOutConstraints += OutputConstraint;
1588
1589      InOutArgTypes.push_back(Arg->getType());
1590      InOutArgs.push_back(Arg);
1591    }
1592  }
1593
1594  unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1595
1596  for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1597    const Expr *InputExpr = S.getInputExpr(i);
1598
1599    TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1600
1601    if (!Constraints.empty())
1602      Constraints += ',';
1603
1604    // Simplify the input constraint.
1605    std::string InputConstraint(S.getInputConstraint(i));
1606    InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
1607                                         &OutputConstraintInfos);
1608
1609    InputConstraint =
1610      AddVariableConstraints(InputConstraint,
1611                            *InputExpr->IgnoreParenNoopCasts(getContext()),
1612                            getTarget(), CGM, S);
1613
1614    llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
1615
1616    // If this input argument is tied to a larger output result, extend the
1617    // input to be the same size as the output.  The LLVM backend wants to see
1618    // the input and output of a matching constraint be the same size.  Note
1619    // that GCC does not define what the top bits are here.  We use zext because
1620    // that is usually cheaper, but LLVM IR should really get an anyext someday.
1621    if (Info.hasTiedOperand()) {
1622      unsigned Output = Info.getTiedOperand();
1623      QualType OutputType = S.getOutputExpr(Output)->getType();
1624      QualType InputTy = InputExpr->getType();
1625
1626      if (getContext().getTypeSize(OutputType) >
1627          getContext().getTypeSize(InputTy)) {
1628        // Use ptrtoint as appropriate so that we can do our extension.
1629        if (isa<llvm::PointerType>(Arg->getType()))
1630          Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
1631        llvm::Type *OutputTy = ConvertType(OutputType);
1632        if (isa<llvm::IntegerType>(OutputTy))
1633          Arg = Builder.CreateZExt(Arg, OutputTy);
1634        else if (isa<llvm::PointerType>(OutputTy))
1635          Arg = Builder.CreateZExt(Arg, IntPtrTy);
1636        else {
1637          assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
1638          Arg = Builder.CreateFPExt(Arg, OutputTy);
1639        }
1640      }
1641    }
1642    if (llvm::Type* AdjTy =
1643              getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
1644                                                   Arg->getType()))
1645      Arg = Builder.CreateBitCast(Arg, AdjTy);
1646
1647    ArgTypes.push_back(Arg->getType());
1648    Args.push_back(Arg);
1649    Constraints += InputConstraint;
1650  }
1651
1652  // Append the "input" part of inout constraints last.
1653  for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1654    ArgTypes.push_back(InOutArgTypes[i]);
1655    Args.push_back(InOutArgs[i]);
1656  }
1657  Constraints += InOutConstraints;
1658
1659  // Clobbers
1660  for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1661    StringRef Clobber = S.getClobber(i);
1662
1663    if (Clobber != "memory" && Clobber != "cc")
1664    Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
1665
1666    if (i != 0 || NumConstraints != 0)
1667      Constraints += ',';
1668
1669    Constraints += "~{";
1670    Constraints += Clobber;
1671    Constraints += '}';
1672  }
1673
1674  // Add machine specific clobbers
1675  std::string MachineClobbers = getTarget().getClobbers();
1676  if (!MachineClobbers.empty()) {
1677    if (!Constraints.empty())
1678      Constraints += ',';
1679    Constraints += MachineClobbers;
1680  }
1681
1682  llvm::Type *ResultType;
1683  if (ResultRegTypes.empty())
1684    ResultType = VoidTy;
1685  else if (ResultRegTypes.size() == 1)
1686    ResultType = ResultRegTypes[0];
1687  else
1688    ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
1689
1690  llvm::FunctionType *FTy =
1691    llvm::FunctionType::get(ResultType, ArgTypes, false);
1692
1693  bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
1694  llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
1695    llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
1696  llvm::InlineAsm *IA =
1697    llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
1698                         /* IsAlignStack */ false, AsmDialect);
1699  llvm::CallInst *Result = Builder.CreateCall(IA, Args);
1700  Result->addAttribute(llvm::AttributeSet::FunctionIndex,
1701                       llvm::Attribute::NoUnwind);
1702
1703  // Slap the source location of the inline asm into a !srcloc metadata on the
1704  // call.  FIXME: Handle metadata for MS-style inline asms.
1705  if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S))
1706    Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(),
1707                                                   *this));
1708
1709  // Extract all of the register value results from the asm.
1710  std::vector<llvm::Value*> RegResults;
1711  if (ResultRegTypes.size() == 1) {
1712    RegResults.push_back(Result);
1713  } else {
1714    for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
1715      llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
1716      RegResults.push_back(Tmp);
1717    }
1718  }
1719
1720  for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1721    llvm::Value *Tmp = RegResults[i];
1722
1723    // If the result type of the LLVM IR asm doesn't match the result type of
1724    // the expression, do the conversion.
1725    if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1726      llvm::Type *TruncTy = ResultTruncRegTypes[i];
1727
1728      // Truncate the integer result to the right size, note that TruncTy can be
1729      // a pointer.
1730      if (TruncTy->isFloatingPointTy())
1731        Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
1732      else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
1733        uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
1734        Tmp = Builder.CreateTrunc(Tmp,
1735                   llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
1736        Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
1737      } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
1738        uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
1739        Tmp = Builder.CreatePtrToInt(Tmp,
1740                   llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
1741        Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1742      } else if (TruncTy->isIntegerTy()) {
1743        Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1744      } else if (TruncTy->isVectorTy()) {
1745        Tmp = Builder.CreateBitCast(Tmp, TruncTy);
1746      }
1747    }
1748
1749    EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
1750  }
1751}
1752
1753void CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S) {
1754  llvm_unreachable("not implemented yet");
1755}
1756