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


C++ PHINode类代码示例

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


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

示例1: DEBUG


//.........这里部分代码省略.........
  // For unroll factor 2 remainder loop will have 1 iterations.
  // Do not create 1 iteration loop.
  bool CreateRemainderLoop = (Count != 2);

  // Clone all the basic blocks in the loop. If Count is 2, we don't clone
  // the loop, otherwise we create a cloned loop to execute the extra
  // iterations. This function adds the appropriate CFG connections.
  BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit;
  BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
  Loop *remainderLoop = CloneLoopBlocks(
      L, ModVal, CreateRemainderLoop, UseEpilogRemainder, UnrollRemainder,
      InsertTop, InsertBot,
      NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI);

  // Insert the cloned blocks into the function.
  F->getBasicBlockList().splice(InsertBot->getIterator(),
                                F->getBasicBlockList(),
                                NewBlocks[0]->getIterator(),
                                F->end());

  // Now the loop blocks are cloned and the other exiting blocks from the
  // remainder are connected to the original Loop's exit blocks. The remaining
  // work is to update the phi nodes in the original loop, and take in the
  // values from the cloned region. Also update the dominator info for
  // OtherExits and their immediate successors, since we have new edges into
  // OtherExits.
  SmallSet<BasicBlock*, 8> ImmediateSuccessorsOfExitBlocks;
  for (auto *BB : OtherExits) {
   for (auto &II : *BB) {

     // Given we preserve LCSSA form, we know that the values used outside the
     // loop will be used through these phi nodes at the exit blocks that are
     // transformed below.
     if (!isa<PHINode>(II))
       break;
     PHINode *Phi = cast<PHINode>(&II);
     unsigned oldNumOperands = Phi->getNumIncomingValues();
     // Add the incoming values from the remainder code to the end of the phi
     // node.
     for (unsigned i =0; i < oldNumOperands; i++){
       Value *newVal = VMap[Phi->getIncomingValue(i)];
       // newVal can be a constant or derived from values outside the loop, and
       // hence need not have a VMap value.
       if (!newVal)
         newVal = Phi->getIncomingValue(i);
       Phi->addIncoming(newVal,
                           cast<BasicBlock>(VMap[Phi->getIncomingBlock(i)]));
     }
   }
#if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
    for (BasicBlock *SuccBB : successors(BB)) {
      assert(!(any_of(OtherExits,
                      [SuccBB](BasicBlock *EB) { return EB == SuccBB; }) ||
               SuccBB == LatchExit) &&
             "Breaks the definition of dedicated exits!");
    }
#endif
   // Update the dominator info because the immediate dominator is no longer the
   // header of the original Loop. BB has edges both from L and remainder code.
   // Since the preheader determines which loop is run (L or directly jump to
   // the remainder code), we set the immediate dominator as the preheader.
   if (DT) {
     DT->changeImmediateDominator(BB, PreHeader);
     // Also update the IDom for immediate successors of BB.  If the current
     // IDom is the header, update the IDom to be the preheader because that is
     // the nearest common dominator of all predecessors of SuccBB.  We need to
开发者ID:JaredCJR,项目名称:llvm,代码行数:67,代码来源:LoopUnrollRuntime.cpp

示例2: while

/// optimizeCheck - replace the given check CallInst with the check's fast
/// version if all the source memory objects can be found and it is obvious
/// that none of them have been freed at the point where the check is made.
/// Returns the new call if possible and NULL otherwise.
///
/// This currently works only with memory objects that can't be freed:
/// * global variables
/// * allocas that trivially have function scope
/// * byval arguments
///
bool ExactCheckOpt::optimizeCheck(CallInst *CI, CheckInfoType *Info) {
  // Examined values
  SmallSet<Value*, 16> Visited;
  // Potential memory objects
  SmallSet<Value*, 4> Objects;

  std::queue<Value*> Q;
  // Start from the the pointer operand
  Value *StartPtr = CI->getArgOperand(Info->PtrArgNo)->stripPointerCasts();
  Q.push(StartPtr);

  // Use BFS to find all potential memory objects
  while(!Q.empty()) {
    Value *o = Q.front()->stripPointerCasts();
    Q.pop();
    if(Visited.count(o))
      continue;
    Visited.insert(o);

    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(o)) {
      if (CE->getOpcode() == Instruction::GetElementPtr) {
        Q.push(CE->getOperand(0));
      } else {
        // Exit early if any of the objects are unsupported.
        if (!isSimpleMemoryObject(o))
          return false;
        Objects.insert(o);
      }
    } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(o)) {
      Q.push(GEP->getPointerOperand());
      // It is fine to ignore the case of indexing into null with a pointer
      // because that case is invalid for LLVM-aware objects such as allocas,
      // globals, and objects pointed to by noalias pointers.
    } else if(PHINode *PHI = dyn_cast<PHINode>(o)) {
      for (unsigned i = 0, num = PHI->getNumIncomingValues(); i != num; ++i)
        Q.push(PHI->getIncomingValue(i));
    } else if (SelectInst *SI = dyn_cast<SelectInst>(o)) {
      Q.push(SI->getTrueValue());
      Q.push(SI->getFalseValue());
    } else {
      // Exit early if any of the objects are unsupported.
      if (!isSimpleMemoryObject(o))
        return false;
      Objects.insert(o);
    }
  }

  // Mapping from the initial value to the corresponding size and void pointer:
  // * memory object -> its size and pointer
  // * phi/select -> corresponding phi/select for the sizes and pointers
  // * anything else -> the corresponding size and pointer on the path
  std::map <Value*, PtrSizePair> M;

  Module &Mod = *CI->getParent()->getParent()->getParent();
  Type *SizeTy = getSizeType(Info, Mod);

  // Add non-instruction non-constant allocation object pointers to the front
  // of the function's entry block.
  BasicBlock &EntryBlock = CI->getParent()->getParent()->getEntryBlock();
  Instruction *FirstInsertionPoint = ++BasicBlock::iterator(EntryBlock.begin());

  for (SmallSet<Value*, 16>::const_iterator It = Objects.begin(),
       E = Objects.end();
       It != E;
       ++It) {
    // Obj is a memory object pointer: alloca, argument, load, callinst, etc.
    Value *Obj = *It;

    // Insert instruction-based allocation pointers just after the allocation.
    Instruction *InsertBefore = FirstInsertionPoint;
    if (Instruction *I = dyn_cast<Instruction>(Obj))
      InsertBefore = ++BasicBlock::iterator(I);
    IRBuilder<> Builder(InsertBefore);

    SizeOffsetEvalType SizeOffset = ObjSizeEval->compute(Obj);
    assert(ObjSizeEval->bothKnown(SizeOffset));
    assert(dyn_cast<ConstantInt>(SizeOffset.second)->isZero());
    Value *Size = Builder.CreateIntCast(SizeOffset.first, SizeTy,
                                        /*isSigned=*/false);

    Value *Ptr = Builder.CreatePointerCast(Obj, VoidPtrTy);
    M[Obj] = std::make_pair(Ptr, Size);
  }

  // Create the rest of the size values and object pointers.
  // The phi nodes will be finished later.
  for (SmallSet<Value*, 16>::const_iterator I = Visited.begin(),
       E = Visited.end();
       I != E;
       ++I) {
//.........这里部分代码省略.........
开发者ID:otinn,项目名称:safecode,代码行数:101,代码来源:ExactCheckOpt.cpp

示例3: SplitBlock

void GNUstep::IMPCacher::CacheLookup(Instruction *lookup, Value *slot, Value
                                     *version, bool isSuperMessage) {

    // If this IMP is already cached, don't cache it again.
    if (lookup->getMetadata(IMPCacheFlagKind)) {
        return;
    }

    lookup->setMetadata(IMPCacheFlagKind, AlreadyCachedFlag);
    bool isInvoke = false;

    BasicBlock *beforeLookupBB = lookup->getParent();
    BasicBlock *lookupBB = SplitBlock(beforeLookupBB, lookup, Owner);
    BasicBlock *lookupFinishedBB = lookupBB;
    BasicBlock *afterLookupBB;

    if (InvokeInst *inv = dyn_cast<InvokeInst>(lookup)) {
        afterLookupBB = inv->getNormalDest();
        lookupFinishedBB =
            BasicBlock::Create(Context, "done_lookup", lookupBB->getParent());
        CGBuilder B(lookupFinishedBB);
        B.CreateBr(afterLookupBB);
        inv->setNormalDest(lookupFinishedBB);
        isInvoke = true;
    } else {
        BasicBlock::iterator iter = lookup;
        iter++;
        afterLookupBB = SplitBlock(iter->getParent(), iter, Owner);
    }

    removeTerminator(beforeLookupBB);

    CGBuilder B = CGBuilder(beforeLookupBB);
    // Load the slot and check that neither it nor the version is 0.
    Value *versionValue = B.CreateLoad(version);
    Value *receiverPtr = lookup->getOperand(0);
    Value *receiver = receiverPtr;
    if (!isSuperMessage) {
        receiver = B.CreateLoad(receiverPtr);
    }
    // For small objects, we skip the cache entirely.
    // FIXME: Class messages are never to small objects...
    bool is64Bit = llvm::Module::Pointer64 ==
                   B.GetInsertBlock()->getParent()->getParent()->getPointerSize();
    LLVMType *intPtrTy = is64Bit ? Type::getInt64Ty(Context) :
                         Type::getInt32Ty(Context);

    // Receiver as an integer
    Value *receiverSmallObject = B.CreatePtrToInt(receiver, intPtrTy);
    // Receiver is a small object...
    receiverSmallObject =
        B.CreateAnd(receiverSmallObject, is64Bit ? 7 : 1);
    // Receiver is not a small object.
    receiverSmallObject =
        B.CreateICmpNE(receiverSmallObject, Constant::getNullValue(intPtrTy));
    // Ideally, we'd call objc_msgSend() here, but for now just skip the cache
    // lookup

    Value *isCacheEmpty =
        B.CreateICmpEQ(versionValue, Constant::getNullValue(IntTy));
    Value *receiverNil =
        B.CreateICmpEQ(receiver, Constant::getNullValue(receiver->getType()));

    isCacheEmpty = B.CreateOr(isCacheEmpty, receiverNil);
    isCacheEmpty = B.CreateOr(isCacheEmpty, receiverSmallObject);

    BasicBlock *cacheLookupBB = BasicBlock::Create(Context, "cache_check",
                                lookupBB->getParent());

    B.CreateCondBr(isCacheEmpty, lookupBB, cacheLookupBB);

    // Check the cache node is current
    B.SetInsertPoint(cacheLookupBB);
    Value *slotValue = B.CreateLoad(slot, "slot_value");
    Value *slotVersion = B.CreateStructGEP(slotValue, 3);
    // Note: Volatile load because the slot version might have changed in
    // another thread.
    slotVersion = B.CreateLoad(slotVersion, true, "slot_version");
    Value *slotCachedFor = B.CreateStructGEP(slotValue, 1);
    slotCachedFor = B.CreateLoad(slotCachedFor, true, "slot_owner");
    Value *cls = B.CreateLoad(B.CreateBitCast(receiver, IdTy));
    Value *isVersionCorrect = B.CreateICmpEQ(slotVersion, versionValue);
    Value *isOwnerCorrect = B.CreateICmpEQ(slotCachedFor, cls);
    Value *isSlotValid = B.CreateAnd(isVersionCorrect, isOwnerCorrect);
    // If this slot is still valid, skip the lookup.
    B.CreateCondBr(isSlotValid, afterLookupBB, lookupBB);

    // Perform the real lookup and cache the result
    removeTerminator(lookupFinishedBB);
    // Replace the looked up slot with the loaded one
    B.SetInsertPoint(afterLookupBB, afterLookupBB->begin());
    PHINode *newLookup = IRBuilderCreatePHI(&B, lookup->getType(), 3, "new_lookup");
    // Not volatile, so a redundant load elimination pass can do some phi
    // magic with this later.
    lookup->replaceAllUsesWith(newLookup);

    B.SetInsertPoint(lookupFinishedBB);
    Value * newReceiver = receiver;
    if (!isSuperMessage) {
        newReceiver = B.CreateLoad(receiverPtr);
//.........这里部分代码省略.........
开发者ID:andyvand,项目名称:darwin-sdk,代码行数:101,代码来源:IMPCacher.cpp

示例4: DEBUG

bool LoopInterchangeTransform::adjustLoopBranches() {

    DEBUG(dbgs() << "adjustLoopBranches called\n");
    // Adjust the loop preheader
    BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
    BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
    BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
    BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();
    BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader();
    BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
    BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor();
    BasicBlock *InnerLoopLatchPredecessor =
        InnerLoopLatch->getUniquePredecessor();
    BasicBlock *InnerLoopLatchSuccessor;
    BasicBlock *OuterLoopLatchSuccessor;

    BranchInst *OuterLoopLatchBI =
        dyn_cast<BranchInst>(OuterLoopLatch->getTerminator());
    BranchInst *InnerLoopLatchBI =
        dyn_cast<BranchInst>(InnerLoopLatch->getTerminator());
    BranchInst *OuterLoopHeaderBI =
        dyn_cast<BranchInst>(OuterLoopHeader->getTerminator());
    BranchInst *InnerLoopHeaderBI =
        dyn_cast<BranchInst>(InnerLoopHeader->getTerminator());

    if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor ||
            !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI ||
            !InnerLoopHeaderBI)
        return false;

    BranchInst *InnerLoopLatchPredecessorBI =
        dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator());
    BranchInst *OuterLoopPredecessorBI =
        dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator());

    if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI)
        return false;
    BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor();
    if (!InnerLoopHeaderSuccessor)
        return false;

    // Adjust Loop Preheader and headers

    unsigned NumSucc = OuterLoopPredecessorBI->getNumSuccessors();
    for (unsigned i = 0; i < NumSucc; ++i) {
        if (OuterLoopPredecessorBI->getSuccessor(i) == OuterLoopPreHeader)
            OuterLoopPredecessorBI->setSuccessor(i, InnerLoopPreHeader);
    }

    NumSucc = OuterLoopHeaderBI->getNumSuccessors();
    for (unsigned i = 0; i < NumSucc; ++i) {
        if (OuterLoopHeaderBI->getSuccessor(i) == OuterLoopLatch)
            OuterLoopHeaderBI->setSuccessor(i, LoopExit);
        else if (OuterLoopHeaderBI->getSuccessor(i) == InnerLoopPreHeader)
            OuterLoopHeaderBI->setSuccessor(i, InnerLoopHeaderSuccessor);
    }

    // Adjust reduction PHI's now that the incoming block has changed.
    updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader,
                        OuterLoopHeader);

    BranchInst::Create(OuterLoopPreHeader, InnerLoopHeaderBI);
    InnerLoopHeaderBI->eraseFromParent();

    // -------------Adjust loop latches-----------
    if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader)
        InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1);
    else
        InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0);

    NumSucc = InnerLoopLatchPredecessorBI->getNumSuccessors();
    for (unsigned i = 0; i < NumSucc; ++i) {
        if (InnerLoopLatchPredecessorBI->getSuccessor(i) == InnerLoopLatch)
            InnerLoopLatchPredecessorBI->setSuccessor(i, InnerLoopLatchSuccessor);
    }

    // Adjust PHI nodes in InnerLoopLatchSuccessor. Update all uses of PHI with
    // the value and remove this PHI node from inner loop.
    SmallVector<PHINode *, 8> LcssaVec;
    for (auto I = InnerLoopLatchSuccessor->begin(); isa<PHINode>(I); ++I) {
        PHINode *LcssaPhi = cast<PHINode>(I);
        LcssaVec.push_back(LcssaPhi);
    }
    for (auto I = LcssaVec.begin(), E = LcssaVec.end(); I != E; ++I) {
        PHINode *P = *I;
        Value *Incoming = P->getIncomingValueForBlock(InnerLoopLatch);
        P->replaceAllUsesWith(Incoming);
        P->eraseFromParent();
    }

    if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader)
        OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1);
    else
        OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0);

    if (InnerLoopLatchBI->getSuccessor(1) == InnerLoopLatchSuccessor)
        InnerLoopLatchBI->setSuccessor(1, OuterLoopLatchSuccessor);
    else
        InnerLoopLatchBI->setSuccessor(0, OuterLoopLatchSuccessor);

