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"
25 using namespace clang;
26 using namespace CodeGen;
27 
28 //===----------------------------------------------------------------------===//
29 //                              Statement Emission
30 //===----------------------------------------------------------------------===//
31 
32 void 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     if (++NumStopPoints == 1)
42       FirstStopPoint = Loc;
43   }
44 }
45 
46 void CodeGenFunction::EmitStmt(const Stmt *S) {
47   assert(S && "Null statement?");
48 
49   // These statements have their own debug info handling.
50   if (EmitSimpleStmt(S))
51     return;
52 
53   // Check if we are generating unreachable code.
54   if (!HaveInsertPoint()) {
55     // If so, and the statement doesn't contain a label, then we do not need to
56     // generate actual code. This is safe because (1) the current point is
57     // unreachable, so we don't need to execute the code, and (2) we've already
58     // handled the statements which update internal data structures (like the
59     // local variable map) which could be used by subsequent statements.
60     if (!ContainsLabel(S)) {
61       // Verify that any decl statements were handled as simple, they may be in
62       // scope of subsequent reachable statements.
63       assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
64       return;
65     }
66 
67     // Otherwise, make a new block to hold the code.
68     EnsureInsertPoint();
69   }
70 
71   // Generate a stoppoint if we are emitting debug info.
72   EmitStopPoint(S);
73 
74   switch (S->getStmtClass()) {
75   case Stmt::NoStmtClass:
76   case Stmt::CXXCatchStmtClass:
77   case Stmt::SEHExceptStmtClass:
78   case Stmt::SEHFinallyStmtClass:
79   case Stmt::MSDependentExistsStmtClass:
80     llvm_unreachable("invalid statement class to emit generically");
81   case Stmt::NullStmtClass:
82   case Stmt::CompoundStmtClass:
83   case Stmt::DeclStmtClass:
84   case Stmt::LabelStmtClass:
85   case Stmt::AttributedStmtClass:
86   case Stmt::GotoStmtClass:
87   case Stmt::BreakStmtClass:
88   case Stmt::ContinueStmtClass:
89   case Stmt::DefaultStmtClass:
90   case Stmt::CaseStmtClass:
91     llvm_unreachable("should have emitted these statements as simple");
92 
93 #define STMT(Type, Base)
94 #define ABSTRACT_STMT(Op)
95 #define EXPR(Type, Base) \
96   case Stmt::Type##Class:
97 #include "clang/AST/StmtNodes.inc"
98   {
99     // Remember the block we came in on.
100     llvm::BasicBlock *incoming = Builder.GetInsertBlock();
101     assert(incoming && "expression emission must have an insertion point");
102 
103     EmitIgnoredExpr(cast<Expr>(S));
104 
105     llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
106     assert(outgoing && "expression emission cleared block!");
107 
108     // The expression emitters assume (reasonably!) that the insertion
109     // point is always set.  To maintain that, the call-emission code
110     // for noreturn functions has to enter a new block with no
111     // predecessors.  We want to kill that block and mark the current
112     // insertion point unreachable in the common case of a call like
113     // "exit();".  Since expression emission doesn't otherwise create
114     // blocks with no predecessors, we can just test for that.
115     // However, we must be careful not to do this to our incoming
116     // block, because *statement* emission does sometimes create
117     // reachable blocks which will have no predecessors until later in
118     // the function.  This occurs with, e.g., labels that are not
119     // reachable by fallthrough.
120     if (incoming != outgoing && outgoing->use_empty()) {
121       outgoing->eraseFromParent();
122       Builder.ClearInsertionPoint();
123     }
124     break;
125   }
126 
127   case Stmt::IndirectGotoStmtClass:
128     EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
129 
130   case Stmt::IfStmtClass:       EmitIfStmt(cast<IfStmt>(*S));             break;
131   case Stmt::WhileStmtClass:    EmitWhileStmt(cast<WhileStmt>(*S));       break;
132   case Stmt::DoStmtClass:       EmitDoStmt(cast<DoStmt>(*S));             break;
133   case Stmt::ForStmtClass:      EmitForStmt(cast<ForStmt>(*S));           break;
134 
135   case Stmt::ReturnStmtClass:   EmitReturnStmt(cast<ReturnStmt>(*S));     break;
136 
137   case Stmt::SwitchStmtClass:   EmitSwitchStmt(cast<SwitchStmt>(*S));     break;
138   case Stmt::GCCAsmStmtClass:   // Intentional fall-through.
139   case Stmt::MSAsmStmtClass:    EmitAsmStmt(cast<AsmStmt>(*S));           break;
140   case Stmt::CapturedStmtClass:
141     EmitCapturedStmt(cast<CapturedStmt>(*S));
142     break;
143   case Stmt::ObjCAtTryStmtClass:
144     EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
145     break;
146   case Stmt::ObjCAtCatchStmtClass:
147     llvm_unreachable(
148                     "@catch statements should be handled by EmitObjCAtTryStmt");
149   case Stmt::ObjCAtFinallyStmtClass:
150     llvm_unreachable(
151                   "@finally statements should be handled by EmitObjCAtTryStmt");
152   case Stmt::ObjCAtThrowStmtClass:
153     EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
154     break;
155   case Stmt::ObjCAtSynchronizedStmtClass:
156     EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
157     break;
158   case Stmt::ObjCForCollectionStmtClass:
159     EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
160     break;
161   case Stmt::ObjCAutoreleasePoolStmtClass:
162     EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
163     break;
164 
165   case Stmt::CXXTryStmtClass:
166     EmitCXXTryStmt(cast<CXXTryStmt>(*S));
167     break;
168   case Stmt::CXXForRangeStmtClass:
169     EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
170   case Stmt::SEHTryStmtClass:
171     // FIXME Not yet implemented
172     break;
173   }
174 }
175 
176 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
177   switch (S->getStmtClass()) {
178   default: return false;
179   case Stmt::NullStmtClass: break;
180   case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
181   case Stmt::DeclStmtClass:     EmitDeclStmt(cast<DeclStmt>(*S));         break;
182   case Stmt::LabelStmtClass:    EmitLabelStmt(cast<LabelStmt>(*S));       break;
183   case Stmt::AttributedStmtClass:
184                             EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
185   case Stmt::GotoStmtClass:     EmitGotoStmt(cast<GotoStmt>(*S));         break;
186   case Stmt::BreakStmtClass:    EmitBreakStmt(cast<BreakStmt>(*S));       break;
187   case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
188   case Stmt::DefaultStmtClass:  EmitDefaultStmt(cast<DefaultStmt>(*S));   break;
189   case Stmt::CaseStmtClass:     EmitCaseStmt(cast<CaseStmt>(*S));         break;
190   }
191 
192   return true;
193 }
194 
195 /// EmitCompoundStmt - Emit a compound statement {..} node.  If GetLast is true,
196 /// this captures the expression result of the last sub-statement and returns it
197 /// (for use by the statement expression extension).
198 RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
199                                          AggValueSlot AggSlot) {
200   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
201                              "LLVM IR generation of compound statement ('{}')");
202 
203   // Keep track of the current cleanup stack depth, including debug scopes.
204   LexicalScope Scope(*this, S.getSourceRange());
205 
206   return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
207 }
208 
209 RValue CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast,
210                                          AggValueSlot AggSlot) {
211 
212   for (CompoundStmt::const_body_iterator I = S.body_begin(),
213        E = S.body_end()-GetLast; I != E; ++I)
214     EmitStmt(*I);
215 
216   RValue RV;
217   if (!GetLast)
218     RV = RValue::get(0);
219   else {
220     // We have to special case labels here.  They are statements, but when put
221     // at the end of a statement expression, they yield the value of their
222     // subexpression.  Handle this by walking through all labels we encounter,
223     // emitting them before we evaluate the subexpr.
224     const Stmt *LastStmt = S.body_back();
225     while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
226       EmitLabel(LS->getDecl());
227       LastStmt = LS->getSubStmt();
228     }
229 
230     EnsureInsertPoint();
231 
232     RV = EmitAnyExpr(cast<Expr>(LastStmt), AggSlot);
233   }
234 
235   return RV;
236 }
237 
238 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
239   llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
240 
241   // If there is a cleanup stack, then we it isn't worth trying to
242   // simplify this block (we would need to remove it from the scope map
243   // and cleanup entry).
244   if (!EHStack.empty())
245     return;
246 
247   // Can only simplify direct branches.
248   if (!BI || !BI->isUnconditional())
249     return;
250 
251   // Can only simplify empty blocks.
252   if (BI != BB->begin())
253     return;
254 
255   BB->replaceAllUsesWith(BI->getSuccessor(0));
256   BI->eraseFromParent();
257   BB->eraseFromParent();
258 }
259 
260 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
261   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
262 
263   // Fall out of the current block (if necessary).
264   EmitBranch(BB);
265 
266   if (IsFinished && BB->use_empty()) {
267     delete BB;
268     return;
269   }
270 
271   // Place the block after the current block, if possible, or else at
272   // the end of the function.
273   if (CurBB && CurBB->getParent())
274     CurFn->getBasicBlockList().insertAfter(CurBB, BB);
275   else
276     CurFn->getBasicBlockList().push_back(BB);
277   Builder.SetInsertPoint(BB);
278 }
279 
280 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
281   // Emit a branch from the current block to the target one if this
282   // was a real block.  If this was just a fall-through block after a
283   // terminator, don't emit it.
284   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
285 
286   if (!CurBB || CurBB->getTerminator()) {
287     // If there is no insert point or the previous block is already
288     // terminated, don't touch it.
289   } else {
290     // Otherwise, create a fall-through branch.
291     Builder.CreateBr(Target);
292   }
293 
294   Builder.ClearInsertionPoint();
295 }
296 
297 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
298   bool inserted = false;
299   for (llvm::BasicBlock::use_iterator
300          i = block->use_begin(), e = block->use_end(); i != e; ++i) {
301     if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(*i)) {
302       CurFn->getBasicBlockList().insertAfter(insn->getParent(), block);
303       inserted = true;
304       break;
305     }
306   }
307 
308   if (!inserted)
309     CurFn->getBasicBlockList().push_back(block);
310 
311   Builder.SetInsertPoint(block);
312 }
313 
314 CodeGenFunction::JumpDest
315 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
316   JumpDest &Dest = LabelMap[D];
317   if (Dest.isValid()) return Dest;
318 
319   // Create, but don't insert, the new block.
320   Dest = JumpDest(createBasicBlock(D->getName()),
321                   EHScopeStack::stable_iterator::invalid(),
322                   NextCleanupDestIndex++);
323   return Dest;
324 }
325 
326 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
327   // Add this label to the current lexical scope if we're within any
328   // normal cleanups.  Jumps "in" to this label --- when permitted by
329   // the language --- may need to be routed around such cleanups.
330   if (EHStack.hasNormalCleanups() && CurLexicalScope)
331     CurLexicalScope->addLabel(D);
332 
333   JumpDest &Dest = LabelMap[D];
334 
335   // If we didn't need a forward reference to this label, just go
336   // ahead and create a destination at the current scope.
337   if (!Dest.isValid()) {
338     Dest = getJumpDestInCurrentScope(D->getName());
339 
340   // Otherwise, we need to give this label a target depth and remove
341   // it from the branch-fixups list.
342   } else {
343     assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
344     Dest.setScopeDepth(EHStack.stable_begin());
345     ResolveBranchFixups(Dest.getBlock());
346   }
347 
348   EmitBlock(Dest.getBlock());
349 }
350 
351 /// Change the cleanup scope of the labels in this lexical scope to
352 /// match the scope of the enclosing context.
353 void CodeGenFunction::LexicalScope::rescopeLabels() {
354   assert(!Labels.empty());
355   EHScopeStack::stable_iterator innermostScope
356     = CGF.EHStack.getInnermostNormalCleanup();
357 
358   // Change the scope depth of all the labels.
359   for (SmallVectorImpl<const LabelDecl*>::const_iterator
360          i = Labels.begin(), e = Labels.end(); i != e; ++i) {
361     assert(CGF.LabelMap.count(*i));
362     JumpDest &dest = CGF.LabelMap.find(*i)->second;
363     assert(dest.getScopeDepth().isValid());
364     assert(innermostScope.encloses(dest.getScopeDepth()));
365     dest.setScopeDepth(innermostScope);
366   }
367 
368   // Reparent the labels if the new scope also has cleanups.
369   if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
370     ParentScope->Labels.append(Labels.begin(), Labels.end());
371   }
372 }
373 
374 
375 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
376   EmitLabel(S.getDecl());
377   EmitStmt(S.getSubStmt());
378 }
379 
380 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
381   EmitStmt(S.getSubStmt());
382 }
383 
384 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
385   // If this code is reachable then emit a stop point (if generating
386   // debug info). We have to do this ourselves because we are on the
387   // "simple" statement path.
388   if (HaveInsertPoint())
389     EmitStopPoint(&S);
390 
391   EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
392 }
393 
394 
395 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
396   if (const LabelDecl *Target = S.getConstantTarget()) {
397     EmitBranchThroughCleanup(getJumpDestForLabel(Target));
398     return;
399   }
400 
401   // Ensure that we have an i8* for our PHI node.
402   llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
403                                          Int8PtrTy, "addr");
404   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
405 
406   // Get the basic block for the indirect goto.
407   llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
408 
409   // The first instruction in the block has to be the PHI for the switch dest,
410   // add an entry for this branch.
411   cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
412 
413   EmitBranch(IndGotoBB);
414 }
415 
416 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
417   // C99 6.8.4.1: The first substatement is executed if the expression compares
418   // unequal to 0.  The condition must be a scalar type.
419   RunCleanupsScope ConditionScope(*this);
420 
421   if (S.getConditionVariable())
422     EmitAutoVarDecl(*S.getConditionVariable());
423 
424   // If the condition constant folds and can be elided, try to avoid emitting
425   // the condition and the dead arm of the if/else.
426   bool CondConstant;
427   if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) {
428     // Figure out which block (then or else) is executed.
429     const Stmt *Executed = S.getThen();
430     const Stmt *Skipped  = S.getElse();
431     if (!CondConstant)  // Condition false?
432       std::swap(Executed, Skipped);
433 
434     // If the skipped block has no labels in it, just emit the executed block.
435     // This avoids emitting dead code and simplifies the CFG substantially.
436     if (!ContainsLabel(Skipped)) {
437       if (Executed) {
438         RunCleanupsScope ExecutedScope(*this);
439         EmitStmt(Executed);
440       }
441       return;
442     }
443   }
444 
445   // Otherwise, the condition did not fold, or we couldn't elide it.  Just emit
446   // the conditional branch.
447   llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
448   llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
449   llvm::BasicBlock *ElseBlock = ContBlock;
450   if (S.getElse())
451     ElseBlock = createBasicBlock("if.else");
452   EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
453 
454   // Emit the 'then' code.
455   EmitBlock(ThenBlock);
456   {
457     RunCleanupsScope ThenScope(*this);
458     EmitStmt(S.getThen());
459   }
460   EmitBranch(ContBlock);
461 
462   // Emit the 'else' code if present.
463   if (const Stmt *Else = S.getElse()) {
464     // There is no need to emit line number for unconditional branch.
465     if (getDebugInfo())
466       Builder.SetCurrentDebugLocation(llvm::DebugLoc());
467     EmitBlock(ElseBlock);
468     {
469       RunCleanupsScope ElseScope(*this);
470       EmitStmt(Else);
471     }
472     // There is no need to emit line number for unconditional branch.
473     if (getDebugInfo())
474       Builder.SetCurrentDebugLocation(llvm::DebugLoc());
475     EmitBranch(ContBlock);
476   }
477 
478   // Emit the continuation block for code after the if.
479   EmitBlock(ContBlock, true);
480 }
481 
482 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
483   // Emit the header for the loop, which will also become
484   // the continue target.
485   JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
486   EmitBlock(LoopHeader.getBlock());
487 
488   // Create an exit block for when the condition fails, which will
489   // also become the break target.
490   JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
491 
492   // Store the blocks to use for break and continue.
493   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
494 
495   // C++ [stmt.while]p2:
496   //   When the condition of a while statement is a declaration, the
497   //   scope of the variable that is declared extends from its point
498   //   of declaration (3.3.2) to the end of the while statement.
499   //   [...]
500   //   The object created in a condition is destroyed and created
501   //   with each iteration of the loop.
502   RunCleanupsScope ConditionScope(*this);
503 
504   if (S.getConditionVariable())
505     EmitAutoVarDecl(*S.getConditionVariable());
506 
507   // Evaluate the conditional in the while header.  C99 6.8.5.1: The
508   // evaluation of the controlling expression takes place before each
509   // execution of the loop body.
510   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
511 
512   // while(1) is common, avoid extra exit blocks.  Be sure
513   // to correctly handle break/continue though.
514   bool EmitBoolCondBranch = true;
515   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
516     if (C->isOne())
517       EmitBoolCondBranch = false;
518 
519   // As long as the condition is true, go to the loop body.
520   llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
521   if (EmitBoolCondBranch) {
522     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
523     if (ConditionScope.requiresCleanups())
524       ExitBlock = createBasicBlock("while.exit");
525 
526     Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
527 
528     if (ExitBlock != LoopExit.getBlock()) {
529       EmitBlock(ExitBlock);
530       EmitBranchThroughCleanup(LoopExit);
531     }
532   }
533 
534   // Emit the loop body.  We have to emit this in a cleanup scope
535   // because it might be a singleton DeclStmt.
536   {
537     RunCleanupsScope BodyScope(*this);
538     EmitBlock(LoopBody);
539     EmitStmt(S.getBody());
540   }
541 
542   BreakContinueStack.pop_back();
543 
544   // Immediately force cleanup.
545   ConditionScope.ForceCleanup();
546 
547   // Branch to the loop header again.
548   EmitBranch(LoopHeader.getBlock());
549 
550   // Emit the exit block.
551   EmitBlock(LoopExit.getBlock(), true);
552 
553   // The LoopHeader typically is just a branch if we skipped emitting
554   // a branch, try to erase it.
555   if (!EmitBoolCondBranch)
556     SimplifyForwardingBlocks(LoopHeader.getBlock());
557 }
558 
559 void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
560   JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
561   JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
562 
563   // Store the blocks to use for break and continue.
564   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
565 
566   // Emit the body of the loop.
567   llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
568   EmitBlock(LoopBody);
569   {
570     RunCleanupsScope BodyScope(*this);
571     EmitStmt(S.getBody());
572   }
573 
574   BreakContinueStack.pop_back();
575 
576   EmitBlock(LoopCond.getBlock());
577 
578   // C99 6.8.5.2: "The evaluation of the controlling expression takes place
579   // after each execution of the loop body."
580 
581   // Evaluate the conditional in the while header.
582   // C99 6.8.5p2/p4: The first substatement is executed if the expression
583   // compares unequal to 0.  The condition must be a scalar type.
584   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
585 
586   // "do {} while (0)" is common in macros, avoid extra blocks.  Be sure
587   // to correctly handle break/continue though.
588   bool EmitBoolCondBranch = true;
589   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
590     if (C->isZero())
591       EmitBoolCondBranch = false;
592 
593   // As long as the condition is true, iterate the loop.
594   if (EmitBoolCondBranch)
595     Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock());
596 
597   // Emit the exit block.
598   EmitBlock(LoopExit.getBlock());
599 
600   // The DoCond block typically is just a branch if we skipped
601   // emitting a branch, try to erase it.
602   if (!EmitBoolCondBranch)
603     SimplifyForwardingBlocks(LoopCond.getBlock());
604 }
605 
606 void CodeGenFunction::EmitForStmt(const ForStmt &S) {
607   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
608 
609   RunCleanupsScope ForScope(*this);
610 
611   CGDebugInfo *DI = getDebugInfo();
612   if (DI)
613     DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
614 
615   // Evaluate the first part before the loop.
616   if (S.getInit())
617     EmitStmt(S.getInit());
618 
619   // Start the loop with a block that tests the condition.
620   // If there's an increment, the continue scope will be overwritten
621   // later.
622   JumpDest Continue = getJumpDestInCurrentScope("for.cond");
623   llvm::BasicBlock *CondBlock = Continue.getBlock();
624   EmitBlock(CondBlock);
625 
626   // Create a cleanup scope for the condition variable cleanups.
627   RunCleanupsScope ConditionScope(*this);
628 
629   llvm::Value *BoolCondVal = 0;
630   if (S.getCond()) {
631     // If the for statement has a condition scope, emit the local variable
632     // declaration.
633     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
634     if (S.getConditionVariable()) {
635       EmitAutoVarDecl(*S.getConditionVariable());
636     }
637 
638     // If there are any cleanups between here and the loop-exit scope,
639     // create a block to stage a loop exit along.
640     if (ForScope.requiresCleanups())
641       ExitBlock = createBasicBlock("for.cond.cleanup");
642 
643     // As long as the condition is true, iterate the loop.
644     llvm::BasicBlock *ForBody = createBasicBlock("for.body");
645 
646     // C99 6.8.5p2/p4: The first substatement is executed if the expression
647     // compares unequal to 0.  The condition must be a scalar type.
648     BoolCondVal = EvaluateExprAsBool(S.getCond());
649     Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
650 
651     if (ExitBlock != LoopExit.getBlock()) {
652       EmitBlock(ExitBlock);
653       EmitBranchThroughCleanup(LoopExit);
654     }
655 
656     EmitBlock(ForBody);
657   } else {
658     // Treat it as a non-zero constant.  Don't even create a new block for the
659     // body, just fall into it.
660   }
661 
662   // If the for loop doesn't have an increment we can just use the
663   // condition as the continue block.  Otherwise we'll need to create
664   // a block for it (in the current scope, i.e. in the scope of the
665   // condition), and that we will become our continue block.
666   if (S.getInc())
667     Continue = getJumpDestInCurrentScope("for.inc");
668 
669   // Store the blocks to use for break and continue.
670   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
671 
672   {
673     // Create a separate cleanup scope for the body, in case it is not
674     // a compound statement.
675     RunCleanupsScope BodyScope(*this);
676     EmitStmt(S.getBody());
677   }
678 
679   // If there is an increment, emit it next.
680   if (S.getInc()) {
681     EmitBlock(Continue.getBlock());
682     EmitStmt(S.getInc());
683   }
684 
685   BreakContinueStack.pop_back();
686 
687   ConditionScope.ForceCleanup();
688   EmitBranch(CondBlock);
689 
690   ForScope.ForceCleanup();
691 
692   if (DI)
693     DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
694 
695   // Emit the fall-through block.
696   EmitBlock(LoopExit.getBlock(), true);
697 }
698 
699 void CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S) {
700   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
701 
702   RunCleanupsScope ForScope(*this);
703 
704   CGDebugInfo *DI = getDebugInfo();
705   if (DI)
706     DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
707 
708   // Evaluate the first pieces before the loop.
709   EmitStmt(S.getRangeStmt());
710   EmitStmt(S.getBeginEndStmt());
711 
712   // Start the loop with a block that tests the condition.
713   // If there's an increment, the continue scope will be overwritten
714   // later.
715   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
716   EmitBlock(CondBlock);
717 
718   // If there are any cleanups between here and the loop-exit scope,
719   // create a block to stage a loop exit along.
720   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
721   if (ForScope.requiresCleanups())
722     ExitBlock = createBasicBlock("for.cond.cleanup");
723 
724   // The loop body, consisting of the specified body and the loop variable.
725   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
726 
727   // The body is executed if the expression, contextually converted
728   // to bool, is true.
729   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
730   Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
731 
732   if (ExitBlock != LoopExit.getBlock()) {
733     EmitBlock(ExitBlock);
734     EmitBranchThroughCleanup(LoopExit);
735   }
736 
737   EmitBlock(ForBody);
738 
739   // Create a block for the increment. In case of a 'continue', we jump there.
740   JumpDest Continue = getJumpDestInCurrentScope("for.inc");
741 
742   // Store the blocks to use for break and continue.
743   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
744 
745   {
746     // Create a separate cleanup scope for the loop variable and body.
747     RunCleanupsScope BodyScope(*this);
748     EmitStmt(S.getLoopVarStmt());
749     EmitStmt(S.getBody());
750   }
751 
752   // If there is an increment, emit it next.
753   EmitBlock(Continue.getBlock());
754   EmitStmt(S.getInc());
755 
756   BreakContinueStack.pop_back();
757 
758   EmitBranch(CondBlock);
759 
760   ForScope.ForceCleanup();
761 
762   if (DI)
763     DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
764 
765   // Emit the fall-through block.
766   EmitBlock(LoopExit.getBlock(), true);
767 }
768 
769 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
770   if (RV.isScalar()) {
771     Builder.CreateStore(RV.getScalarVal(), ReturnValue);
772   } else if (RV.isAggregate()) {
773     EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
774   } else {
775     EmitStoreOfComplex(RV.getComplexVal(),
776                        MakeNaturalAlignAddrLValue(ReturnValue, Ty),
777                        /*init*/ true);
778   }
779   EmitBranchThroughCleanup(ReturnBlock);
780 }
781 
782 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
783 /// if the function returns void, or may be missing one if the function returns
784 /// non-void.  Fun stuff :).
785 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
786   // Emit the result value, even if unused, to evalute the side effects.
787   const Expr *RV = S.getRetValue();
788 
789   // Treat block literals in a return expression as if they appeared
790   // in their own scope.  This permits a small, easily-implemented
791   // exception to our over-conservative rules about not jumping to
792   // statements following block literals with non-trivial cleanups.
793   RunCleanupsScope cleanupScope(*this);
794   if (const ExprWithCleanups *cleanups =
795         dyn_cast_or_null<ExprWithCleanups>(RV)) {
796     enterFullExpression(cleanups);
797     RV = cleanups->getSubExpr();
798   }
799 
800   // FIXME: Clean this up by using an LValue for ReturnTemp,
801   // EmitStoreThroughLValue, and EmitAnyExpr.
802   if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) {
803     // Apply the named return value optimization for this return statement,
804     // which means doing nothing: the appropriate result has already been
805     // constructed into the NRVO variable.
806 
807     // If there is an NRVO flag for this variable, set it to 1 into indicate
808     // that the cleanup code should not destroy the variable.
809     if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
810       Builder.CreateStore(Builder.getTrue(), NRVOFlag);
811   } else if (!ReturnValue) {
812     // Make sure not to return anything, but evaluate the expression
813     // for side effects.
814     if (RV)
815       EmitAnyExpr(RV);
816   } else if (RV == 0) {
817     // Do nothing (return value is left uninitialized)
818   } else if (FnRetTy->isReferenceType()) {
819     // If this function returns a reference, take the address of the expression
820     // rather than the value.
821     RValue Result = EmitReferenceBindingToExpr(RV, /*InitializedDecl=*/0);
822     Builder.CreateStore(Result.getScalarVal(), ReturnValue);
823   } else {
824     switch (getEvaluationKind(RV->getType())) {
825     case TEK_Scalar:
826       Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
827       break;
828     case TEK_Complex:
829       EmitComplexExprIntoLValue(RV,
830                      MakeNaturalAlignAddrLValue(ReturnValue, RV->getType()),
831                                 /*isInit*/ true);
832       break;
833     case TEK_Aggregate: {
834       CharUnits Alignment = getContext().getTypeAlignInChars(RV->getType());
835       EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Alignment,
836                                             Qualifiers(),
837                                             AggValueSlot::IsDestructed,
838                                             AggValueSlot::DoesNotNeedGCBarriers,
839                                             AggValueSlot::IsNotAliased));
840       break;
841     }
842     }
843   }
844 
845   if (RV == 0 || RV->isEvaluatable(getContext()))
846     ++NumSimpleReturnExprs;
847 
848   cleanupScope.ForceCleanup();
849   EmitBranchThroughCleanup(ReturnBlock);
850 }
851 
852 void 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 
863 void 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 
876 void 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.
892 void 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 
947 void 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 
1016 void 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 ///
1047 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
1048 static 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.
1174 static 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 
1225 void 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 
1317 static std::string
1318 SimplifyConstraint(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.
1366 static std::string
1367 AddVariableConstraints(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 
1397 llvm::Value*
1398 CodeGenFunction::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 
1427 llvm::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.
1444 static 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 
1469 void 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     TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
1479                                     S.getOutputName(i));
1480     bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
1481     assert(IsValid && "Failed to parse output constraint");
1482     OutputConstraintInfos.push_back(Info);
1483   }
1484 
1485   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1486     TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
1487                                     S.getInputName(i));
1488     bool IsValid =
1489       getTarget().validateInputConstraint(OutputConstraintInfos.data(),
1490                                           S.getNumOutputs(), Info);
1491     assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1492     InputConstraintInfos.push_back(Info);
1493   }
1494 
1495   std::string Constraints;
1496 
1497   std::vector<LValue> ResultRegDests;
1498   std::vector<QualType> ResultRegQualTys;
1499   std::vector<llvm::Type *> ResultRegTypes;
1500   std::vector<llvm::Type *> ResultTruncRegTypes;
1501   std::vector<llvm::Type *> ArgTypes;
1502   std::vector<llvm::Value*> Args;
1503 
1504   // Keep track of inout constraints.
1505   std::string InOutConstraints;
1506   std::vector<llvm::Value*> InOutArgs;
1507   std::vector<llvm::Type*> InOutArgTypes;
1508 
1509   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1510     TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1511 
1512     // Simplify the output constraint.
1513     std::string OutputConstraint(S.getOutputConstraint(i));
1514     OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
1515                                           getTarget());
1516 
1517     const Expr *OutExpr = S.getOutputExpr(i);
1518     OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1519 
1520     OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
1521                                               getTarget(), CGM, S);
1522 
1523     LValue Dest = EmitLValue(OutExpr);
1524     if (!Constraints.empty())
1525       Constraints += ',';
1526 
1527     // If this is a register output, then make the inline asm return it
1528     // by-value.  If this is a memory result, return the value by-reference.
1529     if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
1530       Constraints += "=" + OutputConstraint;
1531       ResultRegQualTys.push_back(OutExpr->getType());
1532       ResultRegDests.push_back(Dest);
1533       ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1534       ResultTruncRegTypes.push_back(ResultRegTypes.back());
1535 
1536       // If this output is tied to an input, and if the input is larger, then
1537       // we need to set the actual result type of the inline asm node to be the
1538       // same as the input type.
1539       if (Info.hasMatchingInput()) {
1540         unsigned InputNo;
1541         for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1542           TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1543           if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1544             break;
1545         }
1546         assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1547 
1548         QualType InputTy = S.getInputExpr(InputNo)->getType();
1549         QualType OutputType = OutExpr->getType();
1550 
1551         uint64_t InputSize = getContext().getTypeSize(InputTy);
1552         if (getContext().getTypeSize(OutputType) < InputSize) {
1553           // Form the asm to return the value as a larger integer or fp type.
1554           ResultRegTypes.back() = ConvertType(InputTy);
1555         }
1556       }
1557       if (llvm::Type* AdjTy =
1558             getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1559                                                  ResultRegTypes.back()))
1560         ResultRegTypes.back() = AdjTy;
1561     } else {
1562       ArgTypes.push_back(Dest.getAddress()->getType());
1563       Args.push_back(Dest.getAddress());
1564       Constraints += "=*";
1565       Constraints += OutputConstraint;
1566     }
1567 
1568     if (Info.isReadWrite()) {
1569       InOutConstraints += ',';
1570 
1571       const Expr *InputExpr = S.getOutputExpr(i);
1572       llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
1573                                             InOutConstraints);
1574 
1575       if (llvm::Type* AdjTy =
1576             getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1577                                                  Arg->getType()))
1578         Arg = Builder.CreateBitCast(Arg, AdjTy);
1579 
1580       if (Info.allowsRegister())
1581         InOutConstraints += llvm::utostr(i);
1582       else
1583         InOutConstraints += OutputConstraint;
1584 
1585       InOutArgTypes.push_back(Arg->getType());
1586       InOutArgs.push_back(Arg);
1587     }
1588   }
1589 
1590   unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1591 
1592   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1593     const Expr *InputExpr = S.getInputExpr(i);
1594 
1595     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1596 
1597     if (!Constraints.empty())
1598       Constraints += ',';
1599 
1600     // Simplify the input constraint.
1601     std::string InputConstraint(S.getInputConstraint(i));
1602     InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
1603                                          &OutputConstraintInfos);
1604 
1605     InputConstraint =
1606       AddVariableConstraints(InputConstraint,
1607                             *InputExpr->IgnoreParenNoopCasts(getContext()),
1608                             getTarget(), CGM, S);
1609 
1610     llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
1611 
1612     // If this input argument is tied to a larger output result, extend the
1613     // input to be the same size as the output.  The LLVM backend wants to see
1614     // the input and output of a matching constraint be the same size.  Note
1615     // that GCC does not define what the top bits are here.  We use zext because
1616     // that is usually cheaper, but LLVM IR should really get an anyext someday.
1617     if (Info.hasTiedOperand()) {
1618       unsigned Output = Info.getTiedOperand();
1619       QualType OutputType = S.getOutputExpr(Output)->getType();
1620       QualType InputTy = InputExpr->getType();
1621 
1622       if (getContext().getTypeSize(OutputType) >
1623           getContext().getTypeSize(InputTy)) {
1624         // Use ptrtoint as appropriate so that we can do our extension.
1625         if (isa<llvm::PointerType>(Arg->getType()))
1626           Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
1627         llvm::Type *OutputTy = ConvertType(OutputType);
1628         if (isa<llvm::IntegerType>(OutputTy))
1629           Arg = Builder.CreateZExt(Arg, OutputTy);
1630         else if (isa<llvm::PointerType>(OutputTy))
1631           Arg = Builder.CreateZExt(Arg, IntPtrTy);
1632         else {
1633           assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
1634           Arg = Builder.CreateFPExt(Arg, OutputTy);
1635         }
1636       }
1637     }
1638     if (llvm::Type* AdjTy =
1639               getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
1640                                                    Arg->getType()))
1641       Arg = Builder.CreateBitCast(Arg, AdjTy);
1642 
1643     ArgTypes.push_back(Arg->getType());
1644     Args.push_back(Arg);
1645     Constraints += InputConstraint;
1646   }
1647 
1648   // Append the "input" part of inout constraints last.
1649   for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1650     ArgTypes.push_back(InOutArgTypes[i]);
1651     Args.push_back(InOutArgs[i]);
1652   }
1653   Constraints += InOutConstraints;
1654 
1655   // Clobbers
1656   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1657     StringRef Clobber = S.getClobber(i);
1658 
1659     if (Clobber != "memory" && Clobber != "cc")
1660     Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
1661 
1662     if (i != 0 || NumConstraints != 0)
1663       Constraints += ',';
1664 
1665     Constraints += "~{";
1666     Constraints += Clobber;
1667     Constraints += '}';
1668   }
1669 
1670   // Add machine specific clobbers
1671   std::string MachineClobbers = getTarget().getClobbers();
1672   if (!MachineClobbers.empty()) {
1673     if (!Constraints.empty())
1674       Constraints += ',';
1675     Constraints += MachineClobbers;
1676   }
1677 
1678   llvm::Type *ResultType;
1679   if (ResultRegTypes.empty())
1680     ResultType = VoidTy;
1681   else if (ResultRegTypes.size() == 1)
1682     ResultType = ResultRegTypes[0];
1683   else
1684     ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
1685 
1686   llvm::FunctionType *FTy =
1687     llvm::FunctionType::get(ResultType, ArgTypes, false);
1688 
1689   bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
1690   llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
1691     llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
1692   llvm::InlineAsm *IA =
1693     llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
1694                          /* IsAlignStack */ false, AsmDialect);
1695   llvm::CallInst *Result = Builder.CreateCall(IA, Args);
1696   Result->addAttribute(llvm::AttributeSet::FunctionIndex,
1697                        llvm::Attribute::NoUnwind);
1698 
1699   // Slap the source location of the inline asm into a !srcloc metadata on the
1700   // call.  FIXME: Handle metadata for MS-style inline asms.
1701   if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S))
1702     Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(),
1703                                                    *this));
1704 
1705   // Extract all of the register value results from the asm.
1706   std::vector<llvm::Value*> RegResults;
1707   if (ResultRegTypes.size() == 1) {
1708     RegResults.push_back(Result);
1709   } else {
1710     for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
1711       llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
1712       RegResults.push_back(Tmp);
1713     }
1714   }
1715 
1716   for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1717     llvm::Value *Tmp = RegResults[i];
1718 
1719     // If the result type of the LLVM IR asm doesn't match the result type of
1720     // the expression, do the conversion.
1721     if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1722       llvm::Type *TruncTy = ResultTruncRegTypes[i];
1723 
1724       // Truncate the integer result to the right size, note that TruncTy can be
1725       // a pointer.
1726       if (TruncTy->isFloatingPointTy())
1727         Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
1728       else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
1729         uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
1730         Tmp = Builder.CreateTrunc(Tmp,
1731                    llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
1732         Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
1733       } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
1734         uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
1735         Tmp = Builder.CreatePtrToInt(Tmp,
1736                    llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
1737         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1738       } else if (TruncTy->isIntegerTy()) {
1739         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1740       } else if (TruncTy->isVectorTy()) {
1741         Tmp = Builder.CreateBitCast(Tmp, TruncTy);
1742       }
1743     }
1744 
1745     EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
1746   }
1747 }
1748 
1749 void CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S) {
1750   llvm_unreachable("not implemented yet");
1751 }
1752