当前位置: 首页>>代码示例>>C++>>正文


C++ BasicBlock::getContext方法代码示例

本文整理汇总了C++中BasicBlock::getContext方法的典型用法代码示例。如果您正苦于以下问题:C++ BasicBlock::getContext方法的具体用法?C++ BasicBlock::getContext怎么用?C++ BasicBlock::getContext使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在BasicBlock的用法示例。


在下文中一共展示了BasicBlock::getContext方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: doJumpTableViaSwitch

void doJumpTableViaSwitch(
        NativeModulePtr natM, 
        BasicBlock *& block, 
        InstPtr ip, 
        MCInst &inst)
{

    llvm::dbgs() << __FUNCTION__ << ": Doing jumpt table via switch\n";
    Function *F = block->getParent();
    Module *M = F->getParent();
    // we know this conforms to
    // jmp [reg*4+displacement]

    // sanity check
    const MCOperand& scale = OP(1);
    const MCOperand& index = OP(2);

    TASSERT(index.isReg(), "Conformant jump tables need index to be a register");
    TASSERT(scale.isImm() && scale.getImm() == 4, "Conformant jump tables have scale == 4");

    MCSJumpTablePtr jmpptr = ip->get_jump_table();

    // to ensure no negative entries
    Value *adjustment = CONST_V<32>(block, jmpptr->getInitialEntry());
    Value *reg_val = R_READ<32>(block, index.getReg());
    Value *real_index = 
        BinaryOperator::Create(Instruction::Add, adjustment, reg_val, "", block);
   
    // create a default block that just traps
    BasicBlock *defaultBlock = 
        BasicBlock::Create(block->getContext(), "", block->getParent(), 0);
    Function *trapFn = Intrinsic::getDeclaration(M, Intrinsic::trap);
    CallInst::Create(trapFn, "", defaultBlock);
    ReturnInst::Create(defaultBlock->getContext(), defaultBlock);
    // end default block

    const std::vector<VA> &jmpblocks = jmpptr->getJumpTable();

    // create a switch inst
    SwitchInst *theSwitch = SwitchInst::Create(
            real_index, 
            defaultBlock,
            jmpblocks.size(),
            block);

    // populate switch
    int myindex = 0;
    for(std::vector<VA>::const_iterator itr = jmpblocks.begin();
        itr != jmpblocks.end();
        itr++) 
    {
        std::string  bbname = "block_0x"+to_string<VA>(*itr, std::hex);
        BasicBlock *toBlock = bbFromStrName(bbname, F);
        TASSERT(toBlock != NULL, "Could not find block: "+bbname);
        theSwitch->addCase(CONST_V<32>(block, myindex), toBlock);
        ++myindex;
    }

}
开发者ID:IDA-RE-things,项目名称:mcsema,代码行数:59,代码来源:JumpTables.cpp

示例2: optimizeSQRT