//.........这里部分代码省略.........
开发者ID:tauOS,项目名称:llvm,代码行数:101,代码来源:LoopInterchange.cpp

示例5: CleanupAndPrepareModules


//.........这里部分代码省略.........

      // Don't forward functions which are external in the test module too.
      if (TestFn && !TestFn->isDeclaration()) {
        // 1. Add a string constant with its name to the global file
        Constant *InitArray = ConstantArray::get(F->getContext(), F->getName());
        GlobalVariable *funcName =
          new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
                             GlobalValue::InternalLinkage, InitArray,
                             F->getName() + "_name");

        // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
        // sbyte* so it matches the signature of the resolver function.

        // GetElementPtr *funcName, ulong 0, ulong 0
        std::vector<Constant*> GEPargs(2,
                     Constant::getNullValue(Type::getInt32Ty(F->getContext())));
        Value *GEP =
                ConstantExpr::getGetElementPtr(funcName, &GEPargs[0], 2);
        std::vector<Value*> ResolverArgs;
        ResolverArgs.push_back(GEP);

        // Rewrite uses of F in global initializers, etc. to uses of a wrapper
        // function that dynamically resolves the calls to F via our JIT API
        if (!F->use_empty()) {
          // Create a new global to hold the cached function pointer.
          Constant *NullPtr = ConstantPointerNull::get(F->getType());
          GlobalVariable *Cache =
            new GlobalVariable(*F->getParent(), F->getType(), 
                               false, GlobalValue::InternalLinkage,
                               NullPtr,F->getName()+".fpcache");

          // Construct a new stub function that will re-route calls to F
          const FunctionType *FuncTy = F->getFunctionType();
          Function *FuncWrapper = Function::Create(FuncTy,
                                                   GlobalValue::InternalLinkage,
                                                   F->getName() + "_wrapper",
                                                   F->getParent());
          BasicBlock *EntryBB  = BasicBlock::Create(F->getContext(),
                                                    "entry", FuncWrapper);
          BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
                                                    "usecache", FuncWrapper);
          BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
                                                    "lookupfp", FuncWrapper);

          // Check to see if we already looked up the value.
          Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
          Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
                                       NullPtr, "isNull");
          BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);

          // Resolve the call to function F via the JIT API:
          //
          // call resolver(GetElementPtr...)
          CallInst *Resolver =
            CallInst::Create(resolverFunc, ResolverArgs.begin(),
                             ResolverArgs.end(), "resolver", LookupBB);

          // Cast the result from the resolver to correctly-typed function.
          CastInst *CastedResolver =
            new BitCastInst(Resolver,
                            PointerType::getUnqual(F->getFunctionType()),
                            "resolverCast", LookupBB);

          // Save the value in our cache.
          new StoreInst(CastedResolver, Cache, LookupBB);
          BranchInst::Create(DoCallBB, LookupBB);

          PHINode *FuncPtr = PHINode::Create(NullPtr->getType(),
                                             "fp", DoCallBB);
          FuncPtr->addIncoming(CastedResolver, LookupBB);
          FuncPtr->addIncoming(CachedVal, EntryBB);

          // Save the argument list.
          std::vector<Value*> Args;
          for (Function::arg_iterator i = FuncWrapper->arg_begin(),
                 e = FuncWrapper->arg_end(); i != e; ++i)
            Args.push_back(i);

          // Pass on the arguments to the real function, return its result
          if (F->getReturnType() == Type::getVoidTy(F->getContext())) {
            CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
            ReturnInst::Create(F->getContext(), DoCallBB);
          } else {
            CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
                                              "retval", DoCallBB);
            ReturnInst::Create(F->getContext(),Call, DoCallBB);
          }

          // Use the wrapper function instead of the old function
          F->replaceAllUsesWith(FuncWrapper);
        }
      }
    }
  }

  if (verifyModule(*Test) || verifyModule(*Safe)) {
    errs() << "Bugpoint has a bug, which corrupted a module!!\n";
    abort();
  }
}
开发者ID:Killfrra,项目名称:llvm-kernel,代码行数:101,代码来源:Miscompilation.cpp

