33 #define DEBUG_TYPE "licm"
60 STATISTIC(NumSunk ,
"Number of instructions sunk out of loop");
61 STATISTIC(NumHoisted ,
"Number of instructions hoisted out of loop");
62 STATISTIC(NumMovedLoads,
"Number of load insts hoisted or sunk");
63 STATISTIC(NumMovedCalls,
"Number of call insts hoisted or sunk");
64 STATISTIC(NumPromoted ,
"Number of memory locations promoted to registers");
68 cl::desc(
"Disable memory promotion in LICM pass"));
96 bool doFinalization() {
97 assert(LoopToAliasSetMap.empty() &&
"Didn't free loop alias sets");
124 void deleteAnalysisValue(
Value *V,
Loop *L);
146 assert(CurLoop->contains(BB) &&
"Only valid if BB is IN the loop");
147 return LI->getLoopFor(BB) != CurLoop;
175 bool pointerInvalidatedByLoop(
Value *V, uint64_t Size,
178 return CurAST->getAliasSetForPointer(V, Size, TBAAInfo).isMod();
209 LI = &getAnalysis<LoopInfo>();
210 AA = &getAnalysis<AliasAnalysis>();
211 DT = &getAnalysis<DominatorTree>();
213 TD = getAnalysisIfAvailable<DataLayout>();
214 TLI = &getAnalysis<TargetLibraryInfo>();
219 LoopItr != LoopItrE; ++LoopItr) {
220 Loop *InnerL = *LoopItr;
222 assert(InnerAST &&
"Where is my AST?");
225 CurAST->add(*InnerAST);
230 LoopToAliasSetMap.erase(InnerL);
245 if (
LI->getLoopFor(BB) == L)
253 (BB != BBE) && !MayThrow ; ++BB)
255 (
I != E) && !MayThrow; ++
I)
256 MayThrow |=
I->mayThrow();
271 HoistRegion(DT->getNode(L->
getHeader()));
282 PromoteAliasSet(*
I, ExitBlocks, InsertPts);
292 LoopToAliasSetMap[L] = CurAST;
305 assert(N != 0 &&
"Null dominator tree node?");
309 if (!CurLoop->contains(BB))
return;
312 const std::vector<DomTreeNode*> &Children = N->
getChildren();
313 for (
unsigned i = 0, e = Children.size(); i != e; ++i)
314 SinkRegion(Children[i]);
318 if (inSubLoop(BB))
return;
326 DEBUG(
dbgs() <<
"LICM deleting dead inst: " << I <<
'\n');
328 CurAST->deleteValue(&I);
339 if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
352 assert(N != 0 &&
"Null dominator tree node?");
356 if (!CurLoop->contains(BB))
return;
368 DEBUG(
dbgs() <<
"LICM folding inst: " << I <<
" --> " << *
C <<
'\n');
369 CurAST->copyValue(&I,
C);
370 CurAST->deleteValue(&I);
380 if (CurLoop->hasLoopInvariantOperands(&I) && canSinkOrHoistInst(I) &&
381 isSafeToExecuteUnconditionally(I))
385 const std::vector<DomTreeNode*> &Children = N->
getChildren();
386 for (
unsigned i = 0, e = Children.size(); i != e; ++i)
387 HoistRegion(Children[i]);
396 if (!
LI->isUnordered())
401 if (AA->pointsToConstantMemory(
LI->getOperand(0)))
403 if (
LI->getMetadata(
"invariant.load"))
408 if (
LI->getType()->isSized())
409 Size = AA->getTypeStoreSize(
LI->getType());
410 return !pointerInvalidatedByLoop(
LI->getOperand(0), Size,
412 }
else if (
CallInst *CI = dyn_cast<CallInst>(&I)) {
414 if (isa<DbgInfoIntrinsic>(I))
424 bool FoundMod =
false;
433 if (!FoundMod)
return true;
443 if (!isa<BinaryOperator>(I) && !isa<CastInst>(
I) && !isa<SelectInst>(I) &&
444 !isa<GetElementPtrInst>(
I) && !isa<CmpInst>(I) &&
445 !isa<InsertElementInst>(
I) && !isa<ExtractElementInst>(I) &&
446 !isa<ShuffleVectorInst>(
I) && !isa<ExtractValueInst>(I) &&
447 !isa<InsertValueInst>(
I))
450 return isSafeToExecuteUnconditionally(I);
460 if (
PHINode *PN = dyn_cast<PHINode>(User)) {
462 for (
unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
463 if (PN->getIncomingValue(i) == &
I)
464 if (CurLoop->contains(PN->getIncomingBlock(i)))
466 }
else if (CurLoop->contains(User)) {
480 DEBUG(
dbgs() <<
"LICM sinking instruction: " << I <<
"\n");
483 CurLoop->getUniqueExitBlocks(ExitBlocks);
485 if (isa<LoadInst>(I)) ++NumMovedLoads;
486 else if (isa<CallInst>(I)) ++NumMovedCalls;
493 if (ExitBlocks.
size() == 1) {
494 if (!DT->dominates(I.
getParent(), ExitBlocks[0])) {
496 CurAST->deleteValue(&I);
506 I.
moveBefore(ExitBlocks[0]->getFirstInsertionPt());
511 CurAST->deleteValue(&I);
516 if (ExitBlocks.
empty()) {
518 CurAST->deleteValue(&I);
540 unsigned NumInserted = 0;
542 for (
unsigned i = 0, e = ExitBlocks.
size(); i != e; ++i) {
545 if (!DT->dominates(InstOrigBB, ExitBlock))
555 if (NumInserted++ == 0) {
567 SSA.AddAvailableValue(ExitBlock, New);
571 if (NumInserted == 0) {
572 CurAST->deleteValue(&I);
582 Use &U = UI.getUse();
585 SSA.RewriteUseAfterInsertions(U);
590 for (
unsigned i = 0, e = NewPHIs.
size(); i != e; ++i)
591 CurAST->copyValue(&I, NewPHIs[i]);
594 CurAST->deleteValue(&I);
601 DEBUG(
dbgs() <<
"LICM hoisting to " << Preheader->getName() <<
": "
607 if (isa<LoadInst>(I)) ++NumMovedLoads;
608 else if (isa<CallInst>(I)) ++NumMovedCalls;
617 bool LICM::isSafeToExecuteUnconditionally(
Instruction &Inst) {
622 return isGuaranteedToExecute(Inst);
625 bool LICM::isGuaranteedToExecute(
Instruction &Inst) {
639 if (Inst.
getParent() == CurLoop->getHeader())
644 CurLoop->getExitBlocks(ExitBlocks);
647 for (
unsigned i = 0, e = ExitBlocks.
size(); i != e; ++i)
648 if (!DT->dominates(Inst.
getParent(), ExitBlocks[i]))
653 if (ExitBlocks.
empty())
670 LoopPromoter(
Value *SP,
678 PointerMustAliases(PMA), LoopExitBlocks(LEB), LoopInsertPts(LIP),
679 AST(ast), DL(dl), Alignment(alignment), TBAATag(TBAATag) {}
685 Ptr =
LI->getOperand(0);
688 return PointerMustAliases.count(Ptr);
691 virtual void doExtraRewritesBeforeFinalDeletion()
const {
696 for (
unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
698 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
709 AST.copyValue(LI, V);
711 virtual void instructionDeleted(
Instruction *I)
const {
722 void LICM::PromoteAliasSet(
AliasSet &AS,
732 assert(!AS.
empty() &&
733 "Must alias set should have at least one pointer element in it!");
749 bool GuaranteedToExecute =
false;
756 unsigned Alignment = 1;
763 Value *ASIV = ASI->getValue();
764 PointerMustAliases.
insert(ASIV);
769 if (SomePtr->getType() != ASIV->
getType())
776 if (!Use || !CurLoop->contains(Use))
781 if (
LoadInst *load = dyn_cast<LoadInst>(Use)) {
782 assert(!load->isVolatile() &&
"AST broken");
783 if (!load->isSimple())
785 }
else if (
StoreInst *store = dyn_cast<StoreInst>(Use)) {
790 assert(!store->isVolatile() &&
"AST broken");
791 if (!store->isSimple())
802 unsigned InstAlignment = store->getAlignment();
803 if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0)
804 if (isGuaranteedToExecute(*Use)) {
805 GuaranteedToExecute =
true;
806 Alignment = InstAlignment;
809 if (!GuaranteedToExecute)
810 GuaranteedToExecute = isGuaranteedToExecute(*Use);
816 if (LoopUses.
empty()) {
819 }
else if (TBAATag) {
829 if (!GuaranteedToExecute)
833 DEBUG(
dbgs() <<
"LICM: Promoting value stored to in loop: " <<*SomePtr<<
'\n');
841 DebugLoc DL = LoopUses[0]->getDebugLoc();
845 if (ExitBlocks.
empty()) {
846 CurLoop->getUniqueExitBlocks(ExitBlocks);
848 for (
unsigned i = 0, e = ExitBlocks.
size(); i != e; ++i)
849 InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt();
855 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
856 InsertPts, *CurAST, DL, Alignment, TBAATag);
861 new LoadInst(SomePtr, SomePtr->getName()+
".promoted",
862 Preheader->getTerminator());
866 SSA.AddAvailableValue(Preheader, PreheaderLoad);
870 Promoter.run(LoopUses);
889 void LICM::deleteAnalysisValue(
Value *V,
Loop *L) {
void push_back(const T &Elt)
AnalysisUsage & addPreserved()
Helper class for SSA formation on a set of values defined in multiple blocks.
static PassRegistry * getPassRegistry()
bool isForwardingAliasSet() const
Define an iterator for alias sets... this is just a forward iterator.
enable_if_c<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static cl::opt< bool > DisablePromotion("disable-licm-promotion", cl::Hidden, cl::desc("Disable memory promotion in LICM pass"))
LoopT * getParentLoop() const
MDNode - a tuple of other values.
void setDebugLoc(const DebugLoc &Loc)
setDebugLoc - Set the debug location information for this instruction.
BlockT * getHeader() const
LoopInfoBase< BlockT, LoopT > * LI
StringRef getName() const
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
static Value * getPointerOperand(Instruction &Inst)
virtual bool doFinalization(Module &)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
void setName(const Twine &Name)
ID
LLVM Calling Convention Representation.
Instruction * clone() const
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout *TD=0, const TargetLibraryInfo *TLI=0)
AnalysisUsage & addPreservedID(const void *ID)
void replaceAllUsesWith(Value *V)
bool onlyReadsMemory(ImmutableCallSite CS)
BlockT * getLoopPreheader() const
LLVM Basic Block Representation.
LLVM Constant Representation.
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=0)
const InstListType & getInstList() const
Return the underlying instruction list container.
iterator insert(iterator where, NodeTy *New)
Value * getOperand(unsigned i) const
void setAlignment(unsigned Align)
void initializeLICMPass(PassRegistry &)
#define INITIALIZE_AG_DEPENDENCY(depName)
static MDNode * getMostGenericTBAA(MDNode *A, MDNode *B)
Methods for metadata merging.
bool hasDedicatedExits() const
static UndefValue * get(Type *T)
void setMetadata(unsigned KindID, MDNode *Node)
STATISTIC(NumSunk,"Number of instructions sunk out of loop")
const std::vector< DomTreeNodeBase< NodeT > * > & getChildren() const
bool isSafeToSpeculativelyExecute(const Value *V, const DataLayout *TD=0)
AnalysisUsage & addRequiredID(const void *ID)
void copyValue(Value *From, Value *To)
MDNode * getMetadata(unsigned KindID) const
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
raw_ostream & dbgs()
dbgs - Return a circular-buffered debug stream.
std::vector< BlockT * >::const_iterator block_iterator
block_iterator block_end() const
Machine Loop Invariant Code Motion
LLVM Value Representation.
void setAlignment(unsigned Align)
void moveBefore(Instruction *MovePos)
block_iterator block_begin() const
std::vector< LoopT * >::const_iterator iterator
iterator getFirstInsertionPt()
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const BasicBlock * getParent() const
void deleteValue(Value *PtrVal)
INITIALIZE_PASS(GlobalMerge,"global-merge","Global Merge", false, false) bool GlobalMerge const DataLayout * TD
bool empty() const
empty - Check if the string is empty.