static bool optimizeSQRT(CallInst *Call, Function *CalledFunc,
                         BasicBlock &CurrBB, Function::iterator &BB,
                         const TargetTransformInfo *TTI) {
  // There is no need to change the IR, since backend will emit sqrt
  // instruction if the call has already been marked read-only.
  if (Call->onlyReadsMemory())
    return false;

  if (!DebugCounter::shouldExecute(PILCounter))
    return false;

  // Do the following transformation:
  //
  // (before)
  // dst = sqrt(src)
  //
  // (after)
  // v0 = sqrt_noreadmem(src) # native sqrt instruction.
  // [if (v0 is a NaN) || if (src < 0)]
  //   v1 = sqrt(src)         # library call.
  // dst = phi(v0, v1)
  //

  // Move all instructions following Call to newly created block JoinBB.
  // Create phi and replace all uses.
  BasicBlock *JoinBB = llvm::SplitBlock(&CurrBB, Call->getNextNode());
  IRBuilder<> Builder(JoinBB, JoinBB->begin());
  Type *Ty = Call->getType();
  PHINode *Phi = Builder.CreatePHI(Ty, 2);
  Call->replaceAllUsesWith(Phi);

  // Create basic block LibCallBB and insert a call to library function sqrt.
  BasicBlock *LibCallBB = BasicBlock::Create(CurrBB.getContext(), "call.sqrt",
                                             CurrBB.getParent(), JoinBB);
  Builder.SetInsertPoint(LibCallBB);
  Instruction *LibCall = Call->clone();
  Builder.Insert(LibCall);
  Builder.CreateBr(JoinBB);

  // Add attribute "readnone" so that backend can use a native sqrt instruction
  // for this call. Insert a FP compare instruction and a conditional branch
  // at the end of CurrBB.
  Call->addAttribute(AttributeList::FunctionIndex, Attribute::ReadNone);
  CurrBB.getTerminator()->eraseFromParent();
  Builder.SetInsertPoint(&CurrBB);
  Value *FCmp = TTI->isFCmpOrdCheaperThanFCmpZero(Ty)
                    ? Builder.CreateFCmpORD(Call, Call)
                    : Builder.CreateFCmpOGE(Call->getOperand(0),
                                            ConstantFP::get(Ty, 0.0));
  Builder.CreateCondBr(FCmp, JoinBB, LibCallBB);

  // Add phi operands.
  Phi->addIncoming(Call, &CurrBB);
  Phi->addIncoming(LibCall, LibCallBB);

  BB = JoinBB->getIterator();
  return true;
}
开发者ID:FreeBSDFoundation,项目名称:freebsd,代码行数:58,代码来源:PartiallyInlineLibCalls.cpp

示例3: IsTrivialUnswitchCondition

/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
/// trivial: that is, that the condition controls whether or not the loop does
/// anything at all.  If this is a trivial condition, unswitching produces no
/// code duplications (equivalently, it produces a simpler loop and a new empty
/// loop, which gets deleted).
///
/// If this is a trivial condition, return true, otherwise return false.  When
/// returning true, this sets Cond and Val to the condition that controls the
/// trivial condition: when Cond dynamically equals Val, the loop is known to
/// exit.  Finally, this sets LoopExit to the BB that the loop exits to when
/// Cond == Val.
///
bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
                                       BasicBlock **LoopExit) {
  BasicBlock *Header = currentLoop->getHeader();
  TerminatorInst *HeaderTerm = Header->getTerminator();
  LLVMContext &Context = Header->getContext();
  
  BasicBlock *LoopExitBB = 0;
  if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
    // If the header block doesn't end with a conditional branch on Cond, we
    // can't handle it.
    if (!BI->isConditional() || BI->getCondition() != Cond)
      return false;
  
    // Check to see if a successor of the branch is guaranteed to 
    // exit through a unique exit block without having any 
    // side-effects.  If so, determine the value of Cond that causes it to do
    // this.
    if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop, 
                                             BI->getSuccessor(0)))) {
      if (Val) *Val = ConstantInt::getTrue(Context);
    } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop, 
                                                    BI->getSuccessor(1)))) {
      if (Val) *Val = ConstantInt::getFalse(Context);
    }
  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
    // If this isn't a switch on Cond, we can't handle it.
    if (SI->getCondition() != Cond) return false;
    
    // Check to see if a successor of the switch is guaranteed to go to the
    // latch block or exit through a one exit block without having any 
    // side-effects.  If so, determine the value of Cond that causes it to do
    // this.  Note that we can't trivially unswitch on the default case.
    for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
      if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop, 
                                               SI->getSuccessor(i)))) {
        // Okay, we found a trivial case, remember the value that is trivial.
        if (Val) *Val = SI->getCaseValue(i);
        break;
      }
  }

  // If we didn't find a single unique LoopExit block, or if the loop exit block
  // contains phi nodes, this isn't trivial.
  if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
    return false;   // Can't handle this.
  
  if (LoopExit) *LoopExit = LoopExitBB;
  
  // We already know that nothing uses any scalar values defined inside of this
  // loop.  As such, we just have to check to see if this loop will execute any
  // side-effecting instructions (e.g. stores, calls, volatile loads) in the
  // part of the loop that the code *would* execute.  We already checked the
  // tail, check the header now.
  for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
    if (I->mayHaveSideEffects())
      return false;
  return true;
}
开发者ID:5432935,项目名称:crossbridge,代码行数:70,代码来源:LoopUnswitch.cpp