示例6: splitLiveRangesLiveAcrossInvokes

// First thing we need to do is scan the whole function for values that are
// live across unwind edges.  Each value that is live across an unwind edge
// we spill into a stack location, guaranteeing that there is nothing live
// across the unwind edge.  This process also splits all critical edges
// coming out of invoke's.
void LowerInvoke::
splitLiveRangesLiveAcrossInvokes(SmallVectorImpl<InvokeInst*> &Invokes) {
  // First step, split all critical edges from invoke instructions.
  for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
    InvokeInst *II = Invokes[i];
    SplitCriticalEdge(II, 0, this);
    SplitCriticalEdge(II, 1, this);
    assert(!isa<PHINode>(II->getNormalDest()) &&
           !isa<PHINode>(II->getUnwindDest()) &&
           "critical edge splitting left single entry phi nodes?");
  }

  Function *F = Invokes.back()->getParent()->getParent();

  // To avoid having to handle incoming arguments specially, we lower each arg
  // to a copy instruction in the entry block.  This ensures that the argument
  // value itself cannot be live across the entry block.
  BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
  while (isa<AllocaInst>(AfterAllocaInsertPt) &&
        isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
    ++AfterAllocaInsertPt;
  for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
       AI != E; ++AI) {
    Type *Ty = AI->getType();
    // Aggregate types can't be cast, but are legal argument types, so we have
    // to handle them differently. We use an extract/insert pair as a
    // lightweight method to achieve the same goal.
    if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
      Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt);
      Instruction *NI = InsertValueInst::Create(AI, EI, 0);
      NI->insertAfter(EI);
      AI->replaceAllUsesWith(NI);
      // Set the operand of the instructions back to the AllocaInst.
      EI->setOperand(0, AI);
      NI->setOperand(0, AI);
    } else {
      // This is always a no-op cast because we're casting AI to AI->getType()
      // so src and destination types are identical. BitCast is the only
      // possibility.
      CastInst *NC = new BitCastInst(
        AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
      AI->replaceAllUsesWith(NC);
      // Set the operand of the cast instruction back to the AllocaInst.
      // Normally it's forbidden to replace a CastInst's operand because it
      // could cause the opcode to reflect an illegal conversion. However,
      // we're replacing it here with the same value it was constructed with.
      // We do this because the above replaceAllUsesWith() clobbered the
      // operand, but we want this one to remain.
      NC->setOperand(0, AI);
    }
  }

  // Finally, scan the code looking for instructions with bad live ranges.
  for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
    for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
      // Ignore obvious cases we don't have to handle.  In particular, most
      // instructions either have no uses or only have a single use inside the
      // current block.  Ignore them quickly.
      Instruction *Inst = II;
      if (Inst->use_empty()) continue;
      if (Inst->hasOneUse() &&
          cast<Instruction>(Inst->use_back())->getParent() == BB &&
          !isa<PHINode>(Inst->use_back())) continue;

      // If this is an alloca in the entry block, it's not a real register
      // value.
      if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
        if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
          continue;

      // Avoid iterator invalidation by copying users to a temporary vector.
      SmallVector<Instruction*,16> Users;
      for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
           UI != E; ++UI) {
        Instruction *User = cast<Instruction>(*UI);
        if (User->getParent() != BB || isa<PHINode>(User))
          Users.push_back(User);
      }

      // Scan all of the uses and see if the live range is live across an unwind
      // edge.  If we find a use live across an invoke edge, create an alloca
      // and spill the value.
      std::set<InvokeInst*> InvokesWithStoreInserted;

      // Find all of the blocks that this value is live in.
      std::set<BasicBlock*> LiveBBs;
      LiveBBs.insert(Inst->getParent());
      while (!Users.empty()) {
        Instruction *U = Users.back();
        Users.pop_back();

        if (!isa<PHINode>(U)) {
          MarkBlocksLiveIn(U->getParent(), LiveBBs);
        } else {
          // Uses for a PHI node occur in their predecessor block.
//.........这里部分代码省略.........
开发者ID:32bitmicro,项目名称:llvm,代码行数:101,代码来源:LowerInvoke.cpp

示例7: if

// UnifyAllExitNodes - Unify all exit nodes of the CFG by creating a new
// BasicBlock, and converting all returns to unconditional branches to this
// new basic block.  The singular exit node is returned.
//
// If there are no return stmts in the Function, a null pointer is returned.
//
bool UnifyFunctionExitNodes::runOnFunction(Function &F) {
  // Loop over all of the blocks in a function, tracking all of the blocks that
  // return.
  //
  std::vector<BasicBlock*> ReturningBlocks;
  std::vector<BasicBlock*> UnreachableBlocks;
  for(Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
    if (isa<ReturnInst>(I->getTerminator()))
      ReturningBlocks.push_back(I);
    else if (isa<UnreachableInst>(I->getTerminator()))
      UnreachableBlocks.push_back(I);

  // Then unreachable blocks.
  if (UnreachableBlocks.empty()) {
    UnreachableBlock = nullptr;
  } else if (UnreachableBlocks.size() == 1) {
    UnreachableBlock = UnreachableBlocks.front();
  } else {
    UnreachableBlock = BasicBlock::Create(F.getContext(),
                                          "UnifiedUnreachableBlock", &F);
    new UnreachableInst(F.getContext(), UnreachableBlock);

    for (std::vector<BasicBlock*>::iterator I = UnreachableBlocks.begin(),
           E = UnreachableBlocks.end(); I != E; ++I) {
      BasicBlock *BB = *I;
      BB->getInstList().pop_back();  // Remove the unreachable inst.
      BranchInst::Create(UnreachableBlock, BB);
    }
  }

  // Now handle return blocks.
  if (ReturningBlocks.empty()) {
    ReturnBlock = nullptr;
    return false;                          // No blocks return
  } else if (ReturningBlocks.size() == 1) {
    ReturnBlock = ReturningBlocks.front(); // Already has a single return block
    return false;
  }

  // Otherwise, we need to insert a new basic block into the function, add a PHI
  // nodes (if the function returns values), and convert all of the return
  // instructions into unconditional branches.
  //
  BasicBlock *NewRetBlock = BasicBlock::Create(F.getContext(),
                                               "UnifiedReturnBlock", &F);

  PHINode *PN = nullptr;
  if (F.getReturnType()->isVoidTy()) {
    ReturnInst::Create(F.getContext(), nullptr, NewRetBlock);
  } else {
    // If the function doesn't return void... add a PHI node to the block...
    PN = PHINode::Create(F.getReturnType(), ReturningBlocks.size(),
                         "UnifiedRetVal");
    NewRetBlock->getInstList().push_back(PN);
    ReturnInst::Create(F.getContext(), PN, NewRetBlock);
  }

  // Loop over all of the blocks, replacing the return instruction with an
  // unconditional branch.
  //
  for (std::vector<BasicBlock*>::iterator I = ReturningBlocks.begin(),
         E = ReturningBlocks.end(); I != E; ++I) {
    BasicBlock *BB = *I;

    // Add an incoming element to the PHI node for every return instruction that
    // is merging into this new block...
    if (PN)
      PN->addIncoming(BB->getTerminator()->getOperand(0), BB);

    BB->getInstList().pop_back();  // Remove the return insn
    BranchInst::Create(NewRetBlock, BB);
  }
  ReturnBlock = NewRetBlock;
  return true;
}
开发者ID:hsorby,项目名称:opencor,代码行数:81,代码来源:UnifyFunctionExitNodes.cpp

示例8: DEBUG

/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
/// an unconditional branch in it.
void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
  BranchInst *BI = cast<BranchInst>(BB->getTerminator());
  BasicBlock *DestBB = BI->getSuccessor(0);

  DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);

  // If the destination block has a single pred, then this is a trivial edge,
  // just collapse it.
  if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
    if (SinglePred != DestBB) {
      // Remember if SinglePred was the entry block of the function.  If so, we
      // will need to move BB back to the entry position.
      bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
      MergeBasicBlockIntoOnlyPred(DestBB, this);

      if (isEntry && BB != &BB->getParent()->getEntryBlock())
        BB->moveBefore(&BB->getParent()->getEntryBlock());
      
      DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
      return;
    }
  }

  // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
  // to handle the new incoming edges it is about to have.
  PHINode *PN;
  for (BasicBlock::iterator BBI = DestBB->begin();
       (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
    // Remove the incoming value for BB, and remember it.
    Value *InVal = PN->removeIncomingValue(BB, false);

    // Two options: either the InVal is a phi node defined in BB or it is some
    // value that dominates BB.
    PHINode *InValPhi = dyn_cast<PHINode>(InVal);
    if (InValPhi && InValPhi->getParent() == BB) {
      // Add all of the input values of the input PHI as inputs of this phi.
      for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
        PN->addIncoming(InValPhi->getIncomingValue(i),
                        InValPhi->getIncomingBlock(i));
    } else {
      // Otherwise, add one instance of the dominating value for each edge that
      // we will be adding.
      if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
        for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
          PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
      } else {
        for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
          PN->addIncoming(InVal, *PI);
      }
    }
  }

  // The PHIs are now updated, change everything that refers to BB to use
  // DestBB and remove BB.
  BB->replaceAllUsesWith(DestBB);
  if (PFI) {
    PFI->replaceAllUses(BB, DestBB);
    PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
  }
  BB->eraseFromParent();
  ++NumElim;

  DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
}
开发者ID:jyasskin,项目名称:llvm-mirror,代码行数:66,代码来源:CodeGenPrepare.cpp

