1 //===--- HexagonCommonGEP.cpp ---------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #define DEBUG_TYPE "commgep"
12 #include "llvm/Pass.h"
13 #include "llvm/ADT/FoldingSet.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/Analysis/LoopInfo.h"
16 #include "llvm/Analysis/PostDominators.h"
17 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/Dominators.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/Verifier.h"
23 #include "llvm/Support/Allocator.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/Transforms/Utils/Local.h"
34 #include "HexagonTargetMachine.h"
38 static cl::opt<bool> OptSpeculate("commgep-speculate", cl::init(true),
39 cl::Hidden, cl::ZeroOrMore);
41 static cl::opt<bool> OptEnableInv("commgep-inv", cl::init(true), cl::Hidden,
44 static cl::opt<bool> OptEnableConst("commgep-const", cl::init(true),
45 cl::Hidden, cl::ZeroOrMore);
48 void initializeHexagonCommonGEPPass(PassRegistry&);
53 typedef std::set<GepNode*> NodeSet;
54 typedef std::map<GepNode*,Value*> NodeToValueMap;
55 typedef std::vector<GepNode*> NodeVect;
56 typedef std::map<GepNode*,NodeVect> NodeChildrenMap;
57 typedef std::set<Use*> UseSet;
58 typedef std::map<GepNode*,UseSet> NodeToUsesMap;
60 // Numbering map for gep nodes. Used to keep track of ordering for
63 NodeOrdering() : LastNum(0) {}
65 void insert(const GepNode *N) { Map.insert(std::make_pair(N, ++LastNum)); }
66 void clear() { Map.clear(); }
68 bool operator()(const GepNode *N1, const GepNode *N2) const {
69 auto F1 = Map.find(N1), F2 = Map.find(N2);
70 assert(F1 != Map.end() && F2 != Map.end());
71 return F1->second < F2->second;
75 std::map<const GepNode *, unsigned> Map;
79 class HexagonCommonGEP : public FunctionPass {
82 HexagonCommonGEP() : FunctionPass(ID) {
83 initializeHexagonCommonGEPPass(*PassRegistry::getPassRegistry());
85 virtual bool runOnFunction(Function &F);
86 virtual const char *getPassName() const {
87 return "Hexagon Common GEP";
90 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
91 AU.addRequired<DominatorTreeWrapperPass>();
92 AU.addPreserved<DominatorTreeWrapperPass>();
93 AU.addRequired<PostDominatorTree>();
94 AU.addPreserved<PostDominatorTree>();
95 AU.addRequired<LoopInfoWrapperPass>();
96 AU.addPreserved<LoopInfoWrapperPass>();
97 FunctionPass::getAnalysisUsage(AU);
101 typedef std::map<Value*,GepNode*> ValueToNodeMap;
102 typedef std::vector<Value*> ValueVect;
103 typedef std::map<GepNode*,ValueVect> NodeToValuesMap;
105 void getBlockTraversalOrder(BasicBlock *Root, ValueVect &Order);
106 bool isHandledGepForm(GetElementPtrInst *GepI);
107 void processGepInst(GetElementPtrInst *GepI, ValueToNodeMap &NM);
111 BasicBlock *recalculatePlacement(GepNode *Node, NodeChildrenMap &NCM,
112 NodeToValueMap &Loc);
113 BasicBlock *recalculatePlacementRec(GepNode *Node, NodeChildrenMap &NCM,
114 NodeToValueMap &Loc);
115 bool isInvariantIn(Value *Val, Loop *L);
116 bool isInvariantIn(GepNode *Node, Loop *L);
117 bool isInMainPath(BasicBlock *B, Loop *L);
118 BasicBlock *adjustForInvariance(GepNode *Node, NodeChildrenMap &NCM,
119 NodeToValueMap &Loc);
120 void separateChainForNode(GepNode *Node, Use *U, NodeToValueMap &Loc);
121 void separateConstantChains(GepNode *Node, NodeChildrenMap &NCM,
122 NodeToValueMap &Loc);
123 void computeNodePlacement(NodeToValueMap &Loc);
125 Value *fabricateGEP(NodeVect &NA, BasicBlock::iterator At,
127 void getAllUsersForNode(GepNode *Node, ValueVect &Values,
128 NodeChildrenMap &NCM);
129 void materialize(NodeToValueMap &Loc);
131 void removeDeadCode();
135 NodeOrdering NodeOrder; // Node ordering, for deterministic behavior.
136 SpecificBumpPtrAllocator<GepNode> *Mem;
140 PostDominatorTree *PDT;
146 char HexagonCommonGEP::ID = 0;
147 INITIALIZE_PASS_BEGIN(HexagonCommonGEP, "hcommgep", "Hexagon Common GEP",
149 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
150 INITIALIZE_PASS_DEPENDENCY(PostDominatorTree)
151 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
152 INITIALIZE_PASS_END(HexagonCommonGEP, "hcommgep", "Hexagon Common GEP",
170 Type *PTy; // Type of the pointer operand.
172 GepNode() : Flags(0), Parent(0), Idx(0), PTy(0) {}
173 GepNode(const GepNode *N) : Flags(N->Flags), Idx(N->Idx), PTy(N->PTy) {
175 BaseVal = N->BaseVal;
179 friend raw_ostream &operator<< (raw_ostream &OS, const GepNode &GN);
183 Type *next_type(Type *Ty, Value *Idx) {
185 if (!Ty->isStructTy()) {
186 Type *NexTy = cast<SequentialType>(Ty)->getElementType();
189 // Otherwise it is a struct type.
190 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
191 assert(CI && "Struct type with non-constant index");
192 int64_t i = CI->getValue().getSExtValue();
193 Type *NextTy = cast<StructType>(Ty)->getElementType(i);
198 raw_ostream &operator<< (raw_ostream &OS, const GepNode &GN) {
201 if (GN.Flags & GepNode::Root) {
205 if (GN.Flags & GepNode::Internal) {
211 if (GN.Flags & GepNode::Used) {
218 if (GN.Flags & GepNode::Root)
219 OS << "BaseVal:" << GN.BaseVal->getName() << '(' << GN.BaseVal << ')';
221 OS << "Parent:" << GN.Parent;
224 if (ConstantInt *CI = dyn_cast<ConstantInt>(GN.Idx))
225 OS << CI->getValue().getSExtValue();
226 else if (GN.Idx->hasName())
227 OS << GN.Idx->getName();
229 OS << "<anon> =" << *GN.Idx;
232 if (GN.PTy->isStructTy()) {
233 StructType *STy = cast<StructType>(GN.PTy);
234 if (!STy->isLiteral())
235 OS << GN.PTy->getStructName();
237 OS << "<anon-struct>:" << *STy;
246 template <typename NodeContainer>
247 void dump_node_container(raw_ostream &OS, const NodeContainer &S) {
248 typedef typename NodeContainer::const_iterator const_iterator;
249 for (const_iterator I = S.begin(), E = S.end(); I != E; ++I)
250 OS << *I << ' ' << **I << '\n';
253 raw_ostream &operator<< (raw_ostream &OS,
254 const NodeVect &S) LLVM_ATTRIBUTE_UNUSED;
255 raw_ostream &operator<< (raw_ostream &OS, const NodeVect &S) {
256 dump_node_container(OS, S);
261 raw_ostream &operator<< (raw_ostream &OS,
262 const NodeToUsesMap &M) LLVM_ATTRIBUTE_UNUSED;
263 raw_ostream &operator<< (raw_ostream &OS, const NodeToUsesMap &M){
264 typedef NodeToUsesMap::const_iterator const_iterator;
265 for (const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
266 const UseSet &Us = I->second;
267 OS << I->first << " -> #" << Us.size() << '{';
268 for (UseSet::const_iterator J = Us.begin(), F = Us.end(); J != F; ++J) {
269 User *R = (*J)->getUser();
271 OS << ' ' << R->getName();
273 OS << " <?>(" << *R << ')';
282 in_set(const NodeSet &S) : NS(S) {}
283 bool operator() (GepNode *N) const {
284 return NS.find(N) != NS.end();
292 inline void *operator new(size_t, SpecificBumpPtrAllocator<GepNode> &A) {
297 void HexagonCommonGEP::getBlockTraversalOrder(BasicBlock *Root,
299 // Compute block ordering for a typical DT-based traversal of the flow
300 // graph: "before visiting a block, all of its dominators must have been
303 Order.push_back(Root);
304 DomTreeNode *DTN = DT->getNode(Root);
305 typedef GraphTraits<DomTreeNode*> GTN;
306 typedef GTN::ChildIteratorType Iter;
307 for (Iter I = GTN::child_begin(DTN), E = GTN::child_end(DTN); I != E; ++I)
308 getBlockTraversalOrder((*I)->getBlock(), Order);
312 bool HexagonCommonGEP::isHandledGepForm(GetElementPtrInst *GepI) {
314 if (!GepI->getType()->isPointerTy())
316 // No GEPs without any indices. (Is this possible?)
317 if (GepI->idx_begin() == GepI->idx_end())
323 void HexagonCommonGEP::processGepInst(GetElementPtrInst *GepI,
324 ValueToNodeMap &NM) {
325 DEBUG(dbgs() << "Visiting GEP: " << *GepI << '\n');
326 GepNode *N = new (*Mem) GepNode;
327 Value *PtrOp = GepI->getPointerOperand();
328 ValueToNodeMap::iterator F = NM.find(PtrOp);
331 N->Flags |= GepNode::Root;
333 // If PtrOp was a GEP instruction, it must have already been processed.
334 // The ValueToNodeMap entry for it is the last gep node in the generated
335 // chain. Link to it here.
336 N->Parent = F->second;
338 N->PTy = PtrOp->getType();
339 N->Idx = *GepI->idx_begin();
341 // Collect the list of users of this GEP instruction. Will add it to the
342 // last node created for it.
344 for (Value::user_iterator UI = GepI->user_begin(), UE = GepI->user_end();
346 // Check if this gep is used by anything other than other geps that
348 if (isa<GetElementPtrInst>(*UI)) {
349 GetElementPtrInst *UserG = cast<GetElementPtrInst>(*UI);
350 if (isHandledGepForm(UserG))
353 Us.insert(&UI.getUse());
358 // Skip the first index operand, since we only handle 0. This dereferences
359 // the pointer operand.
361 Type *PtrTy = cast<PointerType>(PtrOp->getType())->getElementType();
362 for (User::op_iterator OI = GepI->idx_begin()+1, OE = GepI->idx_end();
365 GepNode *Nx = new (*Mem) GepNode;
366 Nx->Parent = PN; // Link Nx to the previous node.
367 Nx->Flags |= GepNode::Internal;
371 NodeOrder.insert(Nx);
374 PtrTy = next_type(PtrTy, Op);
377 // After last node has been created, update the use information.
379 PN->Flags |= GepNode::Used;
380 Uses[PN].insert(Us.begin(), Us.end());
383 // Link the last node with the originating GEP instruction. This is to
384 // help with linking chained GEP instructions.
385 NM.insert(std::make_pair(GepI, PN));
389 void HexagonCommonGEP::collect() {
390 // Establish depth-first traversal order of the dominator tree.
392 getBlockTraversalOrder(&Fn->front(), BO);
394 // The creation of gep nodes requires DT-traversal. When processing a GEP
395 // instruction that uses another GEP instruction as the base pointer, the
396 // gep node for the base pointer should already exist.
398 for (ValueVect::iterator I = BO.begin(), E = BO.end(); I != E; ++I) {
399 BasicBlock *B = cast<BasicBlock>(*I);
400 for (BasicBlock::iterator J = B->begin(), F = B->end(); J != F; ++J) {
401 if (!isa<GetElementPtrInst>(J))
403 GetElementPtrInst *GepI = cast<GetElementPtrInst>(J);
404 if (isHandledGepForm(GepI))
405 processGepInst(GepI, NM);
409 DEBUG(dbgs() << "Gep nodes after initial collection:\n" << Nodes);
414 void invert_find_roots(const NodeVect &Nodes, NodeChildrenMap &NCM,
416 typedef NodeVect::const_iterator const_iterator;
417 for (const_iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
419 if (N->Flags & GepNode::Root) {
423 GepNode *PN = N->Parent;
424 NCM[PN].push_back(N);
428 void nodes_for_root(GepNode *Root, NodeChildrenMap &NCM, NodeSet &Nodes) {
430 Work.push_back(Root);
433 while (!Work.empty()) {
434 NodeVect::iterator First = Work.begin();
437 NodeChildrenMap::iterator CF = NCM.find(N);
438 if (CF != NCM.end()) {
439 Work.insert(Work.end(), CF->second.begin(), CF->second.end());
440 Nodes.insert(CF->second.begin(), CF->second.end());
448 typedef std::set<NodeSet> NodeSymRel;
449 typedef std::pair<GepNode*,GepNode*> NodePair;
450 typedef std::set<NodePair> NodePairSet;
452 const NodeSet *node_class(GepNode *N, NodeSymRel &Rel) {
453 for (NodeSymRel::iterator I = Rel.begin(), E = Rel.end(); I != E; ++I)
459 // Create an ordered pair of GepNode pointers. The pair will be used in
460 // determining equality. The only purpose of the ordering is to eliminate
461 // duplication due to the commutativity of equality/non-equality.
462 NodePair node_pair(GepNode *N1, GepNode *N2) {
463 uintptr_t P1 = uintptr_t(N1), P2 = uintptr_t(N2);
465 return std::make_pair(N1, N2);
466 return std::make_pair(N2, N1);
469 unsigned node_hash(GepNode *N) {
470 // Include everything except flags and parent.
472 ID.AddPointer(N->Idx);
473 ID.AddPointer(N->PTy);
474 return ID.ComputeHash();
477 bool node_eq(GepNode *N1, GepNode *N2, NodePairSet &Eq, NodePairSet &Ne) {
478 // Don't cache the result for nodes with different hashes. The hash
479 // comparison is fast enough.
480 if (node_hash(N1) != node_hash(N2))
483 NodePair NP = node_pair(N1, N2);
484 NodePairSet::iterator FEq = Eq.find(NP);
487 NodePairSet::iterator FNe = Ne.find(NP);
490 // Not previously compared.
491 bool Root1 = N1->Flags & GepNode::Root;
492 bool Root2 = N2->Flags & GepNode::Root;
493 NodePair P = node_pair(N1, N2);
494 // If the Root flag has different values, the nodes are different.
495 // If both nodes are root nodes, but their base pointers differ,
496 // they are different.
497 if (Root1 != Root2 || (Root1 && N1->BaseVal != N2->BaseVal)) {
501 // Here the root flags are identical, and for root nodes the
502 // base pointers are equal, so the root nodes are equal.
503 // For non-root nodes, compare their parent nodes.
504 if (Root1 || node_eq(N1->Parent, N2->Parent, Eq, Ne)) {
513 void HexagonCommonGEP::common() {
514 // The essence of this commoning is finding gep nodes that are equal.
515 // To do this we need to compare all pairs of nodes. To save time,
516 // first, partition the set of all nodes into sets of potentially equal
517 // nodes, and then compare pairs from within each partition.
518 typedef std::map<unsigned,NodeSet> NodeSetMap;
521 for (NodeVect::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
523 unsigned H = node_hash(N);
524 MaybeEq[H].insert(N);
527 // Compute the equivalence relation for the gep nodes. Use two caches,
528 // one for equality and the other for non-equality.
529 NodeSymRel EqRel; // Equality relation (as set of equivalence classes).
530 NodePairSet Eq, Ne; // Caches.
531 for (NodeSetMap::iterator I = MaybeEq.begin(), E = MaybeEq.end();
533 NodeSet &S = I->second;
534 for (NodeSet::iterator NI = S.begin(), NE = S.end(); NI != NE; ++NI) {
536 // If node already has a class, then the class must have been created
537 // in a prior iteration of this loop. Since equality is transitive,
538 // nothing more will be added to that class, so skip it.
539 if (node_class(N, EqRel))
542 // Create a new class candidate now.
544 for (NodeSet::iterator NJ = std::next(NI); NJ != NE; ++NJ)
545 if (node_eq(N, *NJ, Eq, Ne))
547 // If Tmp is empty, N would be the only element in it. Don't bother
548 // creating a class for it then.
550 C.insert(N); // Finalize the set before adding it to the relation.
551 std::pair<NodeSymRel::iterator, bool> Ins = EqRel.insert(C);
553 assert(Ins.second && "Cannot add a class");
559 dbgs() << "Gep node equality:\n";
560 for (NodePairSet::iterator I = Eq.begin(), E = Eq.end(); I != E; ++I)
561 dbgs() << "{ " << I->first << ", " << I->second << " }\n";
563 dbgs() << "Gep equivalence classes:\n";
564 for (NodeSymRel::iterator I = EqRel.begin(), E = EqRel.end(); I != E; ++I) {
566 const NodeSet &S = *I;
567 for (NodeSet::const_iterator J = S.begin(), F = S.end(); J != F; ++J) {
577 // Create a projection from a NodeSet to the minimal element in it.
578 typedef std::map<const NodeSet*,GepNode*> ProjMap;
580 for (NodeSymRel::iterator I = EqRel.begin(), E = EqRel.end(); I != E; ++I) {
581 const NodeSet &S = *I;
582 GepNode *Min = *std::min_element(S.begin(), S.end(), NodeOrder);
583 std::pair<ProjMap::iterator,bool> Ins = PM.insert(std::make_pair(&S, Min));
585 assert(Ins.second && "Cannot add minimal element");
587 // Update the min element's flags, and user list.
589 UseSet &MinUs = Uses[Min];
590 for (NodeSet::iterator J = S.begin(), F = S.end(); J != F; ++J) {
592 uint32_t NF = N->Flags;
593 // If N is used, append all original values of N to the list of
594 // original values of Min.
595 if (NF & GepNode::Used)
596 MinUs.insert(Uses[N].begin(), Uses[N].end());
602 // The collected flags should include all the flags from the min element.
603 assert((Min->Flags & Flags) == Min->Flags);
607 // Commoning: for each non-root gep node, replace "Parent" with the
608 // selected (minimum) node from the corresponding equivalence class.
609 // If a given parent does not have an equivalence class, leave it
610 // unchanged (it means that it's the only element in its class).
611 for (NodeVect::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
613 if (N->Flags & GepNode::Root)
615 const NodeSet *PC = node_class(N->Parent, EqRel);
618 ProjMap::iterator F = PM.find(PC);
621 // Found a replacement, use it.
622 GepNode *Rep = F->second;
626 DEBUG(dbgs() << "Gep nodes after commoning:\n" << Nodes);
628 // Finally, erase the nodes that are no longer used.
630 for (NodeVect::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
632 const NodeSet *PC = node_class(N, EqRel);
635 ProjMap::iterator F = PM.find(PC);
643 NodeVect::iterator NewE = std::remove_if(Nodes.begin(), Nodes.end(),
645 Nodes.resize(std::distance(Nodes.begin(), NewE));
647 DEBUG(dbgs() << "Gep nodes after post-commoning cleanup:\n" << Nodes);
652 template <typename T>
653 BasicBlock *nearest_common_dominator(DominatorTree *DT, T &Blocks) {
655 dbgs() << "NCD of {";
656 for (typename T::iterator I = Blocks.begin(), E = Blocks.end();
660 BasicBlock *B = cast<BasicBlock>(*I);
661 dbgs() << ' ' << B->getName();
666 // Allow null basic blocks in Blocks. In such cases, return 0.
667 typename T::iterator I = Blocks.begin(), E = Blocks.end();
670 BasicBlock *Dom = cast<BasicBlock>(*I);
672 BasicBlock *B = cast_or_null<BasicBlock>(*I);
673 Dom = B ? DT->findNearestCommonDominator(Dom, B) : 0;
677 DEBUG(dbgs() << "computed:" << Dom->getName() << '\n');
681 template <typename T>
682 BasicBlock *nearest_common_dominatee(DominatorTree *DT, T &Blocks) {
683 // If two blocks, A and B, dominate a block C, then A dominates B,
685 typename T::iterator I = Blocks.begin(), E = Blocks.end();
686 // Find the first non-null block.
687 while (I != E && !*I)
690 return DT->getRoot();
691 BasicBlock *DomB = cast<BasicBlock>(*I);
695 BasicBlock *B = cast<BasicBlock>(*I);
696 if (DT->dominates(B, DomB))
698 if (!DT->dominates(DomB, B))
705 // Find the first use in B of any value from Values. If no such use,
707 template <typename T>
708 BasicBlock::iterator first_use_of_in_block(T &Values, BasicBlock *B) {
709 BasicBlock::iterator FirstUse = B->end(), BEnd = B->end();
710 typedef typename T::iterator iterator;
711 for (iterator I = Values.begin(), E = Values.end(); I != E; ++I) {
713 // If V is used in a PHI node, the use belongs to the incoming block,
714 // not the block with the PHI node. In the incoming block, the use
715 // would be considered as being at the end of it, so it cannot
716 // influence the position of the first use (which is assumed to be
717 // at the end to start with).
720 if (!isa<Instruction>(V))
722 Instruction *In = cast<Instruction>(V);
723 if (In->getParent() != B)
725 BasicBlock::iterator It = In->getIterator();
726 if (std::distance(FirstUse, BEnd) < std::distance(It, BEnd))
732 bool is_empty(const BasicBlock *B) {
733 return B->empty() || (&*B->begin() == B->getTerminator());
738 BasicBlock *HexagonCommonGEP::recalculatePlacement(GepNode *Node,
739 NodeChildrenMap &NCM, NodeToValueMap &Loc) {
740 DEBUG(dbgs() << "Loc for node:" << Node << '\n');
741 // Recalculate the placement for Node, assuming that the locations of
742 // its children in Loc are valid.
743 // Return 0 if there is no valid placement for Node (for example, it
744 // uses an index value that is not available at the location required
745 // to dominate all children, etc.).
747 // Find the nearest common dominator for:
748 // - all users, if the node is used, and
751 if (Node->Flags & GepNode::Used) {
752 // Append all blocks with uses of the original values to the
754 NodeToUsesMap::iterator UF = Uses.find(Node);
755 assert(UF != Uses.end() && "Used node with no use information");
756 UseSet &Us = UF->second;
757 for (UseSet::iterator I = Us.begin(), E = Us.end(); I != E; ++I) {
759 User *R = U->getUser();
760 if (!isa<Instruction>(R))
762 BasicBlock *PB = isa<PHINode>(R)
763 ? cast<PHINode>(R)->getIncomingBlock(*U)
764 : cast<Instruction>(R)->getParent();
768 // Append the location of each child.
769 NodeChildrenMap::iterator CF = NCM.find(Node);
770 if (CF != NCM.end()) {
771 NodeVect &Cs = CF->second;
772 for (NodeVect::iterator I = Cs.begin(), E = Cs.end(); I != E; ++I) {
774 NodeToValueMap::iterator LF = Loc.find(CN);
775 // If the child is only used in GEP instructions (i.e. is not used in
776 // non-GEP instructions), the nearest dominator computed for it may
777 // have been null. In such case it won't have a location available.
780 Bs.push_back(LF->second);
784 BasicBlock *DomB = nearest_common_dominator(DT, Bs);
787 // Check if the index used by Node dominates the computed dominator.
788 Instruction *IdxI = dyn_cast<Instruction>(Node->Idx);
789 if (IdxI && !DT->dominates(IdxI->getParent(), DomB))
792 // Avoid putting nodes into empty blocks.
793 while (is_empty(DomB)) {
794 DomTreeNode *N = (*DT)[DomB]->getIDom();
797 DomB = N->getBlock();
800 // Otherwise, DomB is fine. Update the location map.
806 BasicBlock *HexagonCommonGEP::recalculatePlacementRec(GepNode *Node,
807 NodeChildrenMap &NCM, NodeToValueMap &Loc) {
808 DEBUG(dbgs() << "LocRec begin for node:" << Node << '\n');
809 // Recalculate the placement of Node, after recursively recalculating the
810 // placements of all its children.
811 NodeChildrenMap::iterator CF = NCM.find(Node);
812 if (CF != NCM.end()) {
813 NodeVect &Cs = CF->second;
814 for (NodeVect::iterator I = Cs.begin(), E = Cs.end(); I != E; ++I)
815 recalculatePlacementRec(*I, NCM, Loc);
817 BasicBlock *LB = recalculatePlacement(Node, NCM, Loc);
818 DEBUG(dbgs() << "LocRec end for node:" << Node << '\n');
823 bool HexagonCommonGEP::isInvariantIn(Value *Val, Loop *L) {
824 if (isa<Constant>(Val) || isa<Argument>(Val))
826 Instruction *In = dyn_cast<Instruction>(Val);
829 BasicBlock *HdrB = L->getHeader(), *DefB = In->getParent();
830 return DT->properlyDominates(DefB, HdrB);
834 bool HexagonCommonGEP::isInvariantIn(GepNode *Node, Loop *L) {
835 if (Node->Flags & GepNode::Root)
836 if (!isInvariantIn(Node->BaseVal, L))
838 return isInvariantIn(Node->Idx, L);
842 bool HexagonCommonGEP::isInMainPath(BasicBlock *B, Loop *L) {
843 BasicBlock *HB = L->getHeader();
844 BasicBlock *LB = L->getLoopLatch();
845 // B must post-dominate the loop header or dominate the loop latch.
846 if (PDT->dominates(B, HB))
848 if (LB && DT->dominates(B, LB))
855 BasicBlock *preheader(DominatorTree *DT, Loop *L) {
856 if (BasicBlock *PH = L->getLoopPreheader())
860 DomTreeNode *DN = DT->getNode(L->getHeader());
863 return DN->getIDom()->getBlock();
868 BasicBlock *HexagonCommonGEP::adjustForInvariance(GepNode *Node,
869 NodeChildrenMap &NCM, NodeToValueMap &Loc) {
870 // Find the "topmost" location for Node: it must be dominated by both,
871 // its parent (or the BaseVal, if it's a root node), and by the index
874 if (Node->Flags & GepNode::Root) {
875 if (Instruction *PIn = dyn_cast<Instruction>(Node->BaseVal))
876 Bs.push_back(PIn->getParent());
878 Bs.push_back(Loc[Node->Parent]);
880 if (Instruction *IIn = dyn_cast<Instruction>(Node->Idx))
881 Bs.push_back(IIn->getParent());
882 BasicBlock *TopB = nearest_common_dominatee(DT, Bs);
884 // Traverse the loop nest upwards until we find a loop in which Node
885 // is no longer invariant, or until we get to the upper limit of Node's
886 // placement. The traversal will also stop when a suitable "preheader"
887 // cannot be found for a given loop. The "preheader" may actually be
888 // a regular block outside of the loop (i.e. not guarded), in which case
889 // the Node will be speculated.
890 // For nodes that are not in the main path of the containing loop (i.e.
891 // are not executed in each iteration), do not move them out of the loop.
892 BasicBlock *LocB = cast_or_null<BasicBlock>(Loc[Node]);
894 Loop *Lp = LI->getLoopFor(LocB);
896 if (!isInvariantIn(Node, Lp) || !isInMainPath(LocB, Lp))
898 BasicBlock *NewLoc = preheader(DT, Lp);
899 if (!NewLoc || !DT->dominates(TopB, NewLoc))
901 Lp = Lp->getParentLoop();
907 // Recursively compute the locations of all children nodes.
908 NodeChildrenMap::iterator CF = NCM.find(Node);
909 if (CF != NCM.end()) {
910 NodeVect &Cs = CF->second;
911 for (NodeVect::iterator I = Cs.begin(), E = Cs.end(); I != E; ++I)
912 adjustForInvariance(*I, NCM, Loc);
919 struct LocationAsBlock {
920 LocationAsBlock(const NodeToValueMap &L) : Map(L) {}
921 const NodeToValueMap ⤅
924 raw_ostream &operator<< (raw_ostream &OS,
925 const LocationAsBlock &Loc) LLVM_ATTRIBUTE_UNUSED ;
926 raw_ostream &operator<< (raw_ostream &OS, const LocationAsBlock &Loc) {
927 for (NodeToValueMap::const_iterator I = Loc.Map.begin(), E = Loc.Map.end();
929 OS << I->first << " -> ";
930 BasicBlock *B = cast<BasicBlock>(I->second);
931 OS << B->getName() << '(' << B << ')';
937 inline bool is_constant(GepNode *N) {
938 return isa<ConstantInt>(N->Idx);
943 void HexagonCommonGEP::separateChainForNode(GepNode *Node, Use *U,
944 NodeToValueMap &Loc) {
945 User *R = U->getUser();
946 DEBUG(dbgs() << "Separating chain for node (" << Node << ") user: "
948 BasicBlock *PB = cast<Instruction>(R)->getParent();
951 GepNode *C = 0, *NewNode = 0;
952 while (is_constant(N) && !(N->Flags & GepNode::Root)) {
953 // XXX if (single-use) dont-replicate;
954 GepNode *NewN = new (*Mem) GepNode(N);
955 Nodes.push_back(NewN);
960 NewN->Flags &= ~GepNode::Used;
969 // Move over all uses that share the same user as U from Node to NewNode.
970 NodeToUsesMap::iterator UF = Uses.find(Node);
971 assert(UF != Uses.end());
972 UseSet &Us = UF->second;
974 for (UseSet::iterator I = Us.begin(); I != Us.end(); ) {
975 User *S = (*I)->getUser();
976 UseSet::iterator Nx = std::next(I);
984 Node->Flags &= ~GepNode::Used;
988 // Should at least have U in NewUs.
989 NewNode->Flags |= GepNode::Used;
990 DEBUG(dbgs() << "new node: " << NewNode << " " << *NewNode << '\n');
991 assert(!NewUs.empty());
992 Uses[NewNode] = NewUs;
996 void HexagonCommonGEP::separateConstantChains(GepNode *Node,
997 NodeChildrenMap &NCM, NodeToValueMap &Loc) {
998 // First approximation: extract all chains.
1000 nodes_for_root(Node, NCM, Ns);
1002 DEBUG(dbgs() << "Separating constant chains for node: " << Node << '\n');
1003 // Collect all used nodes together with the uses from loads and stores,
1004 // where the GEP node could be folded into the load/store instruction.
1005 NodeToUsesMap FNs; // Foldable nodes.
1006 for (NodeSet::iterator I = Ns.begin(), E = Ns.end(); I != E; ++I) {
1008 if (!(N->Flags & GepNode::Used))
1010 NodeToUsesMap::iterator UF = Uses.find(N);
1011 assert(UF != Uses.end());
1012 UseSet &Us = UF->second;
1013 // Loads/stores that use the node N.
1015 for (UseSet::iterator J = Us.begin(), F = Us.end(); J != F; ++J) {
1017 User *R = U->getUser();
1018 // We're interested in uses that provide the address. It can happen
1019 // that the value may also be provided via GEP, but we won't handle
1020 // those cases here for now.
1021 if (LoadInst *Ld = dyn_cast<LoadInst>(R)) {
1022 unsigned PtrX = LoadInst::getPointerOperandIndex();
1023 if (&Ld->getOperandUse(PtrX) == U)
1025 } else if (StoreInst *St = dyn_cast<StoreInst>(R)) {
1026 unsigned PtrX = StoreInst::getPointerOperandIndex();
1027 if (&St->getOperandUse(PtrX) == U)
1031 // Even if the total use count is 1, separating the chain may still be
1032 // beneficial, since the constant chain may be longer than the GEP alone
1033 // would be (e.g. if the parent node has a constant index and also has
1036 FNs.insert(std::make_pair(N, LSs));
1039 DEBUG(dbgs() << "Nodes with foldable users:\n" << FNs);
1041 for (NodeToUsesMap::iterator I = FNs.begin(), E = FNs.end(); I != E; ++I) {
1042 GepNode *N = I->first;
1043 UseSet &Us = I->second;
1044 for (UseSet::iterator J = Us.begin(), F = Us.end(); J != F; ++J)
1045 separateChainForNode(N, *J, Loc);
1050 void HexagonCommonGEP::computeNodePlacement(NodeToValueMap &Loc) {
1051 // Compute the inverse of the Node.Parent links. Also, collect the set
1053 NodeChildrenMap NCM;
1055 invert_find_roots(Nodes, NCM, Roots);
1057 // Compute the initial placement determined by the users' locations, and
1058 // the locations of the child nodes.
1059 for (NodeVect::iterator I = Roots.begin(), E = Roots.end(); I != E; ++I)
1060 recalculatePlacementRec(*I, NCM, Loc);
1062 DEBUG(dbgs() << "Initial node placement:\n" << LocationAsBlock(Loc));
1065 for (NodeVect::iterator I = Roots.begin(), E = Roots.end(); I != E; ++I)
1066 adjustForInvariance(*I, NCM, Loc);
1068 DEBUG(dbgs() << "Node placement after adjustment for invariance:\n"
1069 << LocationAsBlock(Loc));
1071 if (OptEnableConst) {
1072 for (NodeVect::iterator I = Roots.begin(), E = Roots.end(); I != E; ++I)
1073 separateConstantChains(*I, NCM, Loc);
1075 DEBUG(dbgs() << "Node use information:\n" << Uses);
1077 // At the moment, there is no further refinement of the initial placement.
1078 // Such a refinement could include splitting the nodes if they are placed
1079 // too far from some of its users.
1081 DEBUG(dbgs() << "Final node placement:\n" << LocationAsBlock(Loc));
1085 Value *HexagonCommonGEP::fabricateGEP(NodeVect &NA, BasicBlock::iterator At,
1087 DEBUG(dbgs() << "Fabricating GEP in " << LocB->getName()
1088 << " for nodes:\n" << NA);
1089 unsigned Num = NA.size();
1090 GepNode *RN = NA[0];
1091 assert((RN->Flags & GepNode::Root) && "Creating GEP for non-root");
1094 Value *Input = RN->BaseVal;
1095 Value **IdxList = new Value*[Num+1];
1099 // If the type of the input of the first node is not a pointer,
1100 // we need to add an artificial i32 0 to the indices (because the
1101 // actual input in the IR will be a pointer).
1102 if (!NA[nax]->PTy->isPointerTy()) {
1103 Type *Int32Ty = Type::getInt32Ty(*Ctx);
1104 IdxList[IdxC++] = ConstantInt::get(Int32Ty, 0);
1107 // Keep adding indices from NA until we have to stop and generate
1108 // an "intermediate" GEP.
1109 while (++nax <= Num) {
1110 GepNode *N = NA[nax-1];
1111 IdxList[IdxC++] = N->Idx;
1113 // We have to stop, if the expected type of the output of this node
1114 // is not the same as the input type of the next node.
1115 Type *NextTy = next_type(N->PTy, N->Idx);
1116 if (NextTy != NA[nax]->PTy)
1120 ArrayRef<Value*> A(IdxList, IdxC);
1121 Type *InpTy = Input->getType();
1122 Type *ElTy = cast<PointerType>(InpTy->getScalarType())->getElementType();
1123 NewInst = GetElementPtrInst::Create(ElTy, Input, A, "cgep", &*At);
1124 DEBUG(dbgs() << "new GEP: " << *NewInst << '\n');
1126 } while (nax <= Num);
1133 void HexagonCommonGEP::getAllUsersForNode(GepNode *Node, ValueVect &Values,
1134 NodeChildrenMap &NCM) {
1136 Work.push_back(Node);
1138 while (!Work.empty()) {
1139 NodeVect::iterator First = Work.begin();
1140 GepNode *N = *First;
1142 if (N->Flags & GepNode::Used) {
1143 NodeToUsesMap::iterator UF = Uses.find(N);
1144 assert(UF != Uses.end() && "No use information for used node");
1145 UseSet &Us = UF->second;
1146 for (UseSet::iterator I = Us.begin(), E = Us.end(); I != E; ++I)
1147 Values.push_back((*I)->getUser());
1149 NodeChildrenMap::iterator CF = NCM.find(N);
1150 if (CF != NCM.end()) {
1151 NodeVect &Cs = CF->second;
1152 Work.insert(Work.end(), Cs.begin(), Cs.end());
1158 void HexagonCommonGEP::materialize(NodeToValueMap &Loc) {
1159 DEBUG(dbgs() << "Nodes before materialization:\n" << Nodes << '\n');
1160 NodeChildrenMap NCM;
1162 // Compute the inversion again, since computing placement could alter
1163 // "parent" relation between nodes.
1164 invert_find_roots(Nodes, NCM, Roots);
1166 while (!Roots.empty()) {
1167 NodeVect::iterator First = Roots.begin();
1168 GepNode *Root = *First, *Last = *First;
1171 NodeVect NA; // Nodes to assemble.
1172 // Append to NA all child nodes up to (and including) the first child
1174 // (1) has more than 1 child, or
1176 // (3) has a child located in a different block.
1177 bool LastUsed = false;
1178 unsigned LastCN = 0;
1179 // The location may be null if the computation failed (it can legitimately
1180 // happen for nodes created from dead GEPs).
1181 Value *LocV = Loc[Last];
1184 BasicBlock *LastB = cast<BasicBlock>(LocV);
1187 LastUsed = (Last->Flags & GepNode::Used);
1190 NodeChildrenMap::iterator CF = NCM.find(Last);
1191 LastCN = (CF != NCM.end()) ? CF->second.size() : 0;
1194 GepNode *Child = CF->second.front();
1195 BasicBlock *ChildB = cast_or_null<BasicBlock>(Loc[Child]);
1196 if (ChildB != 0 && LastB != ChildB)
1201 BasicBlock::iterator InsertAt = LastB->getTerminator()->getIterator();
1202 if (LastUsed || LastCN > 0) {
1204 getAllUsersForNode(Root, Urs, NCM);
1205 BasicBlock::iterator FirstUse = first_use_of_in_block(Urs, LastB);
1206 if (FirstUse != LastB->end())
1207 InsertAt = FirstUse;
1210 // Generate a new instruction for NA.
1211 Value *NewInst = fabricateGEP(NA, InsertAt, LastB);
1213 // Convert all the children of Last node into roots, and append them
1214 // to the Roots list.
1216 NodeVect &Cs = NCM[Last];
1217 for (NodeVect::iterator I = Cs.begin(), E = Cs.end(); I != E; ++I) {
1219 CN->Flags &= ~GepNode::Internal;
1220 CN->Flags |= GepNode::Root;
1221 CN->BaseVal = NewInst;
1222 Roots.push_back(CN);
1226 // Lastly, if the Last node was used, replace all uses with the new GEP.
1227 // The uses reference the original GEP values.
1229 NodeToUsesMap::iterator UF = Uses.find(Last);
1230 assert(UF != Uses.end() && "No use information found");
1231 UseSet &Us = UF->second;
1232 for (UseSet::iterator I = Us.begin(), E = Us.end(); I != E; ++I) {
1241 void HexagonCommonGEP::removeDeadCode() {
1243 BO.push_back(&Fn->front());
1245 for (unsigned i = 0; i < BO.size(); ++i) {
1246 BasicBlock *B = cast<BasicBlock>(BO[i]);
1247 DomTreeNode *N = DT->getNode(B);
1248 typedef GraphTraits<DomTreeNode*> GTN;
1249 typedef GTN::ChildIteratorType Iter;
1250 for (Iter I = GTN::child_begin(N), E = GTN::child_end(N); I != E; ++I)
1251 BO.push_back((*I)->getBlock());
1254 for (unsigned i = BO.size(); i > 0; --i) {
1255 BasicBlock *B = cast<BasicBlock>(BO[i-1]);
1256 BasicBlock::InstListType &IL = B->getInstList();
1257 typedef BasicBlock::InstListType::reverse_iterator reverse_iterator;
1259 for (reverse_iterator I = IL.rbegin(), E = IL.rend(); I != E; ++I)
1261 for (ValueVect::iterator I = Ins.begin(), E = Ins.end(); I != E; ++I) {
1262 Instruction *In = cast<Instruction>(*I);
1263 if (isInstructionTriviallyDead(In))
1264 In->eraseFromParent();
1270 bool HexagonCommonGEP::runOnFunction(Function &F) {
1271 // For now bail out on C++ exception handling.
1272 for (Function::iterator A = F.begin(), Z = F.end(); A != Z; ++A)
1273 for (BasicBlock::iterator I = A->begin(), E = A->end(); I != E; ++I)
1274 if (isa<InvokeInst>(I) || isa<LandingPadInst>(I))
1278 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1279 PDT = &getAnalysis<PostDominatorTree>();
1280 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1281 Ctx = &F.getContext();
1287 SpecificBumpPtrAllocator<GepNode> Allocator;
1294 computeNodePlacement(Loc);
1299 // Run this only when expensive checks are enabled.
1307 FunctionPass *createHexagonCommonGEP() {
1308 return new HexagonCommonGEP();