示例4: instrumentBasicBlock

void GEOSProfiler::instrumentBasicBlock(BasicBlock  &BB, Module &M, int ID) {
  IRBuilder<> Builder(BB.getContext());

  auto ConstantId = ConstantInt::get(Builder.getInt32Ty(), ID);
  CallInst *CountCall = Builder.CreateCall(
      M.getFunction("count"), ConstantId);

  CountCall->insertBefore(BB.getFirstNonPHI());
}
开发者ID:vandersonmr,项目名称:GEOS,代码行数:9,代码来源:GEOSProf.cpp

示例5: inlineReportOrSilenceIfMissed

void AliasCheckerInliner::inlineReportOrSilenceIfMissed(CallInst *CI) {
  BasicBlock *BB = CI->getParent();
  CallSite CS(CI);
  Value *P = CS.getArgument(0), *Q = CS.getArgument(2);
  Value *VIDOfP = CS.getArgument(1), *VIDOfQ = CS.getArgument(3);
  // BB:
  //   xxx
  //   call ReportIfMissed(P, VID(P), Q, VID(Q))
  //   yyy
  //
  // =>
  //
  // BB:
  //   xxx
  //   br NewBB
  // NewBB:
  //   call ReportIfMissed(P, VID(P), Q, VID(Q))
  //   yyy
  //
  // =>
  //
  // BB:
  //   xxx
  //   C1 = icmp eq P, Q
  //   C2 = icmp ne P, null
  //   C3 = and C1, C2
  //   br C3, ReportBB, NewBB
  // NewBB:
  //   yyy
  // ReportBB:
  //   ReportMissingAlias(VIDOfP, VIDOfQ, P)
  //   br NewBB

  // Create NewBB.
  BasicBlock *NewBB = BB->splitBasicBlock(CI, "bb");
  // Create ReportBB.
  BasicBlock *ReportBB = BasicBlock::Create(BB->getContext(),
                                            "report",
                                            BB->getParent());
  vector<Value *> Args;
  Args.push_back(VIDOfP);
  Args.push_back(VIDOfQ);
  Args.push_back(P);
  if (CI->getCalledFunction() == ReportIfMissed)
    CallInst::Create(ReportMissingAlias, Args, "", ReportBB);
  else if (CI->getCalledFunction() == SilenceIfMissed)
    CallInst::Create(SilenceMissingAlias, Args, "", ReportBB);
  else
    assert(false);
  BranchInst::Create(NewBB, ReportBB);
  // Update BB.
  insertBranchTo(BB, ReportBB, NewBB, P, Q);
  CI->eraseFromParent();
}
开发者ID:alias-checker,项目名称:dyn-aa,代码行数:54,代码来源:AliasCheckerInliner.cpp

示例6: pushLoop

void ScopAnnotator::pushLoop(Loop *L, bool IsParallel) {

  ActiveLoops.push_back(L);
  if (!IsParallel)
    return;

  BasicBlock *Header = L->getHeader();
  MDNode *Id = getID(Header->getContext());
  assert(Id->getOperand(0) == Id && "Expected Id to be a self-reference");
  assert(Id->getNumOperands() == 1 && "Unexpected extra operands in Id");
  MDNode *Ids = ParallelLoops.empty()
                    ? Id
                    : MDNode::concatenate(ParallelLoops.back(), Id);
  ParallelLoops.push_back(Ids);
}
开发者ID:jeremyhu,项目名称:polly,代码行数:15,代码来源:IRBuilder.cpp