示例9: CloneLoopBlocks

/// Create a clone of the blocks in a loop and connect them together.
/// If UnrollProlog is true, loop structure will not be cloned, otherwise a new
/// loop will be created including all cloned blocks, and the iterator of it
/// switches to count NewIter down to 0.
///
static void CloneLoopBlocks(Loop *L, Value *NewIter, const bool UnrollProlog,
                            BasicBlock *InsertTop, BasicBlock *InsertBot,
                            std::vector<BasicBlock *> &NewBlocks,
                            LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
                            LoopInfo *LI) {
    BasicBlock *Preheader = L->getLoopPreheader();
    BasicBlock *Header = L->getHeader();
    BasicBlock *Latch = L->getLoopLatch();
    Function *F = Header->getParent();
    LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
    LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
    Loop *NewLoop = 0;
    Loop *ParentLoop = L->getParentLoop();
    if (!UnrollProlog) {
        NewLoop = new Loop();
        if (ParentLoop)
            ParentLoop->addChildLoop(NewLoop);
        else
            LI->addTopLevelLoop(NewLoop);
    }

    // For each block in the original loop, create a new copy,
    // and update the value map with the newly created values.
    for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
        BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".prol", F);
        NewBlocks.push_back(NewBB);

        if (NewLoop)
            NewLoop->addBasicBlockToLoop(NewBB, *LI);
        else if (ParentLoop)
            ParentLoop->addBasicBlockToLoop(NewBB, *LI);

        VMap[*BB] = NewBB;
        if (Header == *BB) {
            // For the first block, add a CFG connection to this newly
            // created block.
            InsertTop->getTerminator()->setSuccessor(0, NewBB);

        }
        if (Latch == *BB) {
            // For the last block, if UnrollProlog is true, create a direct jump to
            // InsertBot. If not, create a loop back to cloned head.
            VMap.erase((*BB)->getTerminator());
            BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
            BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
            IRBuilder<> Builder(LatchBR);
            if (UnrollProlog) {
                Builder.CreateBr(InsertBot);
            } else {
                PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2, "prol.iter",
                                                  FirstLoopBB->getFirstNonPHI());
                Value *IdxSub =
                    Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
                                      NewIdx->getName() + ".sub");
                Value *IdxCmp =
                    Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
                Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot);
                NewIdx->addIncoming(NewIter, InsertTop);
                NewIdx->addIncoming(IdxSub, NewBB);
            }
            LatchBR->eraseFromParent();
        }
    }

    // Change the incoming values to the ones defined in the preheader or
    // cloned loop.
    for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
        PHINode *NewPHI = cast<PHINode>(VMap[I]);
        if (UnrollProlog) {
            VMap[I] = NewPHI->getIncomingValueForBlock(Preheader);
            cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
        } else {
            unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
            NewPHI->setIncomingBlock(idx, InsertTop);
            BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
            idx = NewPHI->getBasicBlockIndex(Latch);
            Value *InVal = NewPHI->getIncomingValue(idx);
            NewPHI->setIncomingBlock(idx, NewLatch);
            if (VMap[InVal])
                NewPHI->setIncomingValue(idx, VMap[InVal]);
        }
    }
    if (NewLoop) {
        // Add unroll disable metadata to disable future unrolling for this loop.
        SmallVector<Metadata *, 4> MDs;
        // Reserve first location for self reference to the LoopID metadata node.
        MDs.push_back(nullptr);
        MDNode *LoopID = NewLoop->getLoopID();
        if (LoopID) {
            // First remove any existing loop unrolling metadata.
            for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
                bool IsUnrollMetadata = false;
                MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
                if (MD) {
                    const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
//.........这里部分代码省略.........
开发者ID:cyrilmagsuci,项目名称:freebsd,代码行数:101,代码来源:LoopUnrollRuntime.cpp

示例10: ConnectProlog

/// Connect the unrolling prolog code to the original loop.
/// The unrolling prolog code contains code to execute the
/// 'extra' iterations if the run-time trip count modulo the
/// unroll count is non-zero.
///
/// This function performs the following:
/// - Create PHI nodes at prolog end block to combine values
///   that exit the prolog code and jump around the prolog.
/// - Add a PHI operand to a PHI node at the loop exit block
///   for values that exit the prolog and go around the loop.
/// - Branch around the original loop if the trip count is less
///   than the unroll factor.
///
static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
                          BasicBlock *LastPrologBB, BasicBlock *PrologEnd,
                          BasicBlock *OrigPH, BasicBlock *NewPH,
                          ValueToValueMapTy &VMap, AliasAnalysis *AA,
                          DominatorTree *DT, LoopInfo *LI, Pass *P) {
    BasicBlock *Latch = L->getLoopLatch();
    assert(Latch && "Loop must have a latch");

    // Create a PHI node for each outgoing value from the original loop
    // (which means it is an outgoing value from the prolog code too).
    // The new PHI node is inserted in the prolog end basic block.
    // The new PHI name is added as an operand of a PHI node in either
    // the loop header or the loop exit block.
    for (succ_iterator SBI = succ_begin(Latch), SBE = succ_end(Latch);
            SBI != SBE; ++SBI) {
        for (BasicBlock::iterator BBI = (*SBI)->begin();
                PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) {

            // Add a new PHI node to the prolog end block and add the
            // appropriate incoming values.
            PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName()+".unr",
                                             PrologEnd->getTerminator());
            // Adding a value to the new PHI node from the original loop preheader.
            // This is the value that skips all the prolog code.
            if (L->contains(PN)) {
                NewPN->addIncoming(PN->getIncomingValueForBlock(NewPH), OrigPH);
            } else {
                NewPN->addIncoming(UndefValue::get(PN->getType()), OrigPH);
            }

            Value *V = PN->getIncomingValueForBlock(Latch);
            if (Instruction *I = dyn_cast<Instruction>(V)) {
                if (L->contains(I)) {
                    V = VMap[I];
                }
            }
            // Adding a value to the new PHI node from the last prolog block
            // that was created.
            NewPN->addIncoming(V, LastPrologBB);

            // Update the existing PHI node operand with the value from the
            // new PHI node.  How this is done depends on if the existing
            // PHI node is in the original loop block, or the exit block.
            if (L->contains(PN)) {
                PN->setIncomingValue(PN->getBasicBlockIndex(NewPH), NewPN);
            } else {
                PN->addIncoming(NewPN, PrologEnd);
            }
        }
    }

    // Create a branch around the orignal loop, which is taken if there are no
    // iterations remaining to be executed after running the prologue.
    Instruction *InsertPt = PrologEnd->getTerminator();
    IRBuilder<> B(InsertPt);

    assert(Count != 0 && "nonsensical Count!");

    // If BECount <u (Count - 1) then (BECount + 1) & (Count - 1) == (BECount + 1)
    // (since Count is a power of 2).  This means %xtraiter is (BECount + 1) and
    // and all of the iterations of this loop were executed by the prologue.  Note
    // that if BECount <u (Count - 1) then (BECount + 1) cannot unsigned-overflow.
    Value *BrLoopExit =
        B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
    BasicBlock *Exit = L->getUniqueExitBlock();
    assert(Exit && "Loop must have a single exit block only");
    // Split the exit to maintain loop canonicalization guarantees
    SmallVector<BasicBlock*, 4> Preds(pred_begin(Exit), pred_end(Exit));
    SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", AA, DT, LI,
                           P->mustPreserveAnalysisID(LCSSAID));
    // Add the branch to the exit block (around the unrolled loop)
    B.CreateCondBr(BrLoopExit, Exit, NewPH);
    InsertPt->eraseFromParent();
}
开发者ID:cyrilmagsuci,项目名称:freebsd,代码行数:87,代码来源:LoopUnrollRuntime.cpp

