14 #define DEBUG_TYPE "loop-rotate"
33 #define MAX_HEADER_SIZE 16
35 STATISTIC(NumRotated,
"Number of loops rotated");
59 bool simplifyLoopLatch(
Loop *L);
60 bool rotateLoop(
Loop *L,
bool SimplifiedLatch);
81 LI = &getAnalysis<LoopInfo>();
82 TTI = &getAnalysis<TargetTransformInfo>();
87 bool SimplifiedLatch = simplifyLoopLatch(L);
90 bool MadeChange =
false;
91 while (rotateLoop(L, SimplifiedLatch)) {
93 SimplifiedLatch =
false;
113 for (I = OrigHeader->
begin(); I != E; ++
I) {
121 Value *OrigPreHeaderVal = ValueMap[OrigHeaderVal];
131 UE = OrigHeaderVal->
use_end(); UI != UE; ) {
133 Use &U = UI.getUse();
141 if (!isa<PHINode>(UserInst)) {
146 if (UserBB == OrigHeader)
151 if (UserBB == OrigPreheader) {
152 U = OrigPreHeaderVal;
169 bool seenIncrement =
false;
175 if (isa<DbgInfoIntrinsic>(
I))
178 switch (
I->getOpcode()) {
181 case Instruction::GetElementPtr:
183 if (!cast<GEPOperator>(
I)->hasAllConstantIndices())
186 case Instruction::Add:
187 case Instruction::Sub:
191 case Instruction::Shl:
192 case Instruction::LShr:
193 case Instruction::AShr:
196 seenIncrement =
true;
198 case Instruction::Trunc:
199 case Instruction::ZExt:
200 case Instruction::SExt:
216 bool LoopRotate::simplifyLoopLatch(
Loop *L) {
237 << LastExit->
getName() <<
"\n");
242 unsigned FallThruPath = BI->
getSuccessor(0) == Latch ? 0 : 1;
244 assert(Header == L->
getHeader() &&
"expected a backward branch");
252 assert(Latch->
empty() &&
"unable to evacuate Latch");
253 LI->removeBlock(Latch);
254 if (
DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>())
255 DT->eraseNode(Latch);
270 bool LoopRotate::rotateLoop(
Loop *L,
bool SimplifiedLatch) {
304 DEBUG(
dbgs() <<
"LoopRotation: NOT rotating - contains non duplicatable"
305 <<
" instructions: "; L->
dump());
317 if (OrigPreheader == 0)
334 assert(NewHeader &&
"Unable to determine new loop header");
336 "Unable to determine loop header and exit blocks");
341 "New header doesn't have one pred!");
368 !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
369 !isa<AllocaInst>(Inst)) {
385 if (V &&
LI->replacementPreservesLCSSAForm(C, V)) {
418 assert(L->
getHeader() == NewHeader &&
"Latch block is our new header");
429 assert(PHBI->isConditional() &&
"Should be clone of BI condbr!");
430 if (!isa<ConstantInt>(PHBI->getCondition()) ||
431 PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->
isZero())
436 if (
DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
441 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
443 OrigHeaderNode->
end());
444 DomTreeNode *OrigPreheaderNode = DT->getNode(OrigPreheader);
445 for (
unsigned I = 0, E = HeaderChildren.size(); I != E; ++
I)
446 DT->changeImmediateDominator(HeaderChildren[I], OrigPreheaderNode);
448 assert(DT->getNode(Exit)->getIDom() == OrigPreheaderNode);
449 assert(DT->getNode(NewHeader)->getIDom() == OrigPreheaderNode);
452 DT->changeImmediateDominator(OrigHeader, OrigLatch);
468 Exit->removePredecessor(OrigPreheader,
true );
471 PHBI->eraseFromParent();
474 if (
DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>()) {
476 DT->changeImmediateDominator(NewHeader, OrigPreheader);
477 DT->changeImmediateDominator(OrigHeader, OrigLatch);
482 DomTreeNode *OrigHeaderNode = DT->getNode(OrigHeader);
484 OrigHeaderNode->
end());
488 for (
unsigned I = 0, E = HeaderChildren.size(); I != E; ++
I) {
495 NearestDom = DT->findNearestCommonDominator(NearestDom, *PI);
498 if (Node->
getIDom()->getBlock() != NearestDom) {
499 DT->changeImmediateDominator(BB, NearestDom);
510 assert(L->
getLoopPreheader() &&
"Invalid loop preheader after loop rotation");
511 assert(L->
getLoopLatch() &&
"Invalid loop latch after loop rotation");
void FoldSingleEntryPHINodes(BasicBlock *BB, Pass *P=0)
AnalysisUsage & addPreserved()
Helper class for SSA formation on a set of values defined in multiple blocks.
void addIncoming(Value *V, BasicBlock *BB)
static PassRegistry * getPassRegistry()
void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
BasicBlock * SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, Pass *P=0, bool MergeIdenticalEdges=false, bool DontDeleteUselessPHIs=false, bool SplitLandingPads=false)
enable_if_c<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
bool isLoopExiting(const BlockT *BB) const
bool notDuplicatable
True if this function cannot be duplicated.
Pass * createLoopRotatePass()
const std::vector< BlockT * > & getBlocks() const
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=0, ValueMaterializer *Materializer=0)
void setDebugLoc(const DebugLoc &Loc)
setDebugLoc - Set the debug location information for this instruction.
BlockT * getHeader() const
LoopInfoBase< BlockT, LoopT > * LI
StringRef getName() const
BlockT * getLoopLatch() const
DomTreeNodeBase< NodeT > * getIDom() const
STATISTIC(NumRotated,"Number of loops rotated")
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool isUnconditional() const
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
void analyzeBasicBlock(const BasicBlock *BB, const TargetTransformInfo &TTI)
Add information about a block to the current state.
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=0)
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc. to it.
bool hasLoopInvariantOperands(Instruction *I) const
bool MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P=0)
void setName(const Twine &Name)
ID
LLVM Calling Convention Representation.
Instruction * clone() const
bool mayReadFromMemory() const
BasicBlock * getSuccessor(unsigned i) const
uint64_t rotate(uint64_t val, size_t shift)
Bitwise right rotate. Normally this will compile to a single instruction, especially if the shift is ...
void initializeLoopRotatePass(PassRegistry &)
AnalysisUsage & addPreservedID(const void *ID)
unsigned getNumSuccessors() const
void replaceSuccessorsPhiUsesWith(BasicBlock *New)
Update all phi nodes in this basic block's successors to refer to basic block New instead of to it...
BlockT * getLoopPreheader() const
void insertBefore(Instruction *InsertPos)
LLVM Basic Block Representation.
BasicBlock * getSuccessor(unsigned idx) const
static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader, BasicBlock *OrigPreheader, ValueToValueMapTy &ValueMap)
APInt Or(const APInt &LHS, const APInt &RHS)
Bitwise OR function for APInt.
APInt Xor(const APInt &LHS, const APInt &RHS)
Bitwise XOR function for APInt.
Interval::pred_iterator pred_begin(Interval *I)
bool contains(const LoopT *L) const
const InstListType & getInstList() const
Return the underlying instruction list container.
Interval::pred_iterator pred_end(Interval *I)
static bool shouldSpeculateInstrs(BasicBlock::iterator Begin, BasicBlock::iterator End)
#define INITIALIZE_AG_DEPENDENCY(depName)
Value * SimplifyInstruction(Instruction *I, const DataLayout *TD=0, const TargetLibraryInfo *TLI=0, const DominatorTree *DT=0)
bool mayWriteToMemory() const
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
bool isSafeToSpeculativelyExecute(const Value *V, const DataLayout *TD=0)
static bool isZero(Value *V, DataLayout *DL)
machine trace Machine Trace Metrics
AnalysisUsage & addRequiredID(const void *ID)
void eraseFromParent()
Unlink 'this' from the containing function and delete it.
Utility to calculate the size and a few similar metrics for a set of basic blocks.
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
void splice(iterator where, iplist &L2)
raw_ostream & dbgs()
dbgs - Return a circular-buffered debug stream.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getSinglePredecessor()
Return this block if it has a single predecessor block. Otherwise return a null pointer.
APInt And(const APInt &LHS, const APInt &RHS)
Bitwise AND function for APInt.
void moveToHeader(BlockT *BB)
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
LLVM Value Representation.
void moveBefore(Instruction *MovePos)
unsigned NumInsts
Number of instructions in the analyzed blocks.
void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
int getBasicBlockIndex(const BasicBlock *BB) const
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
const BasicBlock * getParent() const