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