Ejemplo n.º 1
0
void BlockGenerator::copyBB(ValueMapT &GlobalMap, LoopToScevMapT &LTS) {
  BasicBlock *BB = Statement.getBasicBlock();
  BasicBlock *CopyBB =
      SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
  CopyBB->setName("polly.stmt." + BB->getName());
  Builder.SetInsertPoint(CopyBB->begin());

  ValueMapT BBMap;

  for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
       ++II)
    copyInstruction(II, BBMap, GlobalMap, LTS);
}
Ejemplo n.º 2
0
void smtit::performTest1() {

  for (Module::iterator FI = Mod->begin(), FE = Mod->end(); FI != FE; ++FI) {
    Function *Func = &*FI;
    // DEBUG(errs() << *Func << "\n");
    for (Function::iterator BI = Func->begin(), BE = Func->end(); BI != BE;
         ++BI) {
      BasicBlock *BB = &*BI;
      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
        Instruction *BBI = &*I;
        //if (true == isa<StoreInst>(BBI)) {
        if (true == isa<LoadInst>(BBI)) {
          LoadInst *li  = dyn_cast<LoadInst>(BBI);
          Value *ptrOp = li->getPointerOperand();
          DEBUG(errs() << *li << "\t Result Name: " << li->getName() << "\t Pointer Name: " << ptrOp->getName() << "\n");

          // DEBUG(errs() << "\tStore Instruction: " << *BBI << " \n");
          // DEBUG(errs() << "\t\tPointerType: " << isLLVMPAPtrTy(SI->getType())
          // << " \n");
          // Instruction* V = cast<Instruction>(SI->getOperand(1));
          // DEBUG(errs() << "\tOperand : " << *V << " \n");
          // DEBUG(errs() << "\t\tPointerType: " << isLLVMPAPtrTy(V->getType())
          // << " \n");
        } else if(true == isa<GetElementPtrInst>(BBI)) {
          GetElementPtrInst *gep  = dyn_cast<GetElementPtrInst>(BBI);
          DEBUG(errs() << *gep << "\t Result Name: " << gep->getName() << "\n");
          // DEBUG(errs() << "\tInstruction: " << *BBI << " \n");
          // DEBUG(errs() << "\t\tPointerType: " <<
          // isLLVMPAPtrTy(BBI->getType()) << " \n");
        }

        // For def-use chains: All the uses of the definition
        //DEBUG(errs() << *BBI << "\n");
        /*
        for (User *U : BBI->users()) {
          if (Instruction *Inst = dyn_cast<Instruction>(U)) {
            DEBUG(errs()<< " " <<  *Inst << "\n");
          }
        }

        for (Value::user_iterator i = BBI->user_begin(), e = BBI->user_end();
              i != e; ++i) {
          if (Instruction *user_inst = dyn_cast<Instruction>(*i)) {
            DEBUG(errs()<< " " << *user_inst << "\n");
          }
        }
        */
      }
    }
  }
}
Ejemplo n.º 3
0
bool llvm::isPotentiallyReachable(const Instruction *A, const Instruction *B,
                                  const DominatorTree *DT, const LoopInfo *LI) {
  assert(A->getParent()->getParent() == B->getParent()->getParent() &&
         "This analysis is function-local!");

  SmallVector<BasicBlock*, 32> Worklist;

  if (A->getParent() == B->getParent()) {
    // The same block case is special because it's the only time we're looking
    // within a single block to see which instruction comes first. Once we
    // start looking at multiple blocks, the first instruction of the block is
    // reachable, so we only need to determine reachability between whole
    // blocks.
    BasicBlock *BB = const_cast<BasicBlock *>(A->getParent());

    // If the block is in a loop then we can reach any instruction in the block
    // from any other instruction in the block by going around a backedge.
    if (LI && LI->getLoopFor(BB) != nullptr)
      return true;

    // Linear scan, start at 'A', see whether we hit 'B' or the end first.
    for (BasicBlock::const_iterator I = A->getIterator(), E = BB->end(); I != E;
         ++I) {
      if (&*I == B)
        return true;
    }

    // Can't be in a loop if it's the entry block -- the entry block may not
    // have predecessors.
    if (BB == &BB->getParent()->getEntryBlock())
      return false;

    // Otherwise, continue doing the normal per-BB CFG walk.
    Worklist.append(succ_begin(BB), succ_end(BB));

    if (Worklist.empty()) {
      // We've proven that there's no path!
      return false;
    }
  } else {
    Worklist.push_back(const_cast<BasicBlock*>(A->getParent()));
  }

  if (A->getParent() == &A->getParent()->getParent()->getEntryBlock())
    return true;
  if (B->getParent() == &A->getParent()->getParent()->getEntryBlock())
    return false;

  return isPotentiallyReachableFromMany(
      Worklist, const_cast<BasicBlock *>(B->getParent()), DT, LI);
}
Ejemplo n.º 4
0
void MLStatic::expandPath(std::vector<BasicBlock *> tpath, Function *F){
		
	std::vector<Instruction *> temp;
	for(int i=0;i<tpath.size();++i){
		BasicBlock * BB = tpath[i];	
		for (BasicBlock::iterator i = BB->begin(), ie = BB->end(); i != ie; ++i){
			temp.push_back(i);

		}

	}		
	expandedPath[F].push_back(temp);

}
Ejemplo n.º 5
0
/// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
/// only has one predecessor, and that predecessor only has one successor.
/// The LoopInfo Analysis that is passed will be kept consistent.
/// Returns the new combined block.
static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI,
                                            LPPassManager *LPM) {
  // Merge basic blocks into their predecessor if there is only one distinct
  // pred, and if there is only one distinct successor of the predecessor, and
  // if there are no PHI nodes.
  BasicBlock *OnlyPred = BB->getSinglePredecessor();
  if (!OnlyPred) return 0;

  if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
    return 0;

  DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);

  // Resolve any PHI nodes at the start of the block.  They are all
  // guaranteed to have exactly one entry if they exist, unless there are
  // multiple duplicate (but guaranteed to be equal) entries for the
  // incoming edges.  This occurs when there are multiple edges from
  // OnlyPred to OnlySucc.
  FoldSingleEntryPHINodes(BB);

  // Delete the unconditional branch from the predecessor...
  OnlyPred->getInstList().pop_back();

  // Make all PHI nodes that referred to BB now refer to Pred as their
  // source...
  BB->replaceAllUsesWith(OnlyPred);

  // Move all definitions in the successor to the predecessor...
  OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());

  std::string OldName = BB->getName();

  // Erase basic block from the function...

  // ScalarEvolution holds references to loop exit blocks.
  if (LPM) {
    if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>()) {
      if (Loop *L = LI->getLoopFor(BB))
        SE->forgetLoop(L);
    }
  }
  LI->removeBlock(BB);
  BB->eraseFromParent();

  // Inherit predecessor's name if it exists...
  if (!OldName.empty() && !OnlyPred->hasName())
    OnlyPred->setName(OldName);

  return OnlyPred;
}
bool BranchProbabilities::CheckReturnHeuristic(int i)
{
    BasicBlock *BB = _Succ[i];

    // Loop through all instructions in the block
    for (BasicBlock::iterator I = BB->begin(), IEnd = BB->end(); I != IEnd; ++I)
    {
        // Return true if we have the specified instruction
        if (isa<ReturnInst>(I))
            return true;
    }

    return false;
}
Ejemplo n.º 7
0
void SetInsertionPoint(bool after, IRBuilder<>& ib, Instruction* ptr)
{
	if(!after) {
		ib.SetInsertPoint(ptr);
		return;
	}
	BasicBlock* BB = ptr->getParent();
	llvm::BasicBlock::iterator i;
	for( i = BB->begin(); i != BB->end(); i++) {
		if(i.getNodePtrUnchecked() == ptr) { break; }
	}
	i++;
	ib.SetInsertPoint(i);
}
Ejemplo n.º 8
0
/// \brief Test whether a block is valid for extraction.
bool CodeExtractor::isBlockValidForExtraction(const BasicBlock &BB,
                                              bool AllowVarArgs) {
  // Landing pads must be in the function where they were inserted for cleanup.
  if (BB.isEHPad())
    return false;
  // taking the address of a basic block moved to another function is illegal
  if (BB.hasAddressTaken())
    return false;

  // don't hoist code that uses another basicblock address, as it's likely to
  // lead to unexpected behavior, like cross-function jumps
  SmallPtrSet<User const *, 16> Visited;
  SmallVector<User const *, 16> ToVisit;

  for (Instruction const &Inst : BB)
    ToVisit.push_back(&Inst);

  while (!ToVisit.empty()) {
    User const *Curr = ToVisit.pop_back_val();
    if (!Visited.insert(Curr).second)
      continue;
    if (isa<BlockAddress const>(Curr))
      return false; // even a reference to self is likely to be not compatible

    if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->getParent() != &BB)
      continue;

    for (auto const &U : Curr->operands()) {
      if (auto *UU = dyn_cast<User>(U))
        ToVisit.push_back(UU);
    }
  }

  // Don't hoist code containing allocas or invokes. If explicitly requested,
  // allow vastart.
  for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
    if (isa<AllocaInst>(I) || isa<InvokeInst>(I))
      return false;
    if (const CallInst *CI = dyn_cast<CallInst>(I))
      if (const Function *F = CI->getCalledFunction())
        if (F->getIntrinsicID() == Intrinsic::vastart) {
          if (AllowVarArgs)
            continue;
          else
            return false;
        }
  }

  return true;
}
Ejemplo n.º 9
0
/// runOnFunction - Process all loops in the function, inner-most out.
bool LCSSA::runOnLoop(Loop *TheLoop, LPPassManager &LPM) {
  L = TheLoop;
  
  DT = &getAnalysis<DominatorTree>();

  // Get the set of exiting blocks.
  SmallVector<BasicBlock*, 8> ExitBlocks;
  L->getExitBlocks(ExitBlocks);
  
  if (ExitBlocks.empty())
    return false;
  
  // Speed up queries by creating a sorted vector of blocks.
  LoopBlocks.clear();
  LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
  array_pod_sort(LoopBlocks.begin(), LoopBlocks.end());
  
  // Look at all the instructions in the loop, checking to see if they have uses
  // outside the loop.  If so, rewrite those uses.
  bool MadeChange = false;
  
  for (Loop::block_iterator BBI = L->block_begin(), E = L->block_end();
       BBI != E; ++BBI) {
    BasicBlock *BB = *BBI;
    
    // For large loops, avoid use-scanning by using dominance information:  In
    // particular, if a block does not dominate any of the loop exits, then none
    // of the values defined in the block could be used outside the loop.
    if (!BlockDominatesAnExit(BB, ExitBlocks, DT))
      continue;
    
    for (BasicBlock::iterator I = BB->begin(), E = BB->end();
         I != E; ++I) {
      // Reject two common cases fast: instructions with no uses (like stores)
      // and instructions with one use that is in the same block as this.
      if (I->use_empty() ||
          (I->hasOneUse() && I->use_back()->getParent() == BB &&
           !isa<PHINode>(I->use_back())))
        continue;
      
      MadeChange |= ProcessInstruction(I, ExitBlocks);
    }
  }
  
  assert(L->isLCSSAForm(*DT));
  PredCache.clear();

  return MadeChange;
}
Ejemplo n.º 10
0
/*
 * Verify if a given value has references after a call site.
 */
