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