示例7: runOnBasicBlock

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;
}
开发者ID:Maher4Ever,项目名称:emscripten-fastcomp,代码行数:15,代码来源:ExpandGetElementPtr.cpp

示例8: SplitBlockAndInsertIfThenElse

/// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
/// but also creates the ElseBlock.
/// Before:
///   Head
///   SplitBefore
///   Tail
/// After:
///   Head
///   if (Cond)
///     ThenBlock
///   else
///     ElseBlock
///   SplitBefore
///   Tail
void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
                                         TerminatorInst **ThenTerm,
                                         TerminatorInst **ElseTerm,
                                         MDNode *BranchWeights) {
  BasicBlock *Head = SplitBefore->getParent();
  BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
  TerminatorInst *HeadOldTerm = Head->getTerminator();
  LLVMContext &C = Head->getContext();
  BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
  BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
  *ThenTerm = BranchInst::Create(Tail, ThenBlock);
  *ElseTerm = BranchInst::Create(Tail, ElseBlock);
  BranchInst *HeadNewTerm =
    BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
  HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
  ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
}
开发者ID:eaglexmw,项目名称:llvm,代码行数:31,代码来源:BasicBlockUtils.cpp

示例9: UnreachableInst

TerminatorInst *llvm::SplitBlockAndInsertIfThen(Instruction *Cmp,
    bool Unreachable, MDNode *BranchWeights) {
  Instruction *SplitBefore = Cmp->getNextNode();
  BasicBlock *Head = SplitBefore->getParent();
  BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
  TerminatorInst *HeadOldTerm = Head->getTerminator();
  LLVMContext &C = Head->getContext();
  BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
  TerminatorInst *CheckTerm;
  if (Unreachable)
    CheckTerm = new UnreachableInst(C, ThenBlock);
  else
    CheckTerm = BranchInst::Create(Tail, ThenBlock);
  BranchInst *HeadNewTerm =
    BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cmp);
  HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
  ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
  return CheckTerm;
}
开发者ID:ChiahungTai,项目名称:llvm,代码行数:19,代码来源:BasicBlockUtils.cpp

示例10: instrumentMemoryAllocation

void MemoryInstrumenter::instrumentMemoryAllocation(Value *Start,
                                                    Value *Size,
                                                    Value *Success,
                                                    Instruction *Loc) {
  IDAssigner &IDA = getAnalysis<IDAssigner>();

  assert(Start->getType()->isPointerTy());
  assert(Size);
  // The size argument to HookMemAlloc must be long.
  assert(Size->getType() == LongType);
  assert(Success == NULL || Success->getType()->isIntegerTy(1));
  assert(Loc);

  vector<Value *> Args;
  // Arg 1: value ID
  Args.push_back(ConstantInt::get(IntType, IDA.getValueID(Start)));
  // Arg 2: starting address
  if (Start->getType() != CharStarType) {
    Start = new BitCastInst(Start, CharStarType, "", Loc);
  }
  Args.push_back(Start);
  // Arg 3: bound
  Args.push_back(Size);

  // If the allocation is always successful, such as new, we create the
  // memory allocation hook directly; otherwise, we need to check the condition
  // and add the memory allocation hook.
  if (Success == NULL) {
    CallInst::Create(MemAllocHook, Args, "", Loc);
  } else {
    BasicBlock *BB = Loc->getParent();
    BasicBlock *RestBB = BB->splitBasicBlock(Loc, "rest");
    BasicBlock *CallMallocHookBB = BasicBlock::Create(BB->getContext(),
                                                      "call_malloc_hook",
                                                      BB->getParent(),
                                                      RestBB);
    BB->getTerminator()->eraseFromParent();
    BranchInst::Create(CallMallocHookBB, RestBB, Success, BB);
    CallInst::Create(MemAllocHook, Args, "", CallMallocHookBB);
    BranchInst::Create(RestBB, CallMallocHookBB);
  }
}
开发者ID:alias-checker,项目名称:dyn-aa,代码行数:42,代码来源:MemoryInstrumenter.cpp