示例11: while

/// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
/// edge and spill them.
void SjLjEHPass::lowerAcrossUnwindEdges(Function &F,
                                        ArrayRef<InvokeInst*> Invokes) {
  // Finally, scan the code looking for instructions with bad live ranges.
  for (Function::iterator
         BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
    for (BasicBlock::iterator
           II = BB->begin(), IIE = BB->end(); II != IIE; ++II) {
      // Ignore obvious cases we don't have to handle. In particular, most
      // instructions either have no uses or only have a single use inside the
      // current block. Ignore them quickly.
      Instruction *Inst = II;
      if (Inst->use_empty()) continue;
      if (Inst->hasOneUse() &&
          cast<Instruction>(Inst->use_back())->getParent() == BB &&
          !isa<PHINode>(Inst->use_back())) continue;

      // If this is an alloca in the entry block, it's not a real register
      // value.
      if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
        if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
          continue;

      // Avoid iterator invalidation by copying users to a temporary vector.
      SmallVector<Instruction*, 16> Users;
      for (Value::use_iterator
             UI = Inst->use_begin(), E = Inst->use_end(); UI != E; ++UI) {
        Instruction *User = cast<Instruction>(*UI);
        if (User->getParent() != BB || isa<PHINode>(User))
          Users.push_back(User);
      }

      // Find all of the blocks that this value is live in.
      SmallPtrSet<BasicBlock*, 64> LiveBBs;
      LiveBBs.insert(Inst->getParent());
      while (!Users.empty()) {
        Instruction *U = Users.back();
        Users.pop_back();

        if (!isa<PHINode>(U)) {
          MarkBlocksLiveIn(U->getParent(), LiveBBs);
        } else {
          // Uses for a PHI node occur in their predecessor block.
          PHINode *PN = cast<PHINode>(U);
          for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
            if (PN->getIncomingValue(i) == Inst)
              MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
        }
      }

      // Now that we know all of the blocks that this thing is live in, see if
      // it includes any of the unwind locations.
      bool NeedsSpill = false;
      for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
        BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
        if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
          DEBUG(dbgs() << "SJLJ Spill: " << *Inst << " around "
                << UnwindBlock->getName() << "\n");
          NeedsSpill = true;
          break;
        }
      }

      // If we decided we need a spill, do it.
      // FIXME: Spilling this way is overkill, as it forces all uses of
      // the value to be reloaded from the stack slot, even those that aren't
      // in the unwind blocks. We should be more selective.
      if (NeedsSpill) {
        DemoteRegToStack(*Inst, true);
        ++NumSpilled;
      }
    }
  }

  // Go through the landing pads and remove any PHIs there.
  for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
    BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
    LandingPadInst *LPI = UnwindBlock->getLandingPadInst();

    // Place PHIs into a set to avoid invalidating the iterator.
    SmallPtrSet<PHINode*, 8> PHIsToDemote;
    for (BasicBlock::iterator
           PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
      PHIsToDemote.insert(cast<PHINode>(PN));
    if (PHIsToDemote.empty()) continue;

    // Demote the PHIs to the stack.
    for (SmallPtrSet<PHINode*, 8>::iterator
           I = PHIsToDemote.begin(), E = PHIsToDemote.end(); I != E; ++I)
      DemotePHIToStack(*I);

    // Move the landingpad instruction back to the top of the landing pad block.
    LPI->moveBefore(UnwindBlock->begin());
  }
}
开发者ID:PhongNgo,项目名称:llvm,代码行数:96,代码来源:SjLjEHPrepare.cpp