bool DeadStoreEliminationPass::isRefAfterCallSite(Value* v, CallSite &CS) {
  BasicBlock* CSBB = CS.getInstruction()->getParent();

  // Collect basic blocks to inspect
  std::vector<BasicBlock*> BBToInspect;
  std::set<BasicBlock*> BBToInspectSet;
  BBToInspect.push_back(CSBB);
  BBToInspectSet.insert(CSBB);
  for (unsigned int i = 0; i < BBToInspect.size(); ++i) {
    BasicBlock* BB = BBToInspect.at(i);
    TerminatorInst* terminator = BB->getTerminator();
    if (terminator && terminator->getNumSuccessors() > 0) {
      unsigned numSuccessors = terminator->getNumSuccessors();
      for (unsigned i = 0; i < numSuccessors; ++i) {
        // Collect successors
        BasicBlock* successor = terminator->getSuccessor(i);
        if (!BBToInspectSet.count(successor)) {
          BBToInspect.push_back(successor);
          BBToInspectSet.insert(successor);
        }
      }
    }
  }

  // Inspect if any instruction after CS references v
  AliasAnalysis::Location loc(v, getPointerSize(v, *AA), NULL);
  for (unsigned int i = 0; i < BBToInspect.size(); ++i) {
    BasicBlock* BB = BBToInspect.at(i);
    BasicBlock::iterator I = BB->begin();
    if (BB == CSBB) {
      Instruction* callInst = CS.getInstruction();
      Instruction* inst;
      do {
        inst = I;
        ++I;
      } while (inst != callInst);
    }
    for (BasicBlock::iterator IE = BB->end(); I != IE; ++I) {
      Instruction* inst = I;
      DEBUG(errs() << "Verifying if instruction " << *inst << " refs " << *v << ": ");
      AliasAnalysis::ModRefResult mrf = AA->getModRefInfo(inst, loc);
      DEBUG(errs() << mrf << "\n");
      if (mrf == AliasAnalysis::Ref || mrf == AliasAnalysis::ModRef) {
        return true;
      }
    }
  }
  return false;
}
Ejemplo n.º 11
0
/// \brief Check whether or not this function needs a stack protector based
/// upon the stack protector level.
///
/// We use two heuristics: a standard (ssp) and strong (sspstrong).
/// The standard heuristic which will add a guard variable to functions that
/// call alloca with a either a variable size or a size >= SSPBufferSize,
/// functions with character buffers larger than SSPBufferSize, and functions
/// with aggregates containing character buffers larger than SSPBufferSize. The
/// strong heuristic will add a guard variables to functions that call alloca
/// regardless of size, functions with any buffer regardless of type and size,
/// functions with aggregates that contain any buffer regardless of type and
/// size, and functions that contain stack-based variables that have had their
/// address taken.
bool StackProtector::RequiresStackProtector() {
  bool Strong = false;
  if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
                                      Attribute::StackProtectReq))
    return true;
  else if (F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
                                           Attribute::StackProtectStrong))
    Strong = true;
  else if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
                                            Attribute::StackProtect))
    return false;

  for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
    BasicBlock *BB = I;

    for (BasicBlock::iterator
           II = BB->begin(), IE = BB->end(); II != IE; ++II) {
      if (AllocaInst *AI = dyn_cast<AllocaInst>(II)) {
        if (AI->isArrayAllocation()) {
          // SSP-Strong: Enable protectors for any call to alloca, regardless
          // of size.
          if (Strong)
            return true;

          if (const ConstantInt *CI =
               dyn_cast<ConstantInt>(AI->getArraySize())) {
            if (CI->getLimitedValue(SSPBufferSize) >= SSPBufferSize)
              // A call to alloca with size >= SSPBufferSize requires
              // stack protectors.
              return true;
          } else {
            // A call to alloca with a variable size requires protectors.
            return true;
          }
        }

        if (ContainsProtectableArray(AI->getAllocatedType(), Strong))
          return true;

        if (Strong && HasAddressTaken(AI)) {
          ++NumAddrTaken;
          return true;
        }
      }
    }
  }

  return false;
}
void ConstantInsertExtractElementIndex::findNonConstantInsertExtractElements(
    const BasicBlock &BB, Instructions &OutOfRangeConstantIndices,
    Instructions &NonConstantVectorIndices) const {
  for (BasicBlock::const_iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE;
       ++BBI) {
    const Instruction *I = &*BBI;
    if (Value *Idx = getInsertExtractElementIdx(I)) {
      if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
        if (!CI->getValue().ult(vectorNumElements(I)))
          OutOfRangeConstantIndices.push_back(const_cast<Instruction *>(I));
      } else
        NonConstantVectorIndices.push_back(const_cast<Instruction *>(I));
    }
  }
}
bool ExpandGetElementPtr::runOnBasicBlock(BasicBlock &BB) {
    bool Modified = false;
    DataLayout DL(BB.getParent()->getParent());
    Type *PtrType = DL.getIntPtrType(BB.getContext());

    for (BasicBlock::InstListType::iterator Iter = BB.begin();
            Iter != BB.end(); ) {
        Instruction *Inst = Iter++;
        if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
            Modified = true;
            ExpandGEP(GEP, &DL, PtrType);
        }
    }
    return Modified;
}
Ejemplo n.º 14
0
bool Scalarizer::runOnFunction(Function &F) {
  TDL = getAnalysisIfAvailable<DataLayout>();

  for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
    BasicBlock *BB = BBI;
    for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
      Instruction *I = II;
      bool Done = visit(I);
      ++II;
      if (Done && I->getType()->isVoidTy())
        I->eraseFromParent();
    }
  }
  return finish();
}
Ejemplo n.º 15
0
bool MisalignStackPass::runOnBasicBlock (BasicBlock &BB)
{
    bool Changed = false;
    const unsigned alignLimit = sizeof(uint32_t);

    for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
        AllocaInst *AI = dyn_cast<AllocaInst>(I);

        if (AI && AI->getAlignment() > alignLimit) {
            AI->setAlignment(alignLimit);
            Changed = true;
        }
    }

    return Changed;
}
Ejemplo n.º 16
0
bool Aa::LowerConstantExpr::runOnFunction(Function &F)
{
  for (Function::iterator bi = F.begin(), be = F.end(); bi != be; ++bi) {
    BasicBlock *bb = bi;
    
    BasicBlock::iterator ii = bb->begin();
    while (ii != bb->end()) {
      Instruction *inst = ii;
      BasicBlock::iterator II = ii++;
      
      process(inst);
    }
  }

  return true;
}
Ejemplo n.º 17
0
bool NaryReassociate::doOneIteration(Function &F) {
  bool Changed = false;
  SeenExprs.clear();
  // Process the basic blocks in pre-order of the dominator tree. This order
  // ensures that all bases of a candidate are in Candidates when we process it.
  for (auto Node = GraphTraits<DominatorTree *>::nodes_begin(DT);
       Node != GraphTraits<DominatorTree *>::nodes_end(DT); ++Node) {
    BasicBlock *BB = Node->getBlock();
    for (auto I = BB->begin(); I != BB->end(); ++I) {
      if (SE->isSCEVable(I->getType()) && isPotentiallyNaryReassociable(I)) {
        const SCEV *OldSCEV = SE->getSCEV(I);
        if (Instruction *NewI = tryReassociate(I)) {
          Changed = true;
          SE->forgetValue(I);
          I->replaceAllUsesWith(NewI);
          RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
          I = NewI;
        }
        // Add the rewritten instruction to SeenExprs; the original instruction
        // is deleted.
        const SCEV *NewSCEV = SE->getSCEV(I);
        SeenExprs[NewSCEV].push_back(I);
        // Ideally, NewSCEV should equal OldSCEV because tryReassociate(I)
        // is equivalent to I. However, ScalarEvolution::getSCEV may
        // weaken nsw causing NewSCEV not to equal OldSCEV. For example, suppose
        // we reassociate
        //   I = &a[sext(i +nsw j)] // assuming sizeof(a[0]) = 4
        // to
        //   NewI = &a[sext(i)] + sext(j).
        //
        // ScalarEvolution computes
        //   getSCEV(I)    = a + 4 * sext(i + j)
        //   getSCEV(newI) = a + 4 * sext(i) + 4 * sext(j)
        // which are different SCEVs.
        //
        // To alleviate this issue of ScalarEvolution not always capturing
        // equivalence, we add I to SeenExprs[OldSCEV] as well so that we can
        // map both SCEV before and after tryReassociate(I) to I.
        //
        // This improvement is exercised in @reassociate_gep_nsw in nary-gep.ll.
        if (NewSCEV != OldSCEV)
          SeenExprs[OldSCEV].push_back(I);
      }
    }
  }
  return Changed;
}
Ejemplo n.º 18
0
/// Instrumentation passes often insert conditional checks into entry blocks.
/// Call this function before splitting the entry block to move instructions
/// that must remain in the entry block up before the split point. Static
/// allocas and llvm.localescape calls, for example, must remain in the entry
/// block.
BasicBlock::iterator llvm::PrepareToSplitEntryBlock(BasicBlock &BB,
                                                    BasicBlock::iterator IP) {
  assert(&BB.getParent()->getEntryBlock() == &BB);
  for (auto I = IP, E = BB.end(); I != E; ++I) {
    bool KeepInEntry = false;
    if (auto *AI = dyn_cast<AllocaInst>(I)) {
      if (AI->isStaticAlloca())
        KeepInEntry = true;
    } else if (auto *II = dyn_cast<IntrinsicInst>(I)) {
      if (II->getIntrinsicID() == llvm::Intrinsic::localescape)
        KeepInEntry = true;
    }
    if (KeepInEntry)
      IP = moveBeforeInsertPoint(I, IP);
  }
  return IP;
}
Ejemplo n.º 19
0
/// \brief Test whether a block is valid for extraction.
bool CodeExtractor::isBlockValidForExtraction(const BasicBlock &BB) {
  // Landing pads must be in the function where they were inserted for cleanup.
  if (BB.isEHPad())
    return false;

  // Don't hoist code containing allocas, invokes, or vastarts.
  for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
    if (isa<AllocaInst>(I) || isa<InvokeInst>(I))
      return false;
    if (const CallInst *CI = dyn_cast<CallInst>(I))
      if (const Function *F = CI->getCalledFunction())
        if (F->getIntrinsicID() == Intrinsic::vastart)
          return false;
  }

  return true;
}
Ejemplo n.º 20
0
/// \brief Create a new or reuse the previous node as flow node
BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
  BasicBlock *Entry = PrevNode->getEntry();

  if (!PrevNode->isSubRegion()) {
    killTerminator(Entry);
    if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
      return Entry;
  }

  // create a new flow node
  BasicBlock *Flow = getNextFlow(Entry);

  // and wire it up
  changeExit(PrevNode, Flow, true);
  PrevNode = ParentRegion->getBBNode(Flow);
  return Flow;
}
Ejemplo n.º 21
0
  virtual bool runOnBasicBlock(BasicBlock &BB) {
    const DataLayout &DL = getAnalysis<DataLayoutPass>().getDataLayout();
    for (BasicBlock::iterator II = BB.begin(), II_e = BB.end(); II != II_e;
         ++II) {
      // Iterate over each instruction in the BasicBlock. If the instruction
      // is an alloca, dump its type and query the type's size.
      if (AllocaInst *Alloca = dyn_cast<AllocaInst>(II)) {
        Type *AllocType = Alloca->getAllocatedType();
        AllocType->print(outs());
        outs() << " size " << DL.getTypeSizeInBits(AllocType) << " bits\n";
      }
    }

    // Return false to signal that the basic block was not modified by this
    // pass.
    return false;
  }