示例11: UnreachableInst

TerminatorInst *
llvm::SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
                                bool Unreachable, MDNode *BranchWeights,
                                DominatorTree *DT, LoopInfo *LI) {
  BasicBlock *Head = SplitBefore->getParent();
  BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
  TerminatorInst *HeadOldTerm = Head->getTerminator();
  LLVMContext &C = Head->getContext();
  BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
  TerminatorInst *CheckTerm;
  if (Unreachable)
    CheckTerm = new UnreachableInst(C, ThenBlock);
  else
    CheckTerm = BranchInst::Create(Tail, ThenBlock);
  CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
  BranchInst *HeadNewTerm =
    BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
  HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
  ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);

  if (DT) {
    if (DomTreeNode *OldNode = DT->getNode(Head)) {
      std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());

      DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
      for (DomTreeNode *Child : Children)
        DT->changeImmediateDominator(Child, NewNode);

      // Head dominates ThenBlock.
      DT->addNewBlock(ThenBlock, Head);
    }
  }

  if (LI) {
    if (Loop *L = LI->getLoopFor(Head)) {
      L->addBasicBlockToLoop(ThenBlock, *LI);
      L->addBasicBlockToLoop(Tail, *LI);
    }
  }

  return CheckTerm;
}
开发者ID:BNieuwenhuizen,项目名称:llvm,代码行数:42,代码来源:BasicBlockUtils.cpp

示例12: handleLoops

void StructurizeCFG::handleLoops(bool ExitUseAllowed,
                                 BasicBlock *LoopEnd) {
  RegionNode *Node = Order.front();
  BasicBlock *LoopStart = Node->getEntry();

  if (!Loops.count(LoopStart)) {
    wireFlow(ExitUseAllowed, LoopEnd);
    return;
  }

  if (!isPredictableTrue(Node))
    LoopStart = needPrefix(true);

  LoopEnd = Loops[Node->getEntry()];
  wireFlow(false, LoopEnd);
  while (!Visited.count(LoopEnd)) {
    handleLoops(false, LoopEnd);
  }

  // If the start of the loop is the entry block, we can't branch to it so
  // insert a new dummy entry block.
  Function *LoopFunc = LoopStart->getParent();
  if (LoopStart == &LoopFunc->getEntryBlock()) {
    LoopStart->setName("entry.orig");

    BasicBlock *NewEntry =
      BasicBlock::Create(LoopStart->getContext(),
                         "entry",
                         LoopFunc,
                         LoopStart);
    BranchInst::Create(LoopStart, NewEntry);
    DT->setNewRoot(NewEntry);
  }

  // Create an extra loop end node
  LoopEnd = needPrefix(false);
  BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
  LoopConds.push_back(BranchInst::Create(Next, LoopStart,
                                         BoolUndef, LoopEnd));
  addPhiValues(LoopEnd, LoopStart);
  setPrevNode(Next);
}
开发者ID:BNieuwenhuizen,项目名称:llvm,代码行数:42,代码来源:StructurizeCFG.cpp

示例13:

//semantics of the RTL aullshr intrinsic stub
Value *replace_aullshr(Module *M, Instruction *I, Pass *P) {

  BasicBlock *topHalf = I->getParent();
  
  BasicBlock *bottomHalf = llvm::SplitBlock(topHalf, I, P);

  BasicBlock *newBlock = BasicBlock::Create(
          topHalf->getContext(), 
          "aullshr_MainBlock",
          topHalf->getParent());

  // remove old branch, and create a new branch to newBlock
  topHalf->getTerminator()->eraseFromParent();
  BranchInst::Create(newBlock, topHalf);


  // emit aullshr and link that block to bottomHalf
  Value *new_v = emit_aullshr(newBlock, bottomHalf);


  return new_v;
}
开发者ID:0xDEC0DE8,项目名称:mcsema,代码行数:23,代码来源:inlineSpecials.cpp