示例12: getInductionVariable

// This function indicates the current limitations in the transform as a result
// of which we do not proceed.
bool LoopInterchangeLegality::currentLimitations() {

  BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader();
  BasicBlock *InnerLoopHeader = InnerLoop->getHeader();
  BasicBlock *OuterLoopHeader = OuterLoop->getHeader();
  BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
  BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch();

  PHINode *InnerInductionVar;
  PHINode *OuterInductionVar;

  // We currently handle only 1 induction variable inside the loop. We also do
  // not handle reductions as of now.
  if (getPHICount(InnerLoopHeader) > 1)
    return true;

  if (getPHICount(OuterLoopHeader) > 1)
    return true;

  InnerInductionVar = getInductionVariable(InnerLoop, SE);
  OuterInductionVar = getInductionVariable(OuterLoop, SE);

  if (!OuterInductionVar || !InnerInductionVar) {
    DEBUG(dbgs() << "Induction variable not found\n");
    return true;
  }

  // TODO: Triangular loops are not handled for now.
  if (!isLoopStructureUnderstood(InnerInductionVar)) {
    DEBUG(dbgs() << "Loop structure not understood by pass\n");
    return true;
  }

  // TODO: Loops with LCSSA PHI's are currently not handled.
  if (isa<PHINode>(OuterLoopLatch->begin())) {
    DEBUG(dbgs() << "Found and LCSSA PHI in outer loop latch\n");
    return true;
  }
  if (InnerLoopLatch != InnerLoopHeader &&
      isa<PHINode>(InnerLoopLatch->begin())) {
    DEBUG(dbgs() << "Found and LCSSA PHI in inner loop latch\n");
    return true;
  }

  // TODO: Current limitation: Since we split the inner loop latch at the point
  // were induction variable is incremented (induction.next); We cannot have
  // more than 1 user of induction.next since it would result in broken code
  // after split.
  // e.g.
  // for(i=0;i<N;i++) {
  //    for(j = 0;j<M;j++) {
  //      A[j+1][i+2] = A[j][i]+k;
  //  }
  // }
  bool FoundInduction = false;
  Instruction *InnerIndexVarInc = nullptr;
  if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader)
    InnerIndexVarInc =
        dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1));
  else
    InnerIndexVarInc =
        dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0));

  if (!InnerIndexVarInc)
    return true;

  // Since we split the inner loop latch on this induction variable. Make sure
  // we do not have any instruction between the induction variable and branch
  // instruction.

  for (auto I = InnerLoopLatch->rbegin(), E = InnerLoopLatch->rend();
       I != E && !FoundInduction; ++I) {
    if (isa<BranchInst>(*I) || isa<CmpInst>(*I) || isa<TruncInst>(*I))
      continue;
    const Instruction &Ins = *I;
    // We found an instruction. If this is not induction variable then it is not
    // safe to split this loop latch.
    if (!Ins.isIdenticalTo(InnerIndexVarInc))
      return true;
    else
      FoundInduction = true;
  }
  // The loop latch ended and we didnt find the induction variable return as
  // current limitation.
  if (!FoundInduction)
    return true;

  return false;
}
开发者ID:GameFusion,项目名称:llvm,代码行数:91,代码来源:LoopInterchange.cpp