Ejemplo n.º 22
0
/// ChangeToUnreachable - Insert an unreachable instruction before the specified
/// instruction, making it and the rest of the code in the block dead.
static void ChangeToUnreachable(Instruction *I) {
    BasicBlock *BB = I->getParent();
    // Loop over all of the successors, removing BB's entry from any PHI
    // nodes.
    for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
        (*SI)->removePredecessor(BB);

    new UnreachableInst(I);

    // All instructions after this are dead.
    BasicBlock::iterator BBI = I, BBE = BB->end();
    while (BBI != BBE) {
        if (!BBI->use_empty())
            BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
        BB->getInstList().erase(BBI++);
    }
}
Ejemplo n.º 23
0
void HexagonVectorLoopCarriedReuse::findLoopCarriedDeps() {
  BasicBlock *BB = CurLoop->getHeader();
  for (auto I = BB->begin(), E = BB->end(); I != E && isa<PHINode>(I); ++I) {
    auto *PN = cast<PHINode>(I);
    if (!isa<VectorType>(PN->getType()))
      continue;

    DepChain *D = new DepChain();
    findDepChainFromPHI(PN, *D);
    if (D->size() != 0)
      Dependences.insert(D);
    else
      delete D;
  }
  LLVM_DEBUG(dbgs() << "Found " << Dependences.size() << " dependences\n");
  LLVM_DEBUG(for (size_t i = 0; i < Dependences.size();
                  ++i) { dbgs() << *Dependences[i] << "\n"; });
Ejemplo n.º 24
0
int main(int argc, char **argv)
{
	if(argc < 2)
		error("Missing file name.");

	LLVMContext context;
	SMDiagnostic diag;
	OwningPtr<Module> module;
	
	module.reset(ParseIRFile(argv[1], diag, context));
	if(!module.get())
		error("Failed to load IR.");

	for(Module::iterator iter = module->begin(); iter != module->end(); iter++) {
		Function *func = iter;

		char *name = (char *)malloc(1024);
		size_t len = 1024;
		int err;

		name = abi::__cxa_demangle(func->getName().data(), name, &len, &err);
		if(err)
			continue;

		name[strlen(name)-2] = '\0';

		for(Function::iterator iter = func->begin(); iter != func->end(); iter++) {
			BasicBlock *block = iter;

			for(BasicBlock::iterator iter = block->begin(); iter != block->end(); iter++) {
				Instruction *inst = iter;

				if(inst->getOpcode() != Instruction::PtrToInt)
					continue;

				DILocation loc(inst->getMetadata("dbg"));

				printf("%s:%u\n", loc.getFilename().data(), loc.getLineNumber());
			}
		}
		free(name);
	}

	return 0;
}
Ejemplo n.º 25
0
bool BranchProbabilities::CheckInstHeuristic(int i)
{
    if (_bPostDoms[i])
        return false;

    BasicBlock *BB = _Succ[i];

    // Loop through all instructions in the block
    for (BasicBlock::iterator I = BB->begin(), IEnd = BB->end(); I != IEnd; ++I)
    {
        // Return true if we have the specified instruction
        if (isa<InstType>(I))
            return true;
    }

    // Did not find the instruction
    return false;
}
Ejemplo n.º 26
0
///////////////////
// NEW begin
///////////////////
// check dynamic pair satisfy anti-dependency
bool idenRegion::isAntiDepPair(LoadInst *Load, StoreInst *Store) {
    // perform a DFS to check if store is after load
    typedef std::pair<BasicBlock *, BasicBlock::iterator> WorkItem;
    SmallVector<WorkItem, 8> Worklist;
    SmallPtrSet<BasicBlock *, 32> Visited;

    BasicBlock *LoadBB = Load->getParent();
    Worklist.push_back(WorkItem(LoadBB, Load));

    do {
        BasicBlock *BB;
        BasicBlock::iterator I, E;
        tie(BB, I) = Worklist.pop_back_val();

        errs() << "... On BB " << BB->getName() << "\n";
        
        // If we revisited LoadBB, we scan to Load to complete cycle
        // Otherwise we end at BB->end()
        E = (BB == LoadBB && I == BB->begin()) ? Load : BB->end();
        // errs() << "... Last instruction on current BB is " << getLocator(*E) << "\n";

        // iterate throught BB to check if Load instruction exist in the BB
        while (I != E) {
            // errs() << "...... Inst: " << getLocator(*I) << "\n";
            if (isa<StoreInst>(I) && dyn_cast<StoreInst>(I) == Store) {
                return true;
            }
            ++I;
        }
        
        // get current BB's succesor
        TerminatorInst* ti = BB->getTerminator();
        int numSuccesor = ti->getNumSuccessors();
        for (int i = 0; i < numSuccesor; i++) {
            BasicBlock* nextSuc = ti->getSuccessor(i);
            // don't count backedge
            if (Visited.insert(nextSuc) && !DT->dominates(nextSuc, BB)) {
                Worklist.push_back(WorkItem(nextSuc, nextSuc->begin()));
            }
        }
    } while(!Worklist.empty());

    return false;
}
Ejemplo n.º 27
0
void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F,
                                                    BasicBlock &BB) {
  BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
  // Skip static allocas at the top of the entry block so they don't become
  // dynamic when we split the block.  If we used our optimized stack layout,
  // then there will only be one alloca and it will come first.
  for (; IP != BE; ++IP) {
    AllocaInst *AI = dyn_cast<AllocaInst>(IP);
    if (!AI || !AI->isStaticAlloca())
      break;
  }

  bool IsEntryBB = &BB == &F.getEntryBlock();
  DebugLoc EntryLoc =
      IsEntryBB ? IP->getDebugLoc().getFnDebugLoc(*C) : IP->getDebugLoc();
  IRBuilder<> IRB(IP);
  IRB.SetCurrentDebugLocation(EntryLoc);
  SmallVector<Value *, 1> Indices;
  Value *GuardP = IRB.CreateAdd(
      IRB.CreatePointerCast(GuardArray, IntptrTy),
      ConstantInt::get(IntptrTy, (1 + SanCovFunction->getNumUses()) * 4));
  Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
  GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
  LoadInst *Load = IRB.CreateLoad(GuardP);
  Load->setAtomic(Monotonic);
  Load->setAlignment(4);
  Load->setMetadata(F.getParent()->getMDKindID("nosanitize"),
                    MDNode::get(*C, None));
  Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
  Instruction *Ins = SplitBlockAndInsertIfThen(
      Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
  IRB.SetInsertPoint(Ins);
  IRB.SetCurrentDebugLocation(EntryLoc);
  // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
  IRB.CreateCall(SanCovFunction, GuardP);
  IRB.CreateCall(EmptyAsm);  // Avoids callback merge.

  if (ClExperimentalTracing) {
    // Experimental support for tracing.
    // Insert a callback with the same guard variable as used for coverage.
    IRB.SetInsertPoint(IP);
    IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
  }
}
Ejemplo n.º 28
0
   void remove_stupid_allocs(BasicBlock& blk)
   {
      BasicBlock::iterator it(blk.begin());
      BasicBlock::iterator end(blk.end());

      for(; it != end;) {
         Instruction& instr(*it);
         it++;

         if(AllocaInst::classof(&instr)) {
            AllocaInst *alloc((AllocaInst*)&instr);

            if(alloc->use_empty()) {
               alloc->eraseFromParent();
               cout << "Removing an unused alloc...\n";
            }
         }
      }
   }
Ejemplo n.º 29
0
bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
  // If we have a SelectInst that will likely profit from branch prediction,
  // turn it into a branch.
  if (DisableSelectToBranch || OptSize || !TLI ||
      !TLI->isPredictableSelectExpensive())
    return false;

  if (!SI->getCondition()->getType()->isIntegerTy(1) ||
      !isFormingBranchFromSelectProfitable(SI))
    return false;

  ModifiedDT = true;

  // First, we split the block containing the select into 2 blocks.
  BasicBlock *StartBlock = SI->getParent();
  BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
  BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");

  // Create a new block serving as the landing pad for the branch.
  BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
                                             NextBlock->getParent(), NextBlock);

  // Move the unconditional branch from the block with the select in it into our
  // landing pad block.
  StartBlock->getTerminator()->eraseFromParent();
  BranchInst::Create(NextBlock, SmallBlock);

  // Insert the real conditional branch based on the original condition.
  BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);

  // The select itself is replaced with a PHI Node.
  PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
  PN->takeName(SI);
  PN->addIncoming(SI->getTrueValue(), StartBlock);
  PN->addIncoming(SI->getFalseValue(), SmallBlock);
  SI->replaceAllUsesWith(PN);
  SI->eraseFromParent();

  // Instruct OptimizeBlock to skip to the next block.
  CurInstIterator = StartBlock->end();
  ++NumSelectsExpanded;
  return true;
}
/// FindCallsAndStores - Search for call and store instruction on basic blocks.
void BranchPredictionInfo::FindCallsAndStores(Function &F) {
  // Run through all basic blocks of functions.
  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
    BasicBlock *BB = FI;

    // We only need to know if a basic block contains ONE call and/or ONE store.
    bool calls = false;
    bool stores = false;

    // If the terminator instruction is an InvokeInstruction, add it directly.
    // An invoke instruction can be interpreted as a call.
    if (isa<InvokeInst>(BB->getTerminator())) {
      listCalls.insert(BB);
      calls = true;
    }

    // Run over through all basic block searching for any calls.
    for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
         BI != BE; ++BI) {
      // If we found one of each, we don't need to search anymore.
      if (stores && calls)
        break;

      // Obtain the current basic block instruction.
      Instruction *I = BI;

      // If we haven't found a store yet, test the instruction
      // and mark it if it is a store instruction.
      if (!stores && isa<StoreInst>(I)) {
        listStores.insert(BB);
        stores = true;
      }

      // If we haven't found a call yet, test the instruction
      // and mark it if it is a call instruction.
      if (!calls && isa<CallInst>(I)) {
        listCalls.insert(BB);
        calls = true;
      }
    }
  }
}