示例14: UnrollRuntimeLoopProlog


//.........这里部分代码省略.........
  BranchInst *PreHeaderBR = cast<BranchInst>(PH->getTerminator());

  // Compute the number of extra iterations required, which is:
  //  extra iterations = run-time trip count % (loop unroll factor + 1)
  SCEVExpander Expander(*SE, "loop-unroll");
  Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
                                            PreHeaderBR);
  Type *CountTy = TripCount->getType();
  BinaryOperator *ModVal =
    BinaryOperator::CreateURem(TripCount,
                               ConstantInt::get(CountTy, Count),
                               "xtraiter");
  ModVal->insertBefore(PreHeaderBR);

  // Check if for no extra iterations, then jump to unrolled loop
  Value *BranchVal = new ICmpInst(PreHeaderBR,
                                  ICmpInst::ICMP_NE, ModVal,
                                  ConstantInt::get(CountTy, 0), "lcmp");
  // Branch to either the extra iterations or the unrolled loop
  // We will fix up the true branch label when adding loop body copies
  BranchInst::Create(PEnd, PEnd, BranchVal, PreHeaderBR);
  assert(PreHeaderBR->isUnconditional() &&
         PreHeaderBR->getSuccessor(0) == PEnd &&
         "CFG edges in Preheader are not correct");
  PreHeaderBR->eraseFromParent();

  ValueToValueMapTy LVMap;
  Function *F = Header->getParent();
  // These variables are used to update the CFG links in each iteration
  BasicBlock *CompareBB = nullptr;
  BasicBlock *LastLoopBB = PH;
  // Get an ordered list of blocks in the loop to help with the ordering of the
  // cloned blocks in the prolog code
  LoopBlocksDFS LoopBlocks(L);
  LoopBlocks.perform(LI);

  //
  // For each extra loop iteration, create a copy of the loop's basic blocks
  // and generate a condition that branches to the copy depending on the
  // number of 'left over' iterations.
  //
  for (unsigned leftOverIters = Count-1; leftOverIters > 0; --leftOverIters) {
    std::vector<BasicBlock*> NewBlocks;
    ValueToValueMapTy VMap;

    // Clone all the basic blocks in the loop, but we don't clone the loop
    // This function adds the appropriate CFG connections.
    CloneLoopBlocks(L, (leftOverIters == Count-1), LastLoopBB, PEnd, NewBlocks,
                    LoopBlocks, VMap, LVMap, LI);
    LastLoopBB = cast<BasicBlock>(VMap[Latch]);

    // Insert the cloned blocks into function just before the original loop
    F->getBasicBlockList().splice(PEnd, F->getBasicBlockList(),
                                  NewBlocks[0], F->end());

    // Generate the code for the comparison which determines if the loop
    // prolog code needs to be executed.
    if (leftOverIters == Count-1) {
      // There is no compare block for the fall-thru case when for the last
      // left over iteration
      CompareBB = NewBlocks[0];
    } else {
      // Create a new block for the comparison
      BasicBlock *NewBB = BasicBlock::Create(CompareBB->getContext(), "unr.cmp",
                                             F, CompareBB);
      if (Loop *ParentLoop = L->getParentLoop()) {
        // Add the new block to the parent loop, if needed
        ParentLoop->addBasicBlockToLoop(NewBB, LI->getBase());
      }

      // The comparison w/ the extra iteration value and branch
      Value *BranchVal = new ICmpInst(*NewBB, ICmpInst::ICMP_EQ, ModVal,
                                      ConstantInt::get(CountTy, leftOverIters),
                                      "un.tmp");
      // Branch to either the extra iterations or the unrolled loop
      BranchInst::Create(NewBlocks[0], CompareBB,
                         BranchVal, NewBB);
      CompareBB = NewBB;
      PH->getTerminator()->setSuccessor(0, NewBB);
      VMap[NewPH] = CompareBB;
    }

    // Rewrite the cloned instruction operands to use the values
    // created when the clone is created.
    for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
      for (BasicBlock::iterator I = NewBlocks[i]->begin(),
             E = NewBlocks[i]->end(); I != E; ++I) {
        RemapInstruction(I, VMap,
                         RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
      }
    }
  }

  // Connect the prolog code to the original loop and update the
  // PHI functions.
  ConnectProlog(L, TripCount, Count, LastLoopBB, PEnd, PH, NewPH, LVMap,
                LPM->getAsPass());
  NumRuntimeUnrolled++;
  return true;
}
开发者ID:compnerd,项目名称:llvm,代码行数:101,代码来源:LoopUnrollRuntime.cpp