示例13: ConnectProlog

/// Connect the unrolling prolog code to the original loop.
/// The unrolling prolog code contains code to execute the
/// 'extra' iterations if the run-time trip count modulo the
/// unroll count is non-zero.
///
/// This function performs the following:
/// - Create PHI nodes at prolog end block to combine values
///   that exit the prolog code and jump around the prolog.
/// - Add a PHI operand to a PHI node at the loop exit block
///   for values that exit the prolog and go around the loop.
/// - Branch around the original loop if the trip count is less
///   than the unroll factor.
///
static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
                          BasicBlock *PrologExit,
                          BasicBlock *OriginalLoopLatchExit,
                          BasicBlock *PreHeader, BasicBlock *NewPreHeader,
                          ValueToValueMapTy &VMap, DominatorTree *DT,
                          LoopInfo *LI, bool PreserveLCSSA) {
  BasicBlock *Latch = L->getLoopLatch();
  assert(Latch && "Loop must have a latch");
  BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]);

  // Create a PHI node for each outgoing value from the original loop
  // (which means it is an outgoing value from the prolog code too).
  // The new PHI node is inserted in the prolog end basic block.
  // The new PHI node value is added as an operand of a PHI node in either
  // the loop header or the loop exit block.
  for (BasicBlock *Succ : successors(Latch)) {
    for (Instruction &BBI : *Succ) {
      PHINode *PN = dyn_cast<PHINode>(&BBI);
      // Exit when we passed all PHI nodes.
      if (!PN)
        break;
      // Add a new PHI node to the prolog end block and add the
      // appropriate incoming values.
      PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr",
                                       PrologExit->getFirstNonPHI());
      // Adding a value to the new PHI node from the original loop preheader.
      // This is the value that skips all the prolog code.
      if (L->contains(PN)) {
        NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader),
                           PreHeader);
      } else {
        NewPN->addIncoming(UndefValue::get(PN->getType()), PreHeader);
      }

      Value *V = PN->getIncomingValueForBlock(Latch);
      if (Instruction *I = dyn_cast<Instruction>(V)) {
        if (L->contains(I)) {
          V = VMap.lookup(I);
        }
      }
      // Adding a value to the new PHI node from the last prolog block
      // that was created.
      NewPN->addIncoming(V, PrologLatch);

      // Update the existing PHI node operand with the value from the
      // new PHI node.  How this is done depends on if the existing
      // PHI node is in the original loop block, or the exit block.
      if (L->contains(PN)) {
        PN->setIncomingValue(PN->getBasicBlockIndex(NewPreHeader), NewPN);
      } else {
        PN->addIncoming(NewPN, PrologExit);
      }
    }
  }

  // Make sure that created prolog loop is in simplified form
  SmallVector<BasicBlock *, 4> PrologExitPreds;
  Loop *PrologLoop = LI->getLoopFor(PrologLatch);
  if (PrologLoop) {
    for (BasicBlock *PredBB : predecessors(PrologExit))
      if (PrologLoop->contains(PredBB))
        PrologExitPreds.push_back(PredBB);

    SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI,
                           PreserveLCSSA);
  }

  // Create a branch around the original loop, which is taken if there are no
  // iterations remaining to be executed after running the prologue.
  Instruction *InsertPt = PrologExit->getTerminator();
  IRBuilder<> B(InsertPt);

  assert(Count != 0 && "nonsensical Count!");

  // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
  // This means %xtraiter is (BECount + 1) and all of the iterations of this
  // loop were executed by the prologue.  Note that if BECount <u (Count - 1)
  // then (BECount + 1) cannot unsigned-overflow.
  Value *BrLoopExit =
      B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
  // Split the exit to maintain loop canonicalization guarantees
  SmallVector<BasicBlock *, 4> Preds(predecessors(OriginalLoopLatchExit));
  SplitBlockPredecessors(OriginalLoopLatchExit, Preds, ".unr-lcssa", DT, LI,
                         PreserveLCSSA);
  // Add the branch to the exit block (around the unrolled loop)
  B.CreateCondBr(BrLoopExit, OriginalLoopLatchExit, NewPreHeader);
  InsertPt->eraseFromParent();
//.........这里部分代码省略.........
开发者ID:JaredCJR,项目名称:llvm,代码行数:101,代码来源:LoopUnrollRuntime.cpp

示例14: GetValueAtEndOfBlock

