CGStmt.cpp revision baf86955a9a390f2643a1ea9806832eb4a92f716
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"
24using namespace clang;
25using namespace CodeGen;
26
27//===----------------------------------------------------------------------===//
28//                              Statement Emission
29//===----------------------------------------------------------------------===//
30
31void 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
42void 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
143bool 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).
163RValue 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
208void 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
226void 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
246void 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
263CodeGenFunction::JumpDest
264CodeGenFunction::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
275void 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
298void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
299  EmitLabel(S);
300  EmitStmt(S.getSubStmt());
301}
302
303void 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
314void 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
337void 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
395void 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
472void 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
519void 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
616void 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 :).
630void 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
672void 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
685void 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
698void 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.
714void 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
771void 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
807void 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
815void 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
880static std::string
881SimplifyConstraint(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"); result=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.
925static std::string
926AddVariableConstraints(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  if (Constraint != "r") {
942    CGM.ErrorUnsupported(&Stmt, "__asm__");
943    return Constraint;
944  }
945  return "{" + Register.str() + "}";
946}
947
948llvm::Value*
949CodeGenFunction::EmitAsmInputLValue(const AsmStmt &S,
950                                    const TargetInfo::ConstraintInfo &Info,
951                                    LValue InputValue, QualType InputType,
952                                    std::string &ConstraintStr) {
953  llvm::Value *Arg;
954  if (Info.allowsRegister() || !Info.allowsMemory()) {
955    if (!CodeGenFunction::hasAggregateLLVMType(InputType)) {
956      Arg = EmitLoadOfLValue(InputValue, InputType).getScalarVal();
957    } else {
958      const llvm::Type *Ty = ConvertType(InputType);
959      uint64_t Size = CGM.getTargetData().getTypeSizeInBits(Ty);
960      if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
961        Ty = llvm::IntegerType::get(VMContext, Size);
962        Ty = llvm::PointerType::getUnqual(Ty);
963
964        Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
965                                                       Ty));
966      } else {
967        Arg = InputValue.getAddress();
968        ConstraintStr += '*';
969      }
970    }
971  } else {
972    Arg = InputValue.getAddress();
973    ConstraintStr += '*';
974  }
975
976  return Arg;
977}
978
979llvm::Value* CodeGenFunction::EmitAsmInput(const AsmStmt &S,
980                                         const TargetInfo::ConstraintInfo &Info,
981                                           const Expr *InputExpr,
982                                           std::string &ConstraintStr) {
983  if (Info.allowsRegister() || !Info.allowsMemory())
984    if (!CodeGenFunction::hasAggregateLLVMType(InputExpr->getType()))
985      return EmitScalarExpr(InputExpr);
986
987  InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
988  LValue Dest = EmitLValue(InputExpr);
989  return EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(), ConstraintStr);
990}
991
992/// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
993/// asm call instruction.  The !srcloc MDNode contains a list of constant
994/// integers which are the source locations of the start of each line in the
995/// asm.
996static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
997                                      CodeGenFunction &CGF) {
998  llvm::SmallVector<llvm::Value *, 8> Locs;
999  // Add the location of the first line to the MDNode.
1000  Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1001                                        Str->getLocStart().getRawEncoding()));
1002  llvm::StringRef StrVal = Str->getString();
1003  if (!StrVal.empty()) {
1004    const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1005    const LangOptions &LangOpts = CGF.CGM.getLangOptions();
1006
1007    // Add the location of the start of each subsequent line of the asm to the
1008    // MDNode.
1009    for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
1010      if (StrVal[i] != '\n') continue;
1011      SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
1012                                                      CGF.Target);
1013      Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1014                                            LineLoc.getRawEncoding()));
1015    }
1016  }
1017
1018  return llvm::MDNode::get(CGF.getLLVMContext(), Locs.data(), Locs.size());
1019}
1020
1021void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
1022  // Analyze the asm string to decompose it into its pieces.  We know that Sema
1023  // has already done this, so it is guaranteed to be successful.
1024  llvm::SmallVector<AsmStmt::AsmStringPiece, 4> Pieces;
1025  unsigned DiagOffs;
1026  S.AnalyzeAsmString(Pieces, getContext(), DiagOffs);
1027
1028  // Assemble the pieces into the final asm string.
1029  std::string AsmString;
1030  for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
1031    if (Pieces[i].isString())
1032      AsmString += Pieces[i].getString();
1033    else if (Pieces[i].getModifier() == '\0')
1034      AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
1035    else
1036      AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
1037                   Pieces[i].getModifier() + '}';
1038  }
1039
1040  // Get all the output and input constraints together.
1041  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1042  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1043
1044  for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1045    TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
1046                                    S.getOutputName(i));
1047    bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid;
1048    assert(IsValid && "Failed to parse output constraint");
1049    OutputConstraintInfos.push_back(Info);
1050  }
1051
1052  for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1053    TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
1054                                    S.getInputName(i));
1055    bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(),
1056                                                  S.getNumOutputs(), Info);
1057    assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1058    InputConstraintInfos.push_back(Info);
1059  }
1060
1061  std::string Constraints;
1062
1063  std::vector<LValue> ResultRegDests;
1064  std::vector<QualType> ResultRegQualTys;
1065  std::vector<const llvm::Type *> ResultRegTypes;
1066  std::vector<const llvm::Type *> ResultTruncRegTypes;
1067  std::vector<const llvm::Type*> ArgTypes;
1068  std::vector<llvm::Value*> Args;
1069
1070  // Keep track of inout constraints.
1071  std::string InOutConstraints;
1072  std::vector<llvm::Value*> InOutArgs;
1073  std::vector<const llvm::Type*> InOutArgTypes;
1074
1075  for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1076    TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1077
1078    // Simplify the output constraint.
1079    std::string OutputConstraint(S.getOutputConstraint(i));
1080    OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
1081
1082    const Expr *OutExpr = S.getOutputExpr(i);
1083    OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1084
1085    OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr, Target,
1086                                             CGM, S);
1087
1088    LValue Dest = EmitLValue(OutExpr);
1089    if (!Constraints.empty())
1090      Constraints += ',';
1091
1092    // If this is a register output, then make the inline asm return it
1093    // by-value.  If this is a memory result, return the value by-reference.
1094    if (!Info.allowsMemory() && !hasAggregateLLVMType(OutExpr->getType())) {
1095      Constraints += "=" + OutputConstraint;
1096      ResultRegQualTys.push_back(OutExpr->getType());
1097      ResultRegDests.push_back(Dest);
1098      ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1099      ResultTruncRegTypes.push_back(ResultRegTypes.back());
1100
1101      // If this output is tied to an input, and if the input is larger, then
1102      // we need to set the actual result type of the inline asm node to be the
1103      // same as the input type.
1104      if (Info.hasMatchingInput()) {
1105        unsigned InputNo;
1106        for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1107          TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1108          if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1109            break;
1110        }
1111        assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1112
1113        QualType InputTy = S.getInputExpr(InputNo)->getType();
1114        QualType OutputType = OutExpr->getType();
1115
1116        uint64_t InputSize = getContext().getTypeSize(InputTy);
1117        if (getContext().getTypeSize(OutputType) < InputSize) {
1118          // Form the asm to return the value as a larger integer or fp type.
1119          ResultRegTypes.back() = ConvertType(InputTy);
1120        }
1121      }
1122      if (const llvm::Type* AdjTy =
1123            Target.adjustInlineAsmType(OutputConstraint, ResultRegTypes.back(),
1124                                       VMContext))
1125        ResultRegTypes.back() = AdjTy;
1126    } else {
1127      ArgTypes.push_back(Dest.getAddress()->getType());
1128      Args.push_back(Dest.getAddress());
1129      Constraints += "=*";
1130      Constraints += OutputConstraint;
1131    }
1132
1133    if (Info.isReadWrite()) {
1134      InOutConstraints += ',';
1135
1136      const Expr *InputExpr = S.getOutputExpr(i);
1137      llvm::Value *Arg = EmitAsmInputLValue(S, Info, Dest, InputExpr->getType(),
1138                                            InOutConstraints);
1139
1140      if (Info.allowsRegister())
1141        InOutConstraints += llvm::utostr(i);
1142      else
1143        InOutConstraints += OutputConstraint;
1144
1145      InOutArgTypes.push_back(Arg->getType());
1146      InOutArgs.push_back(Arg);
1147    }
1148  }
1149
1150  unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1151
1152  for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1153    const Expr *InputExpr = S.getInputExpr(i);
1154
1155    TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1156
1157    if (!Constraints.empty())
1158      Constraints += ',';
1159
1160    // Simplify the input constraint.
1161    std::string InputConstraint(S.getInputConstraint(i));
1162    InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
1163                                         &OutputConstraintInfos);
1164
1165    InputConstraint =
1166      AddVariableConstraints(InputConstraint,
1167                            *InputExpr->IgnoreParenNoopCasts(getContext()),
1168                            Target, CGM, S);
1169
1170    llvm::Value *Arg = EmitAsmInput(S, Info, InputExpr, Constraints);
1171
1172    // If this input argument is tied to a larger output result, extend the
1173    // input to be the same size as the output.  The LLVM backend wants to see
1174    // the input and output of a matching constraint be the same size.  Note
1175    // that GCC does not define what the top bits are here.  We use zext because
1176    // that is usually cheaper, but LLVM IR should really get an anyext someday.
1177    if (Info.hasTiedOperand()) {
1178      unsigned Output = Info.getTiedOperand();
1179      QualType OutputType = S.getOutputExpr(Output)->getType();
1180      QualType InputTy = InputExpr->getType();
1181
1182      if (getContext().getTypeSize(OutputType) >
1183          getContext().getTypeSize(InputTy)) {
1184        // Use ptrtoint as appropriate so that we can do our extension.
1185        if (isa<llvm::PointerType>(Arg->getType()))
1186          Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
1187        const llvm::Type *OutputTy = ConvertType(OutputType);
1188        if (isa<llvm::IntegerType>(OutputTy))
1189          Arg = Builder.CreateZExt(Arg, OutputTy);
1190        else
1191          Arg = Builder.CreateFPExt(Arg, OutputTy);
1192      }
1193    }
1194    if (const llvm::Type* AdjTy =
1195              Target.adjustInlineAsmType(InputConstraint, Arg->getType(),
1196                                         VMContext))
1197      Arg = Builder.CreateBitCast(Arg, AdjTy);
1198
1199    ArgTypes.push_back(Arg->getType());
1200    Args.push_back(Arg);
1201    Constraints += InputConstraint;
1202  }
1203
1204  // Append the "input" part of inout constraints last.
1205  for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1206    ArgTypes.push_back(InOutArgTypes[i]);
1207    Args.push_back(InOutArgs[i]);
1208  }
1209  Constraints += InOutConstraints;
1210
1211  // Clobbers
1212  for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1213    llvm::StringRef Clobber = S.getClobber(i)->getString();
1214
1215    Clobber = Target.getNormalizedGCCRegisterName(Clobber);
1216
1217    if (i != 0 || NumConstraints != 0)
1218      Constraints += ',';
1219
1220    Constraints += "~{";
1221    Constraints += Clobber;
1222    Constraints += '}';
1223  }
1224
1225  // Add machine specific clobbers
1226  std::string MachineClobbers = Target.getClobbers();
1227  if (!MachineClobbers.empty()) {
1228    if (!Constraints.empty())
1229      Constraints += ',';
1230    Constraints += MachineClobbers;
1231  }
1232
1233  const llvm::Type *ResultType;
1234  if (ResultRegTypes.empty())
1235    ResultType = llvm::Type::getVoidTy(VMContext);
1236  else if (ResultRegTypes.size() == 1)
1237    ResultType = ResultRegTypes[0];
1238  else
1239    ResultType = llvm::StructType::get(VMContext, ResultRegTypes);
1240
1241  const llvm::FunctionType *FTy =
1242    llvm::FunctionType::get(ResultType, ArgTypes, false);
1243
1244  llvm::InlineAsm *IA =
1245    llvm::InlineAsm::get(FTy, AsmString, Constraints,
1246                         S.isVolatile() || S.getNumOutputs() == 0);
1247  llvm::CallInst *Result = Builder.CreateCall(IA, Args.begin(), Args.end());
1248  Result->addAttribute(~0, llvm::Attribute::NoUnwind);
1249
1250  // Slap the source location of the inline asm into a !srcloc metadata on the
1251  // call.
1252  Result->setMetadata("srcloc", getAsmSrcLocInfo(S.getAsmString(), *this));
1253
1254  // Extract all of the register value results from the asm.
1255  std::vector<llvm::Value*> RegResults;
1256  if (ResultRegTypes.size() == 1) {
1257    RegResults.push_back(Result);
1258  } else {
1259    for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
1260      llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
1261      RegResults.push_back(Tmp);
1262    }
1263  }
1264
1265  for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
1266    llvm::Value *Tmp = RegResults[i];
1267
1268    // If the result type of the LLVM IR asm doesn't match the result type of
1269    // the expression, do the conversion.
1270    if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
1271      const llvm::Type *TruncTy = ResultTruncRegTypes[i];
1272
1273      // Truncate the integer result to the right size, note that TruncTy can be
1274      // a pointer.
1275      if (TruncTy->isFloatingPointTy())
1276        Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
1277      else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
1278        uint64_t ResSize = CGM.getTargetData().getTypeSizeInBits(TruncTy);
1279        Tmp = Builder.CreateTrunc(Tmp, llvm::IntegerType::get(VMContext,
1280                                                            (unsigned)ResSize));
1281        Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
1282      } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
1283        uint64_t TmpSize =CGM.getTargetData().getTypeSizeInBits(Tmp->getType());
1284        Tmp = Builder.CreatePtrToInt(Tmp, llvm::IntegerType::get(VMContext,
1285                                                            (unsigned)TmpSize));
1286        Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1287      } else if (TruncTy->isIntegerTy()) {
1288        Tmp = Builder.CreateTrunc(Tmp, TruncTy);
1289      } else if (TruncTy->isVectorTy()) {
1290        Tmp = Builder.CreateBitCast(Tmp, TruncTy);
1291      }
1292    }
1293
1294    EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i],
1295                           ResultRegQualTys[i]);
1296  }
1297}
1298