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