Value *SSAUpdater::GetValueInMiddleOfBlock(BasicBlock *BB) {
  // If there is no definition of the renamed variable in this block, just use
  // GetValueAtEndOfBlock to do our work.
  if (!HasValueForBlock(BB))
    return GetValueAtEndOfBlock(BB);

  // Otherwise, we have the hard case.  Get the live-in values for each
  // predecessor.
  SmallVector<std::pair<BasicBlock*, Value*>, 8> PredValues;
  Value *SingularValue = nullptr;

  // We can get our predecessor info by walking the pred_iterator list, but it
  // is relatively slow.  If we already have PHI nodes in this block, walk one
  // of them to get the predecessor list instead.
  if (PHINode *SomePhi = dyn_cast<PHINode>(BB->begin())) {
    for (unsigned i = 0, e = SomePhi->getNumIncomingValues(); i != e; ++i) {
      BasicBlock *PredBB = SomePhi->getIncomingBlock(i);
      Value *PredVal = GetValueAtEndOfBlock(PredBB);
      PredValues.push_back(std::make_pair(PredBB, PredVal));

      // Compute SingularValue.
      if (i == 0)
        SingularValue = PredVal;
      else if (PredVal != SingularValue)
        SingularValue = nullptr;
    }
  } else {
    bool isFirstPred = true;
    for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
      BasicBlock *PredBB = *PI;
      Value *PredVal = GetValueAtEndOfBlock(PredBB);
      PredValues.push_back(std::make_pair(PredBB, PredVal));

      // Compute SingularValue.
      if (isFirstPred) {
        SingularValue = PredVal;
        isFirstPred = false;
      } else if (PredVal != SingularValue)
        SingularValue = nullptr;
    }
  }

  // If there are no predecessors, just return undef.
  if (PredValues.empty())
    return UndefValue::get(ProtoType);

  // Otherwise, if all the merged values are the same, just use it.
  if (SingularValue)
    return SingularValue;

  // Otherwise, we do need a PHI: check to see if we already have one available
  // in this block that produces the right value.
  if (isa<PHINode>(BB->begin())) {
    SmallDenseMap<BasicBlock*, Value*, 8> ValueMapping(PredValues.begin(),
                                                       PredValues.end());
    PHINode *SomePHI;
    for (BasicBlock::iterator It = BB->begin();
         (SomePHI = dyn_cast<PHINode>(It)); ++It) {
      if (IsEquivalentPHI(SomePHI, ValueMapping))
        return SomePHI;
    }
  }

  // Ok, we have no way out, insert a new one now.
  PHINode *InsertedPHI = PHINode::Create(ProtoType, PredValues.size(),
                                         ProtoName, &BB->front());

  // Fill in all the predecessors of the PHI.
  for (unsigned i = 0, e = PredValues.size(); i != e; ++i)
    InsertedPHI->addIncoming(PredValues[i].second, PredValues[i].first);

  // See if the PHI node can be merged to a single value.  This can happen in
  // loop cases when we get a PHI of itself and one other value.
  if (Value *V =
          SimplifyInstruction(InsertedPHI, BB->getModule()->getDataLayout())) {
    InsertedPHI->eraseFromParent();
    return V;
  }

  // Set the DebugLoc of the inserted PHI, if available.
  DebugLoc DL;
  if (const Instruction *I = BB->getFirstNonPHI())
      DL = I->getDebugLoc();
  InsertedPHI->setDebugLoc(DL);

  // If the client wants to know about all new instructions, tell it.
  if (InsertedPHIs) InsertedPHIs->push_back(InsertedPHI);

  DEBUG(dbgs() << "  Inserted PHI: " << *InsertedPHI << "\n");
  return InsertedPHI;
}
开发者ID:dongAxis,项目名称:clang-700.0.72,代码行数:91,代码来源:SSAUpdater.cpp

示例15: assert

/// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
/// except that it does some simple constant prop and DCE on the fly.  The
/// effect of this is to copy significantly less code in cases where (for
/// example) a function call with constant arguments is inlined, and those
/// constant arguments cause a significant amount of code in the callee to be
/// dead.  Since this doesn't produce an exact copy of the input, it can't be
/// used for things like CloneFunction or CloneModule.
void llvm::CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
                                     DenseMap<const Value*, Value*> &ValueMap,
                                     SmallVectorImpl<ReturnInst*> &Returns,
                                     const char *NameSuffix, 
                                     ClonedCodeInfo *CodeInfo,
                                     const TargetData *TD,
                                     Instruction *TheCall) {
  assert(NameSuffix && "NameSuffix cannot be null!");
  
#ifndef NDEBUG
  for (Function::const_arg_iterator II = OldFunc->arg_begin(), 
       E = OldFunc->arg_end(); II != E; ++II)
    assert(ValueMap.count(II) && "No mapping from source argument specified!");
#endif

  PruningFunctionCloner PFC(NewFunc, OldFunc, ValueMap, Returns,
                            NameSuffix, CodeInfo, TD);

  // Clone the entry block, and anything recursively reachable from it.
  std::vector<const BasicBlock*> CloneWorklist;
  CloneWorklist.push_back(&OldFunc->getEntryBlock());
  while (!CloneWorklist.empty()) {
    const BasicBlock *BB = CloneWorklist.back();
    CloneWorklist.pop_back();
    PFC.CloneBlock(BB, CloneWorklist);
  }
  
  // Loop over all of the basic blocks in the old function.  If the block was
  // reachable, we have cloned it and the old block is now in the value map:
  // insert it into the new function in the right order.  If not, ignore it.
  //
  // Defer PHI resolution until rest of function is resolved.
  SmallVector<const PHINode*, 16> PHIToResolve;
  for (Function::const_iterator BI = OldFunc->begin(), BE = OldFunc->end();
       BI != BE; ++BI) {
    BasicBlock *NewBB = cast_or_null<BasicBlock>(ValueMap[BI]);
    if (NewBB == 0) continue;  // Dead block.

    // Add the new block to the new function.
    NewFunc->getBasicBlockList().push_back(NewBB);
    
    // Loop over all of the instructions in the block, fixing up operand
    // references as we go.  This uses ValueMap to do all the hard work.
    //
    BasicBlock::iterator I = NewBB->begin();

    LLVMContext &Context = OldFunc->getContext();
    unsigned DbgKind = Context.getMetadata().getMDKind("dbg");
    MDNode *TheCallMD = NULL;
    SmallVector<Value *, 4> MDVs;
    if (TheCall && TheCall->hasMetadata()) 
      TheCallMD = Context.getMetadata().getMD(DbgKind, TheCall);
    
    // Handle PHI nodes specially, as we have to remove references to dead
    // blocks.
    if (PHINode *PN = dyn_cast<PHINode>(I)) {
      // Skip over all PHI nodes, remembering them for later.
      BasicBlock::const_iterator OldI = BI->begin();
      for (; (PN = dyn_cast<PHINode>(I)); ++I, ++OldI) {
        if (I->hasMetadata()) {
          if (TheCallMD) {
            if (MDNode *IMD = Context.getMetadata().getMD(DbgKind, I)) {
              MDNode *NewMD = UpdateInlinedAtInfo(IMD, TheCallMD, Context);
              Context.getMetadata().addMD(DbgKind, NewMD, I);
            }
          } else {
            // The cloned instruction has dbg info but the call instruction
            // does not have dbg info. Remove dbg info from cloned instruction.
            Context.getMetadata().removeMD(DbgKind, I);
          }
        }
        PHIToResolve.push_back(cast<PHINode>(OldI));
      }
    }
    
    // Otherwise, remap the rest of the instructions normally.
    for (; I != NewBB->end(); ++I) {
      if (I->hasMetadata()) {
        if (TheCallMD) {
          if (MDNode *IMD = Context.getMetadata().getMD(DbgKind, I)) {
            MDNode *NewMD = UpdateInlinedAtInfo(IMD, TheCallMD, Context);
            Context.getMetadata().addMD(DbgKind, NewMD, I);
          }
        } else {
          // The cloned instruction has dbg info but the call instruction
          // does not have dbg info. Remove dbg info from cloned instruction.
          Context.getMetadata().removeMD(DbgKind, I);
        }
      }
      RemapInstruction(I, ValueMap);
    }
  }
  
//.........这里部分代码省略.........
开发者ID:aaasz,项目名称:SHP,代码行数:101,代码来源:CloneFunction.cpp


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