1 //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code to emit Stmt nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGDebugInfo.h"
15 #include "CodeGenModule.h"
16 #include "CodeGenFunction.h"
17 #include "clang/AST/StmtVisitor.h"
18 #include "clang/Basic/PrettyStackTrace.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/InlineAsm.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/Target/TargetData.h"
24 using namespace clang;
25 using namespace CodeGen;
26 
27 //===----------------------------------------------------------------------===//
28 //                              Statement Emission
29 //===----------------------------------------------------------------------===//
30 
31 void CodeGenFunction::EmitStopPoint(const Stmt *S) {
32   if (CGDebugInfo *DI = getDebugInfo()) {
33     if (isa<DeclStmt>(S))
34       DI->setLocation(S->getLocEnd());
35     else
36       DI->setLocation(S->getLocStart());
37     DI->UpdateLineDirectiveRegion(Builder);
38     DI->EmitStopPoint(Builder);
39   }
40 }
41 
42 void CodeGenFunction::EmitStmt(const Stmt *S) {
43   assert(S && "Null statement?");
44 
45   // Check if we can handle this without bothering to generate an
46   // insert point or debug info.
47   if (EmitSimpleStmt(S))
48     return;
49 
50   // Check if we are generating unreachable code.
51   if (!HaveInsertPoint()) {
52     // If so, and the statement doesn't contain a label, then we do not need to
53     // generate actual code. This is safe because (1) the current point is
54     // unreachable, so we don't need to execute the code, and (2) we've already
55     // handled the statements which update internal data structures (like the
56     // local variable map) which could be used by subsequent statements.
57     if (!ContainsLabel(S)) {
58       // Verify that any decl statements were handled as simple, they may be in
59       // scope of subsequent reachable statements.
60       assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
61       return;
62     }
63 
64     // Otherwise, make a new block to hold the code.
65     EnsureInsertPoint();
66   }
67 
68   // Generate a stoppoint if we are emitting debug info.
69   EmitStopPoint(S);
70 
71   switch (S->getStmtClass()) {
72   default:
73     // Must be an expression in a stmt context.  Emit the value (to get
74     // side-effects) and ignore the result.
75     if (!isa<Expr>(S))
76       ErrorUnsupported(S, "statement");
77 
78     EmitAnyExpr(cast<Expr>(S), 0, false, true);
79 
80     // Expression emitters don't handle unreachable blocks yet, so look for one
81     // explicitly here. This handles the common case of a call to a noreturn
82     // function.
83     if (llvm::BasicBlock *CurBB = Builder.GetInsertBlock()) {
84       if (CurBB->empty() && CurBB->use_empty()) {
85         CurBB->eraseFromParent();
86         Builder.ClearInsertionPoint();
87       }
88     }
89     break;
90   case Stmt::IndirectGotoStmtClass:
91     EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
92 
93   case Stmt::IfStmtClass:       EmitIfStmt(cast<IfStmt>(*S));             break;
94   case Stmt::WhileStmtClass:    EmitWhileStmt(cast<WhileStmt>(*S));       break;
95   case Stmt::DoStmtClass:       EmitDoStmt(cast<DoStmt>(*S));             break;
96   case Stmt::ForStmtClass:      EmitForStmt(cast<ForStmt>(*S));           break;
97 
98   case Stmt::ReturnStmtClass:   EmitReturnStmt(cast<ReturnStmt>(*S));     break;
99 
100   case Stmt::SwitchStmtClass:   EmitSwitchStmt(cast<SwitchStmt>(*S));     break;
101   case Stmt::AsmStmtClass:      EmitAsmStmt(cast<AsmStmt>(*S));           break;
102 
103   case Stmt::ObjCAtTryStmtClass:
104     EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
105     break;
106   case Stmt::ObjCAtCatchStmtClass:
107     assert(0 && "@catch statements should be handled by EmitObjCAtTryStmt");
108     break;
109   case Stmt::ObjCAtFinallyStmtClass:
110     assert(0 && "@finally statements should be handled by EmitObjCAtTryStmt");
111     break;
112   case Stmt::ObjCAtThrowStmtClass:
113     EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
114     break;
115   case Stmt::ObjCAtSynchronizedStmtClass:
116     EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
117     break;
118   case Stmt::ObjCForCollectionStmtClass:
119     EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
120     break;
121 
122   case Stmt::CXXTryStmtClass:
123     EmitCXXTryStmt(cast<CXXTryStmt>(*S));
124     break;
125   }
126 }
127 
128 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
129   switch (S->getStmtClass()) {
130   default: return false;
131   case Stmt::NullStmtClass: break;
132   case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
133   case Stmt::DeclStmtClass:     EmitDeclStmt(cast<DeclStmt>(*S));         break;
134   case Stmt::LabelStmtClass:    EmitLabelStmt(cast<LabelStmt>(*S));       break;
135   case Stmt::GotoStmtClass:     EmitGotoStmt(cast<GotoStmt>(*S));         break;
136   case Stmt::BreakStmtClass:    EmitBreakStmt(cast<BreakStmt>(*S));       break;
137   case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
138   case Stmt::DefaultStmtClass:  EmitDefaultStmt(cast<DefaultStmt>(*S));   break;
139   case Stmt::CaseStmtClass:     EmitCaseStmt(cast<CaseStmt>(*S));         break;
140   }
141 
142   return true;
143 }
144 
145 /// EmitCompoundStmt - Emit a compound statement {..} node.  If GetLast is true,
146 /// this captures the expression result of the last sub-statement and returns it
147 /// (for use by the statement expression extension).
148 RValue CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
149                                          llvm::Value *AggLoc, bool isAggVol) {
150   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
151                              "LLVM IR generation of compound statement ('{}')");
152 
153   CGDebugInfo *DI = getDebugInfo();
154   if (DI) {
155     DI->setLocation(S.getLBracLoc());
156     DI->EmitRegionStart(Builder);
157   }
158 
159   // Keep track of the current cleanup stack depth.
160   RunCleanupsScope Scope(*this);
161 
162   for (CompoundStmt::const_body_iterator I = S.body_begin(),
163        E = S.body_end()-GetLast; I != E; ++I)
164     EmitStmt(*I);
165 
166   if (DI) {
167     DI->setLocation(S.getRBracLoc());
168     DI->EmitRegionEnd(Builder);
169   }
170 
171   RValue RV;
172   if (!GetLast)
173     RV = RValue::get(0);
174   else {
175     // We have to special case labels here.  They are statements, but when put
176     // at the end of a statement expression, they yield the value of their
177     // subexpression.  Handle this by walking through all labels we encounter,
178     // emitting them before we evaluate the subexpr.
179     const Stmt *LastStmt = S.body_back();
180     while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
181       EmitLabel(*LS);
182       LastStmt = LS->getSubStmt();
183     }
184 
185     EnsureInsertPoint();
186 
187     RV = EmitAnyExpr(cast<Expr>(LastStmt), AggLoc);
188   }
189 
190   return RV;
191 }
192 
193 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
194   llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
195 
196   // If there is a cleanup stack, then we it isn't worth trying to
197   // simplify this block (we would need to remove it from the scope map
198   // and cleanup entry).
199   if (!EHStack.empty())
200     return;
201 
202   // Can only simplify direct branches.
203   if (!BI || !BI->isUnconditional())
204     return;
205 
206   BB->replaceAllUsesWith(BI->getSuccessor(0));
207   BI->eraseFromParent();
208   BB->eraseFromParent();
209 }
210 
211 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
212   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
213 
214   // Fall out of the current block (if necessary).
215   EmitBranch(BB);
216 
217   if (IsFinished && BB->use_empty()) {
218     delete BB;
219     return;
220   }
221 
222   // Place the block after the current block, if possible, or else at
223   // the end of the function.
224   if (CurBB && CurBB->getParent())
225     CurFn->getBasicBlockList().insertAfter(CurBB, BB);
226   else
227     CurFn->getBasicBlockList().push_back(BB);
228   Builder.SetInsertPoint(BB);
229 }
230 
231 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
232   // Emit a branch from the current block to the target one if this
233   // was a real block.  If this was just a fall-through block after a
234   // terminator, don't emit it.
235   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
236 
237   if (!CurBB || CurBB->getTerminator()) {
238     // If there is no insert point or the previous block is already
239     // terminated, don't touch it.
240   } else {
241     // Otherwise, create a fall-through branch.
242     Builder.CreateBr(Target);
243   }
244 
245   Builder.ClearInsertionPoint();
246 }
247 
248 CodeGenFunction::JumpDest
249 CodeGenFunction::getJumpDestForLabel(const LabelStmt *S) {
250   JumpDest &Dest = LabelMap[S];
251   if (Dest.isValid()) return Dest;
252 
253   // Create, but don't insert, the new block.
254   Dest = JumpDest(createBasicBlock(S->getName()),
255                   EHScopeStack::stable_iterator::invalid(),
256                   NextCleanupDestIndex++);
257   return Dest;
258 }
259 
260 void CodeGenFunction::EmitLabel(const LabelStmt &S) {
261   JumpDest &Dest = LabelMap[&S];
262 
263   // If we didn't need a forward reference to this label, just go
264   // ahead and create a destination at the current scope.
265   if (!Dest.isValid()) {
266     Dest = getJumpDestInCurrentScope(S.getName());
267 
268   // Otherwise, we need to give this label a target depth and remove
269   // it from the branch-fixups list.
270   } else {
271     assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
272     Dest = JumpDest(Dest.getBlock(),
273                     EHStack.stable_begin(),
274                     Dest.getDestIndex());
275 
276     ResolveBranchFixups(Dest.getBlock());
277   }
278 
279   EmitBlock(Dest.getBlock());
280 }
281 
282 
283 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
284   EmitLabel(S);
285   EmitStmt(S.getSubStmt());
286 }
287 
288 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
289   // If this code is reachable then emit a stop point (if generating
290   // debug info). We have to do this ourselves because we are on the
291   // "simple" statement path.
292   if (HaveInsertPoint())
293     EmitStopPoint(&S);
294 
295   EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
296 }
297 
298 
299 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
300   // Ensure that we have an i8* for our PHI node.
301   llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
302                                          llvm::Type::getInt8PtrTy(VMContext),
303                                           "addr");
304   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
305 
306 
307   // Get the basic block for the indirect goto.
308   llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
309 
310   // The first instruction in the block has to be the PHI for the switch dest,
311   // add an entry for this branch.
312   cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
313 
314   EmitBranch(IndGotoBB);
315 }
316 
317 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
318   // C99 6.8.4.1: The first substatement is executed if the expression compares
319   // unequal to 0.  The condition must be a scalar type.
320   RunCleanupsScope ConditionScope(*this);
321 
322   if (S.getConditionVariable())
323     EmitLocalBlockVarDecl(*S.getConditionVariable());
324 
325   // If the condition constant folds and can be elided, try to avoid emitting
326   // the condition and the dead arm of the if/else.
327   if (int Cond = ConstantFoldsToSimpleInteger(S.getCond())) {
328     // Figure out which block (then or else) is executed.
329     const Stmt *Executed = S.getThen(), *Skipped  = S.getElse();
330     if (Cond == -1)  // Condition false?
331       std::swap(Executed, Skipped);
332 
333     // If the skipped block has no labels in it, just emit the executed block.
334     // This avoids emitting dead code and simplifies the CFG substantially.
335     if (!ContainsLabel(Skipped)) {
336       if (Executed) {
337         RunCleanupsScope ExecutedScope(*this);
338         EmitStmt(Executed);
339       }
340       return;
341     }
342   }
343 
344   // Otherwise, the condition did not fold, or we couldn't elide it.  Just emit
345   // the conditional branch.
346   llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
347   llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
348   llvm::BasicBlock *ElseBlock = ContBlock;
349   if (S.getElse())
350     ElseBlock = createBasicBlock("if.else");
351   EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock);
352 
353   // Emit the 'then' code.
354   EmitBlock(ThenBlock);
355   {
356     RunCleanupsScope ThenScope(*this);
357     EmitStmt(S.getThen());
358   }
359   EmitBranch(ContBlock);
360 
361   // Emit the 'else' code if present.
362   if (const Stmt *Else = S.getElse()) {
363     EmitBlock(ElseBlock);
364     {
365       RunCleanupsScope ElseScope(*this);
366       EmitStmt(Else);
367     }
368     EmitBranch(ContBlock);
369   }
370 
371   // Emit the continuation block for code after the if.
372   EmitBlock(ContBlock, true);
373 }
374 
375 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S) {
376   // Emit the header for the loop, which will also become
377   // the continue target.
378   JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
379   EmitBlock(LoopHeader.getBlock());
380 
381   // Create an exit block for when the condition fails, which will
382   // also become the break target.
383   JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
384 
385   // Store the blocks to use for break and continue.
386   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
387 
388   // C++ [stmt.while]p2:
389   //   When the condition of a while statement is a declaration, the
390   //   scope of the variable that is declared extends from its point
391   //   of declaration (3.3.2) to the end of the while statement.
392   //   [...]
393   //   The object created in a condition is destroyed and created
394   //   with each iteration of the loop.
395   RunCleanupsScope ConditionScope(*this);
396 
397   if (S.getConditionVariable())
398     EmitLocalBlockVarDecl(*S.getConditionVariable());
399 
400   // Evaluate the conditional in the while header.  C99 6.8.5.1: The
401   // evaluation of the controlling expression takes place before each
402   // execution of the loop body.
403   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
404 
405   // while(1) is common, avoid extra exit blocks.  Be sure
406   // to correctly handle break/continue though.
407   bool EmitBoolCondBranch = true;
408   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
409     if (C->isOne())
410       EmitBoolCondBranch = false;
411 
412   // As long as the condition is true, go to the loop body.
413   llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
414   if (EmitBoolCondBranch) {
415     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
416     if (ConditionScope.requiresCleanups())
417       ExitBlock = createBasicBlock("while.exit");
418 
419     Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock);
420 
421     if (ExitBlock != LoopExit.getBlock()) {
422       EmitBlock(ExitBlock);
423       EmitBranchThroughCleanup(LoopExit);
424     }
425   }
426 
427   // Emit the loop body.  We have to emit this in a cleanup scope
428   // because it might be a singleton DeclStmt.
429   {
430     RunCleanupsScope BodyScope(*this);
431     EmitBlock(LoopBody);
432     EmitStmt(S.getBody());
433   }
434 
435   BreakContinueStack.pop_back();
436 
437   // Immediately force cleanup.
438   ConditionScope.ForceCleanup();
439 
440   // Branch to the loop header again.
441   EmitBranch(LoopHeader.getBlock());
442 
443   // Emit the exit block.
444   EmitBlock(LoopExit.getBlock(), true);
445 
446   // The LoopHeader typically is just a branch if we skipped emitting
447   // a branch, try to erase it.
448   if (!EmitBoolCondBranch)
449     SimplifyForwardingBlocks(LoopHeader.getBlock());
450 }
451 
452 void CodeGenFunction::EmitDoStmt(const DoStmt &S) {
453   JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
454   JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
455 
456   // Store the blocks to use for break and continue.
457   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
458 
459   // Emit the body of the loop.
460   llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
461   EmitBlock(LoopBody);
462   {
463     RunCleanupsScope BodyScope(*this);
464     EmitStmt(S.getBody());
465   }
466 
467   BreakContinueStack.pop_back();
468 
469   EmitBlock(LoopCond.getBlock());
470 
471   // C99 6.8.5.2: "The evaluation of the controlling expression takes place
472   // after each execution of the loop body."
473 
474   // Evaluate the conditional in the while header.
475   // C99 6.8.5p2/p4: The first substatement is executed if the expression
476   // compares unequal to 0.  The condition must be a scalar type.
477   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
478 
479   // "do {} while (0)" is common in macros, avoid extra blocks.  Be sure
480   // to correctly handle break/continue though.
481   bool EmitBoolCondBranch = true;
482   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
483     if (C->isZero())
484       EmitBoolCondBranch = false;
485 
486   // As long as the condition is true, iterate the loop.
487   if (EmitBoolCondBranch)
488     Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock());
489 
490   // Emit the exit block.
491   EmitBlock(LoopExit.getBlock());
492 
493   // The DoCond block typically is just a branch if we skipped
494   // emitting a branch, try to erase it.
495   if (!EmitBoolCondBranch)
496     SimplifyForwardingBlocks(LoopCond.getBlock());
497 }
498 
499 void CodeGenFunction::EmitForStmt(const ForStmt &S) {
500   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
501 
502   RunCleanupsScope ForScope(*this);
503 
504   CGDebugInfo *DI = getDebugInfo();
505   if (DI) {
506     DI->setLocation(S.getSourceRange().getBegin());
507     DI->EmitRegionStart(Builder);
508   }
509 
510   // Evaluate the first part before the loop.
511   if (S.getInit())
512     EmitStmt(S.getInit());
513 
514   // Start the loop with a block that tests the condition.
515   // If there's an increment, the continue scope will be overwritten
516   // later.
517   JumpDest Continue = getJumpDestInCurrentScope("for.cond");
518   llvm::BasicBlock *CondBlock = Continue.getBlock();
519   EmitBlock(CondBlock);
520 
521   // Create a cleanup scope for the condition variable cleanups.
522   RunCleanupsScope ConditionScope(*this);
523 
524   llvm::Value *BoolCondVal = 0;
525   if (S.getCond()) {
526     // If the for statement has a condition scope, emit the local variable
527     // declaration.
528     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
529     if (S.getConditionVariable()) {
530       EmitLocalBlockVarDecl(*S.getConditionVariable());
531     }
532 
533     // If there are any cleanups between here and the loop-exit scope,
534     // create a block to stage a loop exit along.
535     if (ForScope.requiresCleanups())
536       ExitBlock = createBasicBlock("for.cond.cleanup");
537 
538     // As long as the condition is true, iterate the loop.
539     llvm::BasicBlock *ForBody = createBasicBlock("for.body");
540 
541     // C99 6.8.5p2/p4: The first substatement is executed if the expression
542     // compares unequal to 0.  The condition must be a scalar type.
543     BoolCondVal = EvaluateExprAsBool(S.getCond());
544     Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock);
545 
546     if (ExitBlock != LoopExit.getBlock()) {
547       EmitBlock(ExitBlock);
548       EmitBranchThroughCleanup(LoopExit);
549     }
550 
551     EmitBlock(ForBody);
552   } else {
553     // Treat it as a non-zero constant.  Don't even create a new block for the
554     // body, just fall into it.
555   }
556 
557   // If the for loop doesn't have an increment we can just use the
558   // condition as the continue block.  Otherwise we'll need to create
559   // a block for it (in the current scope, i.e. in the scope of the
560   // condition), and that we will become our continue block.
561   if (S.getInc())
562     Continue = getJumpDestInCurrentScope("for.inc");
563 
564   // Store the blocks to use for break and continue.
565   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
566 
567   {
568     // Create a separate cleanup scope for the body, in case it is not
569     // a compound statement.
570     RunCleanupsScope BodyScope(*this);
571     EmitStmt(S.getBody());
572   }
573 
574   // If there is an increment, emit it next.
575   if (S.getInc()) {
576     EmitBlock(Continue.getBlock());
577     EmitStmt(S.getInc());
578   }
579 
580   BreakContinueStack.pop_back();
581 
582   ConditionScope.ForceCleanup();
583   EmitBranch(CondBlock);
584 
585   ForScope.ForceCleanup();
586 
587   if (DI) {
588     DI->setLocation(S.getSourceRange().getEnd());
589     DI->EmitRegionEnd(Builder);
590   }
591 
592   // Emit the fall-through block.
593   EmitBlock(LoopExit.getBlock(), true);
594 }
595 
596 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
597   if (RV.isScalar()) {
598     Builder.CreateStore(RV.getScalarVal(), ReturnValue);
599   } else if (RV.isAggregate()) {
600     EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
601   } else {
602     StoreComplexToAddr(RV.getComplexVal(), ReturnValue, false);
603   }
604   EmitBranchThroughCleanup(ReturnBlock);
605 }
606 
607 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
608 /// if the function returns void, or may be missing one if the function returns
609 /// non-void.  Fun stuff :).
610 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
611   // Emit the result value, even if unused, to evalute the side effects.
612   const Expr *RV = S.getRetValue();
613 
614   // FIXME: Clean this up by using an LValue for ReturnTemp,
615   // EmitStoreThroughLValue, and EmitAnyExpr.
616   if (S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable() &&
617       !Target.useGlobalsForAutomaticVariables()) {
618     // Apply the named return value optimization for this return statement,
619     // which means doing nothing: the appropriate result has already been
620     // constructed into the NRVO variable.
621 
622     // If there is an NRVO flag for this variable, set it to 1 into indicate
623     // that the cleanup code should not destroy the variable.
624     if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()]) {
625       const llvm::Type *BoolTy = llvm::Type::getInt1Ty(VMContext);
626       llvm::Value *One = llvm::ConstantInt::get(BoolTy, 1);
627       Builder.CreateStore(One, NRVOFlag);
628     }
629   } else if (!ReturnValue) {
630     // Make sure not to return anything, but evaluate the expression
631     // for side effects.
632     if (RV)
633       EmitAnyExpr(RV);
634   } else if (RV == 0) {
635     // Do nothing (return value is left uninitialized)
636   } else if (FnRetTy->isReferenceType()) {
637     // If this function returns a reference, take the address of the expression
638     // rather than the value.
639     RValue Result = EmitReferenceBindingToExpr(RV, /*InitializedDecl=*/0);
640     Builder.CreateStore(Result.getScalarVal(), ReturnValue);
641   } else if (!hasAggregateLLVMType(RV->getType())) {
642     Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
643   } else if (RV->getType()->isAnyComplexType()) {
644     EmitComplexExprIntoAddr(RV, ReturnValue, false);
645   } else {
646     EmitAggExpr(RV, ReturnValue, false);
647   }
648 
649   EmitBranchThroughCleanup(ReturnBlock);
650 }
651 
652 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
653   // As long as debug info is modeled with instructions, we have to ensure we
654   // have a place to insert here and write the stop point here.
655   if (getDebugInfo()) {
656     EnsureInsertPoint();
657     EmitStopPoint(&S);
658   }
659 
660   for (DeclStmt::const_decl_iterator I = S.decl_begin(), E = S.decl_end();
661        I != E; ++I)
662     EmitDecl(**I);
663 }
664 
665 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
666   assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
667 
668   // If this code is reachable then emit a stop point (if generating
669   // debug info). We have to do this ourselves because we are on the
670   // "simple" statement path.
671   if (HaveInsertPoint())
672     EmitStopPoint(&S);
673 
674   JumpDest Block = BreakContinueStack.back().BreakBlock;
675   EmitBranchThroughCleanup(Block);
676 }
677 
678 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
679   assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
680 
681   // If this code is reachable then emit a stop point (if generating
682   // debug info). We have to do this ourselves because we are on the
683   // "simple" statement path.
684   if (HaveInsertPoint())
685     EmitStopPoint(&S);
686 
687   JumpDest Block = BreakContinueStack.back().ContinueBlock;
688   EmitBranchThroughCleanup(Block);
689 }
690 
691 /// EmitCaseStmtRange - If case statement range is not too big then
692 /// add multiple cases to switch instruction, one for each value within
693 /// the range. If range is too big then emit "if" condition check.
694 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
695   assert(S.getRHS() && "Expected RHS value in CaseStmt");
696 
697   llvm::APSInt LHS = S.getLHS()->EvaluateAsInt(getContext());
698   llvm::APSInt RHS = S.getRHS()->EvaluateAsInt(getContext());
699 
700   // Emit the code for this case. We do this first to make sure it is
701   // properly chained from our predecessor before generating the
702   // switch machinery to enter this block.
703   EmitBlock(createBasicBlock("sw.bb"));
704   llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
705   EmitStmt(S.getSubStmt());
706 
707   // If range is empty, do nothing.
708   if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
709     return;
710 
711   llvm::APInt Range = RHS - LHS;
712   // FIXME: parameters such as this should not be hardcoded.
713   if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
714     // Range is small enough to add multiple switch instruction cases.
715     for (unsigned i = 0, e = Range.getZExtValue() + 1; i != e; ++i) {
716       SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, LHS), CaseDest);
717       LHS++;
718     }
719     return;
720   }
721 
722   // The range is too big. Emit "if" condition into a new block,
723   // making sure to save and restore the current insertion point.
724   llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
725 
726   // Push this test onto the chain of range checks (which terminates
727   // in the default basic block). The switch's default will be changed
728   // to the top of this chain after switch emission is complete.
729   llvm::BasicBlock *FalseDest = CaseRangeBlock;
730   CaseRangeBlock = createBasicBlock("sw.caserange");
731 
732   CurFn->getBasicBlockList().push_back(CaseRangeBlock);
733   Builder.SetInsertPoint(CaseRangeBlock);
734 
735   // Emit range check.
736   llvm::Value *Diff =
737     Builder.CreateSub(SwitchInsn->getCondition(),
738                       llvm::ConstantInt::get(VMContext, LHS),  "tmp");
739   llvm::Value *Cond =
740     Builder.CreateICmpULE(Diff,
741                           llvm::ConstantInt::get(VMContext, Range), "tmp");
742   Builder.CreateCondBr(Cond, CaseDest, FalseDest);
743 
744   // Restore the appropriate insertion point.
745   if (RestoreBB)
746     Builder.SetInsertPoint(RestoreBB);
747   else
748     Builder.ClearInsertionPoint();
749 }
750 
751 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
752   if (S.getRHS()) {
753     EmitCaseStmtRange(S);
754     return;
755   }
756 
757   EmitBlock(createBasicBlock("sw.bb"));
758   llvm::BasicBlock *CaseDest = Builder.GetInsertBlock();
759   llvm::APSInt CaseVal = S.getLHS()->EvaluateAsInt(getContext());
760   SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
761 
762   // Recursively emitting the statement is acceptable, but is not wonderful for
763   // code where we have many case statements nested together, i.e.:
764   //  case 1:
765   //    case 2:
766   //      case 3: etc.
767   // Handling this recursively will create a new block for each case statement
768   // that falls through to the next case which is IR intensive.  It also causes
769   // deep recursion which can run into stack depth limitations.  Handle
770   // sequential non-range case statements specially.
771   const CaseStmt *CurCase = &S;
772   const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
773 
774   // Otherwise, iteratively add consequtive cases to this switch stmt.
775   while (NextCase && NextCase->getRHS() == 0) {
776     CurCase = NextCase;
777     CaseVal = CurCase->getLHS()->EvaluateAsInt(getContext());
778     SwitchInsn->addCase(llvm::ConstantInt::get(VMContext, CaseVal), CaseDest);
779 
780     NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
781   }
782 
783   // Normal default recursion for non-cases.
784   EmitStmt(CurCase->getSubStmt());
785 }
786 
787 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
788   llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
789   assert(DefaultBlock->empty() &&
790          "EmitDefaultStmt: Default block already defined?");
791   EmitBlock(DefaultBlock);
792   EmitStmt(S.getSubStmt());
793 }
794 
795 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
796   JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
797 
798   RunCleanupsScope ConditionScope(*this);
799 
800   if (S.getConditionVariable())
801     EmitLocalBlockVarDecl(*S.getConditionVariable());
802 
803   llvm::Value *CondV = EmitScalarExpr(S.getCond());
804 
805   // Handle nested switch statements.
806   llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
807   llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
808 
809   // Create basic block to hold stuff that comes after switch
810   // statement. We also need to create a default block now so that
811   // explicit case ranges tests can have a place to jump to on
812   // failure.
813   llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
814   SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
815   CaseRangeBlock = DefaultBlock;
816 
817   // Clear the insertion point to indicate we are in unreachable code.
818   Builder.ClearInsertionPoint();
819 
820   // All break statements jump to NextBlock. If BreakContinueStack is non empty
821   // then reuse last ContinueBlock.
822   JumpDest OuterContinue;
823   if (!BreakContinueStack.empty())
824     OuterContinue = BreakContinueStack.back().ContinueBlock;
825 
826   BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
827 
828   // Emit switch body.
829   EmitStmt(S.getBody());
830 
831   BreakContinueStack.pop_back();
832 
833   // Update the default block in case explicit case range tests have
834   // been chained on top.
835   SwitchInsn->setSuccessor(0, CaseRangeBlock);
836 
837   // If a default was never emitted:
838   if (!DefaultBlock->getParent()) {
839     // If we have cleanups, emit the default block so that there's a
840     // place to jump through the cleanups from.
841     if (ConditionScope.requiresCleanups()) {
842       EmitBlock(DefaultBlock);
843 
844     // Otherwise, just forward the default block to the switch end.
845     } else {
846       DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
847       delete DefaultBlock;
848     }
849   }
850 
851   ConditionScope.ForceCleanup();
852 
853   // Emit continuation.
854   EmitBlock(SwitchExit.getBlock(), true);
855 
856   SwitchInsn = SavedSwitchInsn;
857   CaseRangeBlock = SavedCRBlock;
858 }
859 
860 static std::string
861 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
862                  llvm::SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=0) {
863   std::string Result;
864   std::string tmp;
865 
866   while (*Constraint) {
867     switch (*Constraint) {
868     default:
869       tmp = Target.convertConstraint(*Constraint);
870       if (Result.find(tmp) == std::string::npos) // Combine unique constraints
871         Result += tmp;
872       break;
873     // Ignore these
874     case '*':
875     case '?':
876     case '!':
877     case '=': // Will see this and the following in mult-alt constraints.
878     case '+':
879       break;
880     case ',':                 // FIXME - Until the back-end properly supports
881               return Result;  // multiple alternative constraints, we stop here.
882       break;
883     case 'g':
884       Result += "imr";
885       break;
886     case '[': {
887       assert(OutCons &&
888              "Must pass output names to constraints with a symbolic name");
889       unsigned Index;
890       bool result = Target.resolveSymbolicName(Constraint,
891                                                &(*OutCons)[0],
892                                                OutCons->size(), Index);
893       assert(result && "Could not resolve symbolic name"); result=result;
894       Result += llvm::utostr(Index);
895       break;
896     }
897     }
898 
899     Constraint++;
900   }
901 
902   return Result;
903 }
904 
905 llvm::Value*
906 CodeGenFunction::EmitAsmInputLValue(const AsmStmt &S,
907                                     const TargetInfo::ConstraintInfo &Info,
908                                     LValue InputValue, QualType InputType,
909                                     std::string &ConstraintStr) {
910   llvm::Value *Arg;
911   if (Info.allowsRegister() || !Info.allowsMemory()) {
912     if (!CodeGenFunction::hasAggregateLLVMType(InputType)) {
913       Arg = EmitLoadOfLValue(InputValue, InputType).getScalarVal();
914     } else {
915       const llvm::Type *Ty = ConvertType(InputType);
916       uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
917       if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
918         Ty = llvm::IntegerType::get(VMContext, Size);
919         Ty = llvm::PointerType::getUnqual(Ty);
920 
921         Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
922                                                        Ty));
923       } else {
924         Arg = InputValue.getAddress();
925         ConstraintStr += '*';
926       }
927     }
928   } else {
929     Arg = InputValue.getAddress();
930     ConstraintStr += '*';
931   }
932 
933   return Arg;
934 }
935 
936 llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
937                                          const TargetInfo::ConstraintInfo &Info,
938                                            const Expr *InputExpr,
939                                            std::string &ConstraintStr) {
940   if (Info.allowsRegister() || !Info.allowsMemory())
941     if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType()))
942       return EmitScalarExpr(InputExpr);
943 
944   InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
945   LValue Dest = EmitLValue(InputExpr);
946   return EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(), ConstraintStr);
947 }
948 
949 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
950   // Analyze the asm string to decompose it into its pieces.  We know that Sema
951   // has already done this, so it is guaranteed to be successful.
952   llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
953   unsigned DiagOffs;
954   S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
955 
956   // Assemble the pieces into the final asm string.
957   std::string AsmString;
958   for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
959     if (Pieces[i].isString())
960       AsmString += Pieces[i].getString();
961     else if (Pieces[i].getModifier() == '\0')
962       AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
963     else
964       AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
965                    Pieces[i].getModifier() + '}';
966   }
967 
968   // Get all the output and input constraints together.
969   llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
970   llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
971 
972   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
973     TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
974                                     S.getOutputName(i));
975     bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid;
976     assert(IsValid && "Failed to parse output constraint");
977     OutputConstraintInfos.push_back(Info);
978   }
979 
980   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
981     TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
982                                     S.getInputName(i));
983     bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(),
984                                                   S.getNumOutputs(), Info);
985     assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
986     InputConstraintInfos.push_back(Info);
987   }
988 
989   std::string Constraints;
990 
991   std::vector<LValue> ResultRegDests;
992   std::vector<QualType> ResultRegQualTys;
993   std::vector<const llvm::Type *> ResultRegTypes;
994   std::vector<const llvm::Type *> ResultTruncRegTypes;
995   std::vector<const llvm::Type*> ArgTypes;
996   std::vector<llvm::Value*> Args;
997 
998   // Keep track of inout constraints.
999   std::string InOutConstraints;
1000   std::vector<llvm::Value*> InOutArgs;
1001   std::vector<const llvm::Type*> InOutArgTypes;
1002 
1003   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1004     TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1005 
1006     // Simplify the output constraint.
1007     std::string OutputConstraint(S.getOutputConstraint(i));
1008     OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
1009 
1010     const Expr *OutExpr = S.getOutputExpr(i);
1011     OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1012 
1013     LValue Dest = EmitLValue(OutExpr);
1014     if (!Constraints.empty())
1015       Constraints += ',';
1016 
1017     // If this is a register output, then make the inline asm return it
1018     // by-value.  If this is a memory result, return the value by-reference.
1019     if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
1020       Constraints += "=" + OutputConstraint;
1021       ResultRegQualTys.push_back(OutExpr->getType());
1022       ResultRegDests.push_back(Dest);
1023       ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1024       ResultTruncRegTypes.push_back(ResultRegTypes.back());
1025 
1026       // If this output is tied to an input, and if the input is larger, then
1027       // we need to set the actual result type of the inline asm node to be the
1028       // same as the input type.
1029       if (Info.hasMatchingInput()) {
1030         unsigned InputNo;
1031         for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1032           TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1033           if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1034             break;
1035         }
1036         assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1037 
1038         QualType InputTy = S.getInputExpr(InputNo)->getType();
1039         QualType OutputType = OutExpr->getType();
1040 
1041         uint64_t InputSize = getContext().getTypeSize(InputTy);
1042         if (getContext().getTypeSize(OutputType) < InputSize) {
1043           // Form the asm to return the value as a larger integer or fp type.
1044           ResultRegTypes.back() = ConvertType(InputTy);
1045         }
1046       }
1047     } else {
1048       ArgTypes.push_back(Dest.getAddress()->getType());
1049       Args.push_back(Dest.getAddress());
1050       Constraints += "=*";
1051       Constraints += OutputConstraint;
1052     }
1053 
1054     if (Info.isReadWrite()) {
1055       InOutConstraints += ',';
1056 
1057       const Expr *InputExpr = S.getOutputExpr(i);
1058       llvm::Value *Arg = EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(),
1059                                             InOutConstraints);
1060 
1061       if (Info.allowsRegister())
1062         InOutConstraints += llvm::utostr(i);
1063       else
1064         InOutConstraints += OutputConstraint;
1065 
1066       InOutArgTypes.push_back(Arg->getType());
1067       InOutArgs.push_back(Arg);
1068     }
1069   }
1070 
1071   unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1072 
1073   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1074     const Expr *InputExpr = S.getInputExpr(i);
1075 
1076     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1077 
1078     if (!Constraints.empty())
1079       Constraints += ',';
1080 
1081     // Simplify the input constraint.
1082     std::string InputConstraint(S.getInputConstraint(i));
1083     InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
1084                                          &OutputConstraintInfos);
1085 
1086     llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
1087 
1088     // If this input argument is tied to a larger output result, extend the
1089     // input to be the same size as the output.  The LLVM backend wants to see
1090     // the input and output of a matching constraint be the same size.  Note
1091     // that GCC does not define what the top bits are here.  We use zext because
1092     // that is usually cheaper, but LLVM IR should really get an anyext someday.
1093     if (Info.hasTiedOperand()) {
1094       unsigned Output = Info.getTiedOperand();
1095       QualType OutputType = S.getOutputExpr(Output)->getType();
1096       QualType InputTy = InputExpr->getType();
1097 
1098       if (getContext().getTypeSize(OutputType) >
1099           getContext().getTypeSize(InputTy)) {
1100         // Use ptrtoint as appropriate so that we can do our extension.
1101         if (isa<llvm::PointerType>(Arg->getType()))
1102           Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
1103         const llvm::Type *OutputTy = ConvertType(OutputType);
1104         if (isa<llvm::IntegerType>(OutputTy))
1105           Arg = Builder.CreateZExt(Arg, OutputTy);
1106         else
1107           Arg = Builder.CreateFPExt(Arg, OutputTy);
1108       }
1109     }
1110 
1111 
1112     ArgTypes.push_back(Arg->getType());
1113     Args.push_back(Arg);
1114     Constraints += InputConstraint;
1115   }
1116 
1117   // Append the "input" part of inout constraints last.
1118   for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1119     ArgTypes.push_back(InOutArgTypes[i]);
1120     Args.push_back(InOutArgs[i]);
1121   }
1122   Constraints += InOutConstraints;
1123 
1124   // Clobbers
1125   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1126     llvm::StringRef Clobber = S.getClobber(i)->getString();
1127 
1128     Clobber = Target.getNormalizedGCCRegisterName(Clobber);
1129 
1130     if (i != 0 || NumConstraints != 0)
1131       Constraints += ',';
1132 
1133     Constraints += "~{";
1134     Constraints += Clobber;
1135     Constraints += '}';
1136   }
1137 
1138   // Add machine specific clobbers
1139   std::string MachineClobbers = Target.getClobbers();
1140   if (!MachineClobbers.empty()) {
1141     if (!Constraints.empty())
1142       Constraints += ',';
1143     Constraints += MachineClobbers;
1144   }
1145 
1146   const llvm::Type *ResultType;
1147   if (ResultRegTypes.empty())
1148     ResultType = llvm::Type::getVoidTy(VMContext);
1149   else if (ResultRegTypes.size() == 1)
1150     ResultType = ResultRegTypes[0];
1151   else
1152     ResultType = llvm::StructType::get(VMContext, ResultRegTypes);
1153 
1154   const llvm::FunctionType *FTy =
1155     llvm::FunctionType::get(ResultType, ArgTypes, false);
1156 
1157   llvm::InlineAsm *IA =
1158     llvm::InlineAsm::get(FTy, AsmString, Constraints,
1159                          S.isVolatile() || S.getNumOutputs() == 0);
1160   llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end());
1161   Result->addAttribute(~0, llvm::Attribute::NoUnwind);
1162 
1163   // Slap the source location of the inline asm into a !srcloc metadata on the
1164   // call.
1165   unsigned LocID = S.getAsmString()->getLocStart().getRawEncoding();
1166   llvm::Value *LocIDC =
1167     llvm::ConstantInt::get(Int32Ty, LocID);
1168   Result->setMetadata("srcloc", llvm::MDNode::get(VMContext, &LocIDC, 1));
1169 
1170   // Extract all of the register value results from the asm.
1171   std::vector<llvm::Value*> RegResults;
1172   if (ResultRegTypes.size() == 1) {
1173     RegResults.push_back(Result);
1174   } else {
1175     for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
1176       llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
1177       RegResults.push_back(Tmp);
1178     }
1179   }
1180 
1181   for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1182     llvm::Value *Tmp = RegResults[i];
1183 
1184     // If the result type of the LLVM IR asm doesn't match the result type of
1185     // the expression, do the conversion.
1186     if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1187       const llvm::Type *TruncTy = ResultTruncRegTypes[i];
1188 
1189       // Truncate the integer result to the right size, note that TruncTy can be
1190       // a pointer.
1191       if (TruncTy->isFloatingPointTy())
1192         Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
1193       else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
1194         uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
1195         Tmp = Builder.CreateTrunc(Tmp, llvm::IntegerType::get(VMContext,
1196                                                             (unsigned)ResSize));
1197         Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
1198       } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
1199         uint64_t TmpSize =CGM.getTargetData().getTypeSizeInBits(Tmp->getType());
1200         Tmp = Builder.CreatePtrToInt(Tmp, llvm::IntegerType::get(VMContext,
1201                                                             (unsigned)TmpSize));
1202         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1203       } else if (TruncTy->isIntegerTy()) {
1204         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1205       }
1206     }
1207 
1208     EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i],
1209                            ResultRegQualTys[i]);
1210   }
1211 }
1212