Skip to content
CodeGenPrepare.cpp 38 KiB
Newer Older
    Instruction *&InsertedTrunc = InsertedTruncs[UserBB];

    if (!InsertedTrunc) {
      BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
      InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
    }

    // Replace a use of the {s|z}ext source with a use of the result.
    TheUse = InsertedTrunc;
bool CodeGenPrepare::OptimizeInst(Instruction *I) {
  if (PHINode *P = dyn_cast<PHINode>(I)) {
    // It is possible for very late stage optimizations (such as SimplifyCFG)
    // to introduce PHI nodes too late to be cleaned up.  If we detect such a
    // trivial PHI, go ahead and zap it here.
    if (Value *V = SimplifyInstruction(P)) {
      P->replaceAllUsesWith(V);
      P->eraseFromParent();
      ++NumPHIsElim;
    return false;
  }
  
  if (CastInst *CI = dyn_cast<CastInst>(I)) {
    // If the source of the cast is a constant, then this should have
    // already been constant folded.  The only reason NOT to constant fold
    // it is if something (e.g. LSR) was careful to place the constant
    // evaluation in a block other than then one that uses it (e.g. to hoist
    // the address of globals out of a loop).  If this is the case, we don't
    // want to forward-subst the cast.
    if (isa<Constant>(CI->getOperand(0)))
      return false;

    if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
      return true;
    if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
      bool MadeChange = MoveExtToFormExtLoad(I);
      return MadeChange | OptimizeExtUses(I);
    return false;
  }
  
  if (CmpInst *CI = dyn_cast<CmpInst>(I))
    return OptimizeCmpExpression(CI);
  
  if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
      return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
    return false;
  }
  
  if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
      return OptimizeMemoryInst(I, SI->getOperand(1),
                                SI->getOperand(0)->getType());
    return false;
  }
  
  if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
    if (GEPI->hasAllZeroIndices()) {
      /// The GEP operand must be a pointer, so must its result -> BitCast
      Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
                                        GEPI->getName(), GEPI);
      GEPI->replaceAllUsesWith(NC);
      GEPI->eraseFromParent();
      ++NumGEPsElim;
      OptimizeInst(NC);
    return false;
  
  if (CallInst *CI = dyn_cast<CallInst>(I))
    return OptimizeCallInst(CI);
  if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
    return DupRetToEnableTailCallOpts(RI);

  return false;
// In this pass we look for GEP and cast instructions that are used
// across basic blocks and rewrite them to improve basic-block-at-a-time
// selection.
bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
  for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
    MadeChange |= OptimizeInst(CurInstIterator++);