Ignore:
Timestamp:
Apr 19, 2011, 11:12:07 PM (14 years ago)
Author:
Yuri Dario
Message:

clamav: update trunk to 0.97.

Location:
clamav/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • clamav/trunk

  • TabularUnified clamav/trunk/libclamav/c++/llvm/lib/Transforms/Scalar/LoopUnswitch.cpp

    r189 r319  
    3535#include "llvm/Analysis/ConstantFolding.h"
    3636#include "llvm/Analysis/InlineCost.h"
     37#include "llvm/Analysis/InstructionSimplify.h"
    3738#include "llvm/Analysis/LoopInfo.h"
    3839#include "llvm/Analysis/LoopPass.h"
     
    7778
    7879    Loop *currentLoop;
    79     DominanceFrontier *DF;
    8080    DominatorTree *DT;
    8181    BasicBlock *loopHeader;
     
    9292    static char ID; // Pass ID, replacement for typeid
    9393    explicit LoopUnswitch(bool Os = false) :
    94       LoopPass(&ID), OptimizeForSize(Os), redoLoop(false),
    95       currentLoop(NULL), DF(NULL), DT(NULL), loopHeader(NULL),
     94      LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
     95      currentLoop(NULL), DT(NULL), loopHeader(NULL),
    9696      loopPreheader(NULL) {}
    9797
     
    100100
    101101    /// This transformation requires natural loop information & requires that
    102     /// loop preheaders be inserted into the CFG...
     102    /// loop preheaders be inserted into the CFG.
    103103    ///
    104104    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
     
    110110      AU.addPreservedID(LCSSAID);
    111111      AU.addPreserved<DominatorTree>();
    112       AU.addPreserved<DominanceFrontier>();
    113112    }
    114113
     
    160159}
    161160char LoopUnswitch::ID = 0;
    162 static RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
     161INITIALIZE_PASS(LoopUnswitch, "loop-unswitch", "Unswitch loops", false, false);
    163162
    164163Pass *llvm::createLoopUnswitchPass(bool Os) {
     
    201200  LI = &getAnalysis<LoopInfo>();
    202201  LPM = &LPM_Ref;
    203   DF = getAnalysisIfAvailable<DominanceFrontier>();
    204202  DT = getAnalysisIfAvailable<DominatorTree>();
    205203  currentLoop = L;
     
    207205  bool Changed = false;
    208206  do {
    209     assert(currentLoop->isLCSSAForm());
     207    assert(currentLoop->isLCSSAForm(*DT));
    210208    redoLoop = false;
    211209    Changed |= processCurrentLoop();
     
    216214    if (DT)
    217215      DT->runOnFunction(*F);
    218     if (DF)
    219       DF->runOnFunction(*F);
    220216  }
    221217  return Changed;
     
    232228  // loop.
    233229  for (Loop::block_iterator I = currentLoop->block_begin(),
    234          E = currentLoop->block_end();
    235        I != E; ++I) {
     230         E = currentLoop->block_end(); I != E; ++I) {
    236231    TerminatorInst *TI = (*I)->getTerminator();
    237232    if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
     
    283278}
    284279
    285 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
    286 ///   1. Exit the loop with no side effects.
    287 ///   2. Branch to the latch block with no side-effects.
     280/// isTrivialLoopExitBlock - Check to see if all paths from BB exit the
     281/// loop with no side effects (including infinite loops).
    288282///
    289 /// If these conditions are true, we return true and set ExitBB to the block we
     283/// If true, we return true and set ExitBB to the block we
    290284/// exit through.
    291285///
     
    294288                                         std::set<BasicBlock*> &Visited) {
    295289  if (!Visited.insert(BB).second) {
    296     // Already visited and Ok, end of recursion.
    297     return true;
     290    // Already visited. Without more analysis, this could indicate an infinte loop.
     291    return false;
    298292  } else if (!L->contains(BB)) {
    299293    // Otherwise, this is a loop exit, this is fine so long as this is the
     
    325319static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
    326320  std::set<BasicBlock*> Visited;
    327   Visited.insert(L->getHeader());  // Branches to header are ok.
     321  Visited.insert(L->getHeader());  // Branches to header make infinite loops.
    328322  BasicBlock *ExitBB = 0;
    329323  if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
     
    357351      return false;
    358352 
    359     // Check to see if a successor of the branch is guaranteed to go to the
    360     // latch block or exit through a one exit block without having any
     353    // Check to see if a successor of the branch is guaranteed to
     354    // exit through a unique exit block without having any
    361355    // side-effects.  If so, determine the value of Cond that causes it to do
    362356    // this.
     
    416410  Function *F = loopHeader->getParent();
    417411
    418   // If the condition is trivial, always unswitch.  There is no code growth for
    419   // this case.
    420   if (!IsTrivialUnswitchCondition(LoopCond)) {
    421     // Check to see if it would be profitable to unswitch current loop.
    422 
    423     // Do not do non-trivial unswitch while optimizing for size.
    424     if (OptimizeForSize || F->hasFnAttr(Attribute::OptimizeForSize))
    425       return false;
    426 
    427     // FIXME: This is overly conservative because it does not take into
    428     // consideration code simplification opportunities and code that can
    429     // be shared by the resultant unswitched loops.
    430     CodeMetrics Metrics;
    431     for (Loop::block_iterator I = currentLoop->block_begin(),
    432            E = currentLoop->block_end();
    433          I != E; ++I)
    434       Metrics.analyzeBasicBlock(*I);
    435 
    436     // Limit the number of instructions to avoid causing significant code
    437     // expansion, and the number of basic blocks, to avoid loops with
    438     // large numbers of branches which cause loop unswitching to go crazy.
    439     // This is a very ad-hoc heuristic.
    440     if (Metrics.NumInsts > Threshold ||
    441         Metrics.NumBlocks * 5 > Threshold ||
    442         Metrics.NeverInline) {
    443       DEBUG(dbgs() << "NOT unswitching loop %"
    444             << currentLoop->getHeader()->getName() << ", cost too high: "
    445             << currentLoop->getBlocks().size() << "\n");
    446       return false;
    447     }
    448   }
    449 
    450   Constant *CondVal;
    451   BasicBlock *ExitBlock;
     412  Constant *CondVal = 0;
     413  BasicBlock *ExitBlock = 0;
    452414  if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
     415    // If the condition is trivial, always unswitch. There is no code growth
     416    // for this case.
    453417    UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
    454   } else {
    455     UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
    456   }
    457 
     418    return true;
     419  }
     420
     421  // Check to see if it would be profitable to unswitch current loop.
     422
     423  // Do not do non-trivial unswitch while optimizing for size.
     424  if (OptimizeForSize || F->hasFnAttr(Attribute::OptimizeForSize))
     425    return false;
     426
     427  // FIXME: This is overly conservative because it does not take into
     428  // consideration code simplification opportunities and code that can
     429  // be shared by the resultant unswitched loops.
     430  CodeMetrics Metrics;
     431  for (Loop::block_iterator I = currentLoop->block_begin(),
     432         E = currentLoop->block_end();
     433       I != E; ++I)
     434    Metrics.analyzeBasicBlock(*I);
     435
     436  // Limit the number of instructions to avoid causing significant code
     437  // expansion, and the number of basic blocks, to avoid loops with
     438  // large numbers of branches which cause loop unswitching to go crazy.
     439  // This is a very ad-hoc heuristic.
     440  if (Metrics.NumInsts > Threshold ||
     441      Metrics.NumBlocks * 5 > Threshold ||
     442      Metrics.containsIndirectBr || Metrics.isRecursive) {
     443    DEBUG(dbgs() << "NOT unswitching loop %"
     444          << currentLoop->getHeader()->getName() << ", cost too high: "
     445          << currentLoop->getBlocks().size() << "\n");
     446    return false;
     447  }
     448
     449  UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
    458450  return true;
    459451}
    460452
    461453// RemapInstruction - Convert the instruction operands from referencing the
    462 // current values into those specified by ValueMap.
     454// current values into those specified by VMap.
    463455//
    464456static inline void RemapInstruction(Instruction *I,
    465                                     DenseMap<const Value *, Value*> &ValueMap) {
     457                                    ValueMap<const Value *, Value*> &VMap) {
    466458  for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
    467459    Value *Op = I->getOperand(op);
    468     DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
    469     if (It != ValueMap.end()) Op = It->second;
     460    ValueMap<const Value *, Value*>::iterator It = VMap.find(Op);
     461    if (It != VMap.end()) Op = It->second;
    470462    I->setOperand(op, Op);
    471463  }
     
    474466/// CloneLoop - Recursively clone the specified loop and all of its children,
    475467/// mapping the blocks with the specified map.
    476 static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
     468static Loop *CloneLoop(Loop *L, Loop *PL, ValueMap<const Value*, Value*> &VM,
    477469                       LoopInfo *LI, LPPassManager *LPM) {
    478470  Loop *New = new Loop();
    479 
    480471  LPM->insertLoop(New, PL);
    481472
     
    568559/// blocks.  Update the appropriate Phi nodes as we do so.
    569560void LoopUnswitch::SplitExitEdges(Loop *L,
    570                                 const SmallVector<BasicBlock *, 8> &ExitBlocks)
    571 {
     561                                const SmallVector<BasicBlock *, 8> &ExitBlocks){
    572562
    573563  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
     
    620610  // the instructions and blocks.
    621611  NewBlocks.reserve(LoopBlocks.size());
    622   DenseMap<const Value*, Value*> ValueMap;
     612  ValueMap<const Value*, Value*> VMap;
    623613  for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
    624     BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
    625     NewBlocks.push_back(New);
    626     ValueMap[LoopBlocks[i]] = New;  // Keep the BB mapping.
    627     LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
     614    BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
     615    NewBlocks.push_back(NewBB);
     616    VMap[LoopBlocks[i]] = NewBB;  // Keep the BB mapping.
     617    LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
    628618  }
    629619
    630620  // Splice the newly inserted blocks into the function right before the
    631621  // original preheader.
    632   F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
     622  F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
    633623                                NewBlocks[0], F->end());
    634624
    635625  // Now we create the new Loop object for the versioned loop.
    636   Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
     626  Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
    637627  Loop *ParentLoop = L->getParentLoop();
    638628  if (ParentLoop) {
     
    643633 
    644634  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
    645     BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
     635    BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
    646636    // The new exit block should be in the same loop as the old one.
    647637    if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
     
    655645    // NewExit.
    656646    PHINode *PN;
    657     for (BasicBlock::iterator I = ExitSucc->begin();
    658          (PN = dyn_cast<PHINode>(I)); ++I) {
     647    for (BasicBlock::iterator I = ExitSucc->begin(); isa<PHINode>(I); ++I) {
     648      PN = cast<PHINode>(I);
    659649      Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
    660       DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
    661       if (It != ValueMap.end()) V = It->second;
     650      ValueMap<const Value *, Value*>::iterator It = VMap.find(V);
     651      if (It != VMap.end()) V = It->second;
    662652      PN->addIncoming(V, NewExit);
    663653    }
     
    668658    for (BasicBlock::iterator I = NewBlocks[i]->begin(),
    669659           E = NewBlocks[i]->end(); I != E; ++I)
    670       RemapInstruction(I, ValueMap);
     660      RemapInstruction(I, VMap);
    671661 
    672662  // Rewrite the original preheader to select between versions of the loop.
     
    683673  redoLoop = true;
    684674
     675  // Keep a WeakVH holding onto LIC.  If the first call to RewriteLoopBody
     676  // deletes the instruction (for example by simplifying a PHI that feeds into
     677  // the condition that we're unswitching on), we don't rewrite the second
     678  // iteration.
     679  WeakVH LICHandle(LIC);
     680 
    685681  // Now we rewrite the original code to know that the condition is true and the
    686682  // new code to know that the condition is false.
    687   RewriteLoopBodyWithConditionConstant(L      , LIC, Val, false);
    688  
     683  RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
     684
    689685  // It's possible that simplifying one loop could cause the other to be
    690   // deleted.  If so, don't simplify it.
    691   if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
    692     RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
    693 
     686  // changed to another value or a constant.  If its a constant, don't simplify
     687  // it.
     688  if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
     689      LICHandle && !isa<Constant>(LICHandle))
     690    RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
    694691}
    695692
     
    887884        Worklist.push_back(U);
    888885      }
    889   } else {
    890     // Otherwise, we don't know the precise value of LIC, but we do know that it
    891     // is certainly NOT "Val".  As such, simplify any uses in the loop that we
    892     // can.  This case occurs when we unswitch switch statements.
    893     for (unsigned i = 0, e = Users.size(); i != e; ++i)
    894       if (Instruction *U = cast<Instruction>(Users[i])) {
    895         if (!L->contains(U))
    896           continue;
    897 
    898         Worklist.push_back(U);
    899 
    900         // If we know that LIC is not Val, use this info to simplify code.
    901         if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
    902           for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
    903             if (SI->getCaseValue(i) == Val) {
    904               // Found a dead case value.  Don't remove PHI nodes in the
    905               // successor if they become single-entry, those PHI nodes may
    906               // be in the Users list.
    907              
    908               // FIXME: This is a hack.  We need to keep the successor around
    909               // and hooked up so as to preserve the loop structure, because
    910               // trying to update it is complicated.  So instead we preserve the
    911               // loop structure and put the block on a dead code path.
    912               BasicBlock *Switch = SI->getParent();
    913               SplitEdge(Switch, SI->getSuccessor(i), this);
    914               // Compute the successors instead of relying on the return value
    915               // of SplitEdge, since it may have split the switch successor
    916               // after PHI nodes.
    917               BasicBlock *NewSISucc = SI->getSuccessor(i);
    918               BasicBlock *OldSISucc = *succ_begin(NewSISucc);
    919               // Create an "unreachable" destination.
    920               BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
    921                                                      Switch->getParent(),
    922                                                      OldSISucc);
    923               new UnreachableInst(Context, Abort);
    924               // Force the new case destination to branch to the "unreachable"
    925               // block while maintaining a (dead) CFG edge to the old block.
    926               NewSISucc->getTerminator()->eraseFromParent();
    927               BranchInst::Create(Abort, OldSISucc,
    928                                  ConstantInt::getTrue(Context), NewSISucc);
    929               // Release the PHI operands for this edge.
    930               for (BasicBlock::iterator II = NewSISucc->begin();
    931                    PHINode *PN = dyn_cast<PHINode>(II); ++II)
    932                 PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
    933                                      UndefValue::get(PN->getType()));
    934               // Tell the domtree about the new block. We don't fully update the
    935               // domtree here -- instead we force it to do a full recomputation
    936               // after the pass is complete -- but we do need to inform it of
    937               // new blocks.
    938               if (DT)
    939                 DT->addNewBlock(Abort, NewSISucc);
    940               break;
    941             }
    942           }
    943         }
     886    SimplifyCode(Worklist, L);
     887    return;
     888  }
     889 
     890  // Otherwise, we don't know the precise value of LIC, but we do know that it
     891  // is certainly NOT "Val".  As such, simplify any uses in the loop that we
     892  // can.  This case occurs when we unswitch switch statements.
     893  for (unsigned i = 0, e = Users.size(); i != e; ++i) {
     894    Instruction *U = cast<Instruction>(Users[i]);
     895    if (!L->contains(U))
     896      continue;
     897
     898    Worklist.push_back(U);
     899
     900    // TODO: We could do other simplifications, for example, turning
     901    // 'icmp eq LIC, Val' -> false.
     902
     903    // If we know that LIC is not Val, use this info to simplify code.
     904    SwitchInst *SI = dyn_cast<SwitchInst>(U);
     905    if (SI == 0 || !isa<ConstantInt>(Val)) continue;
     906   
     907    unsigned DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
     908    if (DeadCase == 0) continue;  // Default case is live for multiple values.
     909   
     910    // Found a dead case value.  Don't remove PHI nodes in the
     911    // successor if they become single-entry, those PHI nodes may
     912    // be in the Users list.
    944913       
    945         // TODO: We could do other simplifications, for example, turning
    946         // LIC == Val -> false.
    947       }
     914    // FIXME: This is a hack.  We need to keep the successor around
     915    // and hooked up so as to preserve the loop structure, because
     916    // trying to update it is complicated.  So instead we preserve the
     917    // loop structure and put the block on a dead code path.
     918    BasicBlock *Switch = SI->getParent();
     919    SplitEdge(Switch, SI->getSuccessor(DeadCase), this);
     920    // Compute the successors instead of relying on the return value
     921    // of SplitEdge, since it may have split the switch successor
     922    // after PHI nodes.
     923    BasicBlock *NewSISucc = SI->getSuccessor(DeadCase);
     924    BasicBlock *OldSISucc = *succ_begin(NewSISucc);
     925    // Create an "unreachable" destination.
     926    BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
     927                                           Switch->getParent(),
     928                                           OldSISucc);
     929    new UnreachableInst(Context, Abort);
     930    // Force the new case destination to branch to the "unreachable"
     931    // block while maintaining a (dead) CFG edge to the old block.
     932    NewSISucc->getTerminator()->eraseFromParent();
     933    BranchInst::Create(Abort, OldSISucc,
     934                       ConstantInt::getTrue(Context), NewSISucc);
     935    // Release the PHI operands for this edge.
     936    for (BasicBlock::iterator II = NewSISucc->begin();
     937         PHINode *PN = dyn_cast<PHINode>(II); ++II)
     938      PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
     939                           UndefValue::get(PN->getType()));
     940    // Tell the domtree about the new block. We don't fully update the
     941    // domtree here -- instead we force it to do a full recomputation
     942    // after the pass is complete -- but we do need to inform it of
     943    // new blocks.
     944    if (DT)
     945      DT->addNewBlock(Abort, NewSISucc);
    948946  }
    949947 
     
    986984    }
    987985   
     986    // See if instruction simplification can hack this up.  This is common for
     987    // things like "select false, X, Y" after unswitching made the condition be
     988    // 'false'.
     989    if (Value *V = SimplifyInstruction(I)) {
     990      ReplaceUsesOfWith(I, V, Worklist, L, LPM);
     991      continue;
     992    }
     993   
    988994    // Special case hacks that appear commonly in unswitched code.
    989     switch (I->getOpcode()) {
    990     case Instruction::Select:
    991       if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
    992         ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L,
    993                           LPM);
    994         continue;
    995       }
    996       break;
    997     case Instruction::And:
    998       if (isa<ConstantInt>(I->getOperand(0)) &&
    999           // constant -> RHS
    1000           I->getOperand(0)->getType()->isIntegerTy(1))
    1001         cast<BinaryOperator>(I)->swapOperands();
    1002       if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
    1003         if (CB->getType()->isIntegerTy(1)) {
    1004           if (CB->isOne())      // X & 1 -> X
    1005             ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
    1006           else                  // X & 0 -> 0
    1007             ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
    1008           continue;
    1009         }
    1010       break;
    1011     case Instruction::Or:
    1012       if (isa<ConstantInt>(I->getOperand(0)) &&
    1013           // constant -> RHS
    1014           I->getOperand(0)->getType()->isIntegerTy(1))
    1015         cast<BinaryOperator>(I)->swapOperands();
    1016       if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
    1017         if (CB->getType()->isIntegerTy(1)) {
    1018           if (CB->isOne())   // X | 1 -> 1
    1019             ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
    1020           else                  // X | 0 -> X
    1021             ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
    1022           continue;
    1023         }
    1024       break;
    1025     case Instruction::Br: {
    1026       BranchInst *BI = cast<BranchInst>(I);
     995    if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
    1027996      if (BI->isUnconditional()) {
    1028997        // If BI's parent is the only pred of the successor, fold the two blocks
     
    10571026        Succ->eraseFromParent();
    10581027        ++NumSimplify;
    1059       } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
     1028        continue;
     1029      }
     1030     
     1031      if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
    10601032        // Conditional branch.  Turn it into an unconditional branch, then
    10611033        // remove dead blocks.
    1062         break;  // FIXME: Enable.
     1034        continue;  // FIXME: Enable.
    10631035
    10641036        DEBUG(dbgs() << "Folded branch: " << *BI);
     
    10741046        RemoveBlockIfDead(DeadSucc, Worklist, L);
    10751047      }
    1076       break;
    1077     }
    1078     }
    1079   }
    1080 }
     1048      continue;
     1049    }
     1050  }
     1051}
Note: See TracChangeset for help on using the changeset viewer.