示例15: Twine

/*
  in addition to the original condition of the loop, insert one cond
  on the virtual iterator, given the linf and lsup bounds for the chunk
  this cond exits and returns to the decision block to start a new chunk
*/
BasicBlock *insertChunkCond(Loop *&L, LoopInfo *LI, Value *vi, Value *lsup,
                            BasicBlock *dcb, Value *vi_dcb_val,
                            PHINode *&phi_vi) {

  BasicBlock *H = L->getHeader();

  BasicBlock *newCond = BasicBlock::Create(
      H->getContext(), Twine("__kernel__" + H->getName().str() + "_viCond"),
      H->getParent(), H);

  std::vector<BasicBlock *> Lblocks = L->getBlocks();

  BasicBlock *exitBlock = BasicBlock::Create(
      H->getContext(), Twine(H->getName().str() + "_exitChunk"), H->getParent(),
      H);
  BranchInst::Create(dcb, exitBlock);

  phi_vi = PHINode::Create(Type::getInt64Ty(H->getContext()), 2, "vi_value",
                           newCond);
  phi_vi->addIncoming(vi_dcb_val, dcb);

  LoadInst *load_lsup = new LoadInst(lsup, "lsup_value", newCond);

  ICmpInst *cmp = new ICmpInst(*newCond, ICmpInst::ICMP_SLT, phi_vi, load_lsup,
                               vi->getName() + "_cmp");

  // Make sure all predecessors now go to our new condition
  std::vector<TerminatorInst *> termInstrs;
  BasicBlock *lp = L->getLoopPredecessor();

  for (auto it = pred_begin(H), end = pred_end(H); it != end; ++it) {
    if ((*it) == lp) {
      // Original entry should be redirected to dcb
      TerminatorInst *tinstr = (*it)->getTerminator();
      for (auto it = tinstr->op_begin(), end = tinstr->op_end(); it != end;
           ++it) {
        Use *use = &*it;
        if (use->get() == H) {
          use->set(dcb);
        }
      }
    } else {
      termInstrs.push_back((*it)->getTerminator());
    }
  }

  for (auto &tinstr : termInstrs) {
    for (auto it = tinstr->op_begin(), end = tinstr->op_end(); it != end;
         ++it) {
      Use *use = &*it;
      if (use->get() == H) {
        use->set(newCond);
      }
    }
  }

  BranchInst::Create(H, exitBlock, cmp, newCond);

  // update loop info
  if (L != LI->getLoopFor(newCond)) {
    L->addBasicBlockToLoop(newCond, *LI);
  }

  L->moveToHeader(newCond);

  Loop *Lp = L->getParentLoop();
  if (Lp)
    Lp->addBasicBlockToLoop(exitBlock, *LI);
  return newCond;
}
开发者ID:davidklaftenegger,项目名称:daedal,代码行数:75,代码来源:HandleVirtualIterators.cpp


注:本文中的BasicBlock::getContext方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。