1 //===--- HexagonCommonGEP.cpp ---------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #define DEBUG_TYPE "commgep"
11 
12 #include "llvm/ADT/ArrayRef.h"
13 #include "llvm/ADT/FoldingSet.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/Analysis/LoopInfo.h"
17 #include "llvm/Analysis/PostDominators.h"
18 #include "llvm/IR/BasicBlock.h"
19 #include "llvm/IR/Constant.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/Instruction.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/Type.h"
27 #include "llvm/IR/Use.h"
28 #include "llvm/IR/User.h"
29 #include "llvm/IR/Value.h"
30 #include "llvm/IR/Verifier.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/Allocator.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include <algorithm>
40 #include <cassert>
41 #include <cstddef>
42 #include <cstdint>
43 #include <iterator>
44 #include <map>
45 #include <set>
46 #include <utility>
47 #include <vector>
48 
49 using namespace llvm;
50 
51 static cl::opt<bool> OptSpeculate("commgep-speculate", cl::init(true),
52   cl::Hidden, cl::ZeroOrMore);
53 
54 static cl::opt<bool> OptEnableInv("commgep-inv", cl::init(true), cl::Hidden,
55   cl::ZeroOrMore);
56 
57 static cl::opt<bool> OptEnableConst("commgep-const", cl::init(true),
58   cl::Hidden, cl::ZeroOrMore);
59 
60 namespace llvm {
61 
62   void initializeHexagonCommonGEPPass(PassRegistry&);
63 
64 } // end namespace llvm
65 
66 namespace {
67 
68   struct GepNode;
69   typedef std::set<GepNode*> NodeSet;
70   typedef std::map<GepNode*,Value*> NodeToValueMap;
71   typedef std::vector<GepNode*> NodeVect;
72   typedef std::map<GepNode*,NodeVect> NodeChildrenMap;
73   typedef std::set<Use*> UseSet;
74   typedef std::map<GepNode*,UseSet> NodeToUsesMap;
75 
76   // Numbering map for gep nodes. Used to keep track of ordering for
77   // gep nodes.
78   struct NodeOrdering {
79     NodeOrdering() = default;
80 
81     void insert(const GepNode *N) { Map.insert(std::make_pair(N, ++LastNum)); }
82     void clear() { Map.clear(); }
83 
84     bool operator()(const GepNode *N1, const GepNode *N2) const {
85       auto F1 = Map.find(N1), F2 = Map.find(N2);
86       assert(F1 != Map.end() && F2 != Map.end());
87       return F1->second < F2->second;
88     }
89 
90   private:
91     std::map<const GepNode *, unsigned> Map;
92     unsigned LastNum = 0;
93   };
94 
95   class HexagonCommonGEP : public FunctionPass {
96   public:
97     static char ID;
98 
99     HexagonCommonGEP() : FunctionPass(ID) {
100       initializeHexagonCommonGEPPass(*PassRegistry::getPassRegistry());
101     }
102 
103     bool runOnFunction(Function &F) override;
104     StringRef getPassName() const override { return "Hexagon Common GEP"; }
105 
106     void getAnalysisUsage(AnalysisUsage &AU) const override {
107       AU.addRequired<DominatorTreeWrapperPass>();
108       AU.addPreserved<DominatorTreeWrapperPass>();
109       AU.addRequired<PostDominatorTreeWrapperPass>();
110       AU.addPreserved<PostDominatorTreeWrapperPass>();
111       AU.addRequired<LoopInfoWrapperPass>();
112       AU.addPreserved<LoopInfoWrapperPass>();
113       FunctionPass::getAnalysisUsage(AU);
114     }
115 
116   private:
117     typedef std::map<Value*,GepNode*> ValueToNodeMap;
118     typedef std::vector<Value*> ValueVect;
119     typedef std::map<GepNode*,ValueVect> NodeToValuesMap;
120 
121     void getBlockTraversalOrder(BasicBlock *Root, ValueVect &Order);
122     bool isHandledGepForm(GetElementPtrInst *GepI);
123     void processGepInst(GetElementPtrInst *GepI, ValueToNodeMap &NM);
124     void collect();
125     void common();
126 
127     BasicBlock *recalculatePlacement(GepNode *Node, NodeChildrenMap &NCM,
128                                      NodeToValueMap &Loc);
129     BasicBlock *recalculatePlacementRec(GepNode *Node, NodeChildrenMap &NCM,
130                                         NodeToValueMap &Loc);
131     bool isInvariantIn(Value *Val, Loop *L);
132     bool isInvariantIn(GepNode *Node, Loop *L);
133     bool isInMainPath(BasicBlock *B, Loop *L);
134     BasicBlock *adjustForInvariance(GepNode *Node, NodeChildrenMap &NCM,
135                                     NodeToValueMap &Loc);
136     void separateChainForNode(GepNode *Node, Use *U, NodeToValueMap &Loc);
137     void separateConstantChains(GepNode *Node, NodeChildrenMap &NCM,
138                                 NodeToValueMap &Loc);
139     void computeNodePlacement(NodeToValueMap &Loc);
140 
141     Value *fabricateGEP(NodeVect &NA, BasicBlock::iterator At,
142                         BasicBlock *LocB);
143     void getAllUsersForNode(GepNode *Node, ValueVect &Values,
144                             NodeChildrenMap &NCM);
145     void materialize(NodeToValueMap &Loc);
146 
147     void removeDeadCode();
148 
149     NodeVect Nodes;
150     NodeToUsesMap Uses;
151     NodeOrdering NodeOrder;   // Node ordering, for deterministic behavior.
152     SpecificBumpPtrAllocator<GepNode> *Mem;
153     LLVMContext *Ctx;
154     LoopInfo *LI;
155     DominatorTree *DT;
156     PostDominatorTree *PDT;
157     Function *Fn;
158   };
159 
160 } // end anonymous namespace
161 
162 char HexagonCommonGEP::ID = 0;
163 INITIALIZE_PASS_BEGIN(HexagonCommonGEP, "hcommgep", "Hexagon Common GEP",
164       false, false)
165 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
166 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
167 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
168 INITIALIZE_PASS_END(HexagonCommonGEP, "hcommgep", "Hexagon Common GEP",
169       false, false)
170 
171 namespace {
172 
173   struct GepNode {
174     enum {
175       None      = 0,
176       Root      = 0x01,
177       Internal  = 0x02,
178       Used      = 0x04,
179       InBounds  = 0x08
180     };
181 
182     uint32_t Flags;
183     union {
184       GepNode *Parent;
185       Value *BaseVal;
186     };
187     Value *Idx;
188     Type *PTy;  // Type of the pointer operand.
189 
190     GepNode() : Flags(0), Parent(nullptr), Idx(nullptr), PTy(nullptr) {}
191     GepNode(const GepNode *N) : Flags(N->Flags), Idx(N->Idx), PTy(N->PTy) {
192       if (Flags & Root)
193         BaseVal = N->BaseVal;
194       else
195         Parent = N->Parent;
196     }
197 
198     friend raw_ostream &operator<< (raw_ostream &OS, const GepNode &GN);
199   };
200 
201   Type *next_type(Type *Ty, Value *Idx) {
202     if (auto *PTy = dyn_cast<PointerType>(Ty))
203       return PTy->getElementType();
204     // Advance the type.
205     if (!Ty->isStructTy()) {
206       Type *NexTy = cast<SequentialType>(Ty)->getElementType();
207       return NexTy;
208     }
209     // Otherwise it is a struct type.
210     ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
211     assert(CI && "Struct type with non-constant index");
212     int64_t i = CI->getValue().getSExtValue();
213     Type *NextTy = cast<StructType>(Ty)->getElementType(i);
214     return NextTy;
215   }
216 
217   raw_ostream &operator<< (raw_ostream &OS, const GepNode &GN) {
218     OS << "{ {";
219     bool Comma = false;
220     if (GN.Flags & GepNode::Root) {
221       OS << "root";
222       Comma = true;
223     }
224     if (GN.Flags & GepNode::Internal) {
225       if (Comma)
226         OS << ',';
227       OS << "internal";
228       Comma = true;
229     }
230     if (GN.Flags & GepNode::Used) {
231       if (Comma)
232         OS << ',';
233       OS << "used";
234     }
235     if (GN.Flags & GepNode::InBounds) {
236       if (Comma)
237         OS << ',';
238       OS << "inbounds";
239     }
240     OS << "} ";
241     if (GN.Flags & GepNode::Root)
242       OS << "BaseVal:" << GN.BaseVal->getName() << '(' << GN.BaseVal << ')';
243     else
244       OS << "Parent:" << GN.Parent;
245 
246     OS << " Idx:";
247     if (ConstantInt *CI = dyn_cast<ConstantInt>(GN.Idx))
248       OS << CI->getValue().getSExtValue();
249     else if (GN.Idx->hasName())
250       OS << GN.Idx->getName();
251     else
252       OS << "<anon> =" << *GN.Idx;
253 
254     OS << " PTy:";
255     if (GN.PTy->isStructTy()) {
256       StructType *STy = cast<StructType>(GN.PTy);
257       if (!STy->isLiteral())
258         OS << GN.PTy->getStructName();
259       else
260         OS << "<anon-struct>:" << *STy;
261     }
262     else
263       OS << *GN.PTy;
264     OS << " }";
265     return OS;
266   }
267 
268   template <typename NodeContainer>
269   void dump_node_container(raw_ostream &OS, const NodeContainer &S) {
270     typedef typename NodeContainer::const_iterator const_iterator;
271     for (const_iterator I = S.begin(), E = S.end(); I != E; ++I)
272       OS << *I << ' ' << **I << '\n';
273   }
274 
275   raw_ostream &operator<< (raw_ostream &OS,
276                            const NodeVect &S) LLVM_ATTRIBUTE_UNUSED;
277   raw_ostream &operator<< (raw_ostream &OS, const NodeVect &S) {
278     dump_node_container(OS, S);
279     return OS;
280   }
281 
282   raw_ostream &operator<< (raw_ostream &OS,
283                            const NodeToUsesMap &M) LLVM_ATTRIBUTE_UNUSED;
284   raw_ostream &operator<< (raw_ostream &OS, const NodeToUsesMap &M){
285     typedef NodeToUsesMap::const_iterator const_iterator;
286     for (const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
287       const UseSet &Us = I->second;
288       OS << I->first << " -> #" << Us.size() << '{';
289       for (UseSet::const_iterator J = Us.begin(), F = Us.end(); J != F; ++J) {
290         User *R = (*J)->getUser();
291         if (R->hasName())
292           OS << ' ' << R->getName();
293         else
294           OS << " <?>(" << *R << ')';
295       }
296       OS << " }\n";
297     }
298     return OS;
299   }
300 
301   struct in_set {
302     in_set(const NodeSet &S) : NS(S) {}
303     bool operator() (GepNode *N) const {
304       return NS.find(N) != NS.end();
305     }
306 
307   private:
308     const NodeSet &NS;
309   };
310 
311 } // end anonymous namespace
312 
313 inline void *operator new(size_t, SpecificBumpPtrAllocator<GepNode> &A) {
314   return A.Allocate();
315 }
316 
317 void HexagonCommonGEP::getBlockTraversalOrder(BasicBlock *Root,
318       ValueVect &Order) {
319   // Compute block ordering for a typical DT-based traversal of the flow
320   // graph: "before visiting a block, all of its dominators must have been
321   // visited".
322 
323   Order.push_back(Root);
324   for (auto *DTN : children<DomTreeNode*>(DT->getNode(Root)))
325     getBlockTraversalOrder(DTN->getBlock(), Order);
326 }
327 
328 bool HexagonCommonGEP::isHandledGepForm(GetElementPtrInst *GepI) {
329   // No vector GEPs.
330   if (!GepI->getType()->isPointerTy())
331     return false;
332   // No GEPs without any indices.  (Is this possible?)
333   if (GepI->idx_begin() == GepI->idx_end())
334     return false;
335   return true;
336 }
337 
338 void HexagonCommonGEP::processGepInst(GetElementPtrInst *GepI,
339       ValueToNodeMap &NM) {
340   DEBUG(dbgs() << "Visiting GEP: " << *GepI << '\n');
341   GepNode *N = new (*Mem) GepNode;
342   Value *PtrOp = GepI->getPointerOperand();
343   uint32_t InBounds = GepI->isInBounds() ? GepNode::InBounds : 0;
344   ValueToNodeMap::iterator F = NM.find(PtrOp);
345   if (F == NM.end()) {
346     N->BaseVal = PtrOp;
347     N->Flags |= GepNode::Root | InBounds;
348   } else {
349     // If PtrOp was a GEP instruction, it must have already been processed.
350     // The ValueToNodeMap entry for it is the last gep node in the generated
351     // chain. Link to it here.
352     N->Parent = F->second;
353   }
354   N->PTy = PtrOp->getType();
355   N->Idx = *GepI->idx_begin();
356 
357   // Collect the list of users of this GEP instruction. Will add it to the
358   // last node created for it.
359   UseSet Us;
360   for (Value::user_iterator UI = GepI->user_begin(), UE = GepI->user_end();
361        UI != UE; ++UI) {
362     // Check if this gep is used by anything other than other geps that
363     // we will process.
364     if (isa<GetElementPtrInst>(*UI)) {
365       GetElementPtrInst *UserG = cast<GetElementPtrInst>(*UI);
366       if (isHandledGepForm(UserG))
367         continue;
368     }
369     Us.insert(&UI.getUse());
370   }
371   Nodes.push_back(N);
372   NodeOrder.insert(N);
373 
374   // Skip the first index operand, since we only handle 0. This dereferences
375   // the pointer operand.
376   GepNode *PN = N;
377   Type *PtrTy = cast<PointerType>(PtrOp->getType())->getElementType();
378   for (User::op_iterator OI = GepI->idx_begin()+1, OE = GepI->idx_end();
379        OI != OE; ++OI) {
380     Value *Op = *OI;
381     GepNode *Nx = new (*Mem) GepNode;
382     Nx->Parent = PN;  // Link Nx to the previous node.
383     Nx->Flags |= GepNode::Internal | InBounds;
384     Nx->PTy = PtrTy;
385     Nx->Idx = Op;
386     Nodes.push_back(Nx);
387     NodeOrder.insert(Nx);
388     PN = Nx;
389 
390     PtrTy = next_type(PtrTy, Op);
391   }
392 
393   // After last node has been created, update the use information.
394   if (!Us.empty()) {
395     PN->Flags |= GepNode::Used;
396     Uses[PN].insert(Us.begin(), Us.end());
397   }
398 
399   // Link the last node with the originating GEP instruction. This is to
400   // help with linking chained GEP instructions.
401   NM.insert(std::make_pair(GepI, PN));
402 }
403 
404 void HexagonCommonGEP::collect() {
405   // Establish depth-first traversal order of the dominator tree.
406   ValueVect BO;
407   getBlockTraversalOrder(&Fn->front(), BO);
408 
409   // The creation of gep nodes requires DT-traversal. When processing a GEP
410   // instruction that uses another GEP instruction as the base pointer, the
411   // gep node for the base pointer should already exist.
412   ValueToNodeMap NM;
413   for (ValueVect::iterator I = BO.begin(), E = BO.end(); I != E; ++I) {
414     BasicBlock *B = cast<BasicBlock>(*I);
415     for (BasicBlock::iterator J = B->begin(), F = B->end(); J != F; ++J) {
416       if (!isa<GetElementPtrInst>(J))
417         continue;
418       GetElementPtrInst *GepI = cast<GetElementPtrInst>(J);
419       if (isHandledGepForm(GepI))
420         processGepInst(GepI, NM);
421     }
422   }
423 
424   DEBUG(dbgs() << "Gep nodes after initial collection:\n" << Nodes);
425 }
426 
427 static void invert_find_roots(const NodeVect &Nodes, NodeChildrenMap &NCM,
428                               NodeVect &Roots) {
429     typedef NodeVect::const_iterator const_iterator;
430     for (const_iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
431       GepNode *N = *I;
432       if (N->Flags & GepNode::Root) {
433         Roots.push_back(N);
434         continue;
435       }
436       GepNode *PN = N->Parent;
437       NCM[PN].push_back(N);
438     }
439 }
440 
441 static void nodes_for_root(GepNode *Root, NodeChildrenMap &NCM,
442                            NodeSet &Nodes) {
443     NodeVect Work;
444     Work.push_back(Root);
445     Nodes.insert(Root);
446 
447     while (!Work.empty()) {
448       NodeVect::iterator First = Work.begin();
449       GepNode *N = *First;
450       Work.erase(First);
451       NodeChildrenMap::iterator CF = NCM.find(N);
452       if (CF != NCM.end()) {
453         Work.insert(Work.end(), CF->second.begin(), CF->second.end());
454         Nodes.insert(CF->second.begin(), CF->second.end());
455       }
456     }
457 }
458 
459 namespace {
460 
461   typedef std::set<NodeSet> NodeSymRel;
462   typedef std::pair<GepNode*,GepNode*> NodePair;
463   typedef std::set<NodePair> NodePairSet;
464 
465 } // end anonymous namespace
466 
467 static const NodeSet *node_class(GepNode *N, NodeSymRel &Rel) {
468     for (NodeSymRel::iterator I = Rel.begin(), E = Rel.end(); I != E; ++I)
469       if (I->count(N))
470         return &*I;
471     return nullptr;
472 }
473 
474   // Create an ordered pair of GepNode pointers. The pair will be used in
475   // determining equality. The only purpose of the ordering is to eliminate
476   // duplication due to the commutativity of equality/non-equality.
477 static NodePair node_pair(GepNode *N1, GepNode *N2) {
478     uintptr_t P1 = uintptr_t(N1), P2 = uintptr_t(N2);
479     if (P1 <= P2)
480       return std::make_pair(N1, N2);
481     return std::make_pair(N2, N1);
482 }
483 
484 static unsigned node_hash(GepNode *N) {
485     // Include everything except flags and parent.
486     FoldingSetNodeID ID;
487     ID.AddPointer(N->Idx);
488     ID.AddPointer(N->PTy);
489     return ID.ComputeHash();
490 }
491 
492 static bool node_eq(GepNode *N1, GepNode *N2, NodePairSet &Eq,
493                     NodePairSet &Ne) {
494     // Don't cache the result for nodes with different hashes. The hash
495     // comparison is fast enough.
496     if (node_hash(N1) != node_hash(N2))
497       return false;
498 
499     NodePair NP = node_pair(N1, N2);
500     NodePairSet::iterator FEq = Eq.find(NP);
501     if (FEq != Eq.end())
502       return true;
503     NodePairSet::iterator FNe = Ne.find(NP);
504     if (FNe != Ne.end())
505       return false;
506     // Not previously compared.
507     bool Root1 = N1->Flags & GepNode::Root;
508     bool Root2 = N2->Flags & GepNode::Root;
509     NodePair P = node_pair(N1, N2);
510     // If the Root flag has different values, the nodes are different.
511     // If both nodes are root nodes, but their base pointers differ,
512     // they are different.
513     if (Root1 != Root2 || (Root1 && N1->BaseVal != N2->BaseVal)) {
514       Ne.insert(P);
515       return false;
516     }
517     // Here the root flags are identical, and for root nodes the
518     // base pointers are equal, so the root nodes are equal.
519     // For non-root nodes, compare their parent nodes.
520     if (Root1 || node_eq(N1->Parent, N2->Parent, Eq, Ne)) {
521       Eq.insert(P);
522       return true;
523     }
524     return false;
525 }
526 
527 void HexagonCommonGEP::common() {
528   // The essence of this commoning is finding gep nodes that are equal.
529   // To do this we need to compare all pairs of nodes. To save time,
530   // first, partition the set of all nodes into sets of potentially equal
531   // nodes, and then compare pairs from within each partition.
532   typedef std::map<unsigned,NodeSet> NodeSetMap;
533   NodeSetMap MaybeEq;
534 
535   for (NodeVect::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
536     GepNode *N = *I;
537     unsigned H = node_hash(N);
538     MaybeEq[H].insert(N);
539   }
540 
541   // Compute the equivalence relation for the gep nodes.  Use two caches,
542   // one for equality and the other for non-equality.
543   NodeSymRel EqRel;  // Equality relation (as set of equivalence classes).
544   NodePairSet Eq, Ne;  // Caches.
545   for (NodeSetMap::iterator I = MaybeEq.begin(), E = MaybeEq.end();
546        I != E; ++I) {
547     NodeSet &S = I->second;
548     for (NodeSet::iterator NI = S.begin(), NE = S.end(); NI != NE; ++NI) {
549       GepNode *N = *NI;
550       // If node already has a class, then the class must have been created
551       // in a prior iteration of this loop. Since equality is transitive,
552       // nothing more will be added to that class, so skip it.
553       if (node_class(N, EqRel))
554         continue;
555 
556       // Create a new class candidate now.
557       NodeSet C;
558       for (NodeSet::iterator NJ = std::next(NI); NJ != NE; ++NJ)
559         if (node_eq(N, *NJ, Eq, Ne))
560           C.insert(*NJ);
561       // If Tmp is empty, N would be the only element in it. Don't bother
562       // creating a class for it then.
563       if (!C.empty()) {
564         C.insert(N);  // Finalize the set before adding it to the relation.
565         std::pair<NodeSymRel::iterator, bool> Ins = EqRel.insert(C);
566         (void)Ins;
567         assert(Ins.second && "Cannot add a class");
568       }
569     }
570   }
571 
572   DEBUG({
573     dbgs() << "Gep node equality:\n";
574     for (NodePairSet::iterator I = Eq.begin(), E = Eq.end(); I != E; ++I)
575       dbgs() << "{ " << I->first << ", " << I->second << " }\n";
576 
577     dbgs() << "Gep equivalence classes:\n";
578     for (NodeSymRel::iterator I = EqRel.begin(), E = EqRel.end(); I != E; ++I) {
579       dbgs() << '{';
580       const NodeSet &S = *I;
581       for (NodeSet::const_iterator J = S.begin(), F = S.end(); J != F; ++J) {
582         if (J != S.begin())
583           dbgs() << ',';
584         dbgs() << ' ' << *J;
585       }
586       dbgs() << " }\n";
587     }
588   });
589 
590   // Create a projection from a NodeSet to the minimal element in it.
591   typedef std::map<const NodeSet*,GepNode*> ProjMap;
592   ProjMap PM;
593   for (NodeSymRel::iterator I = EqRel.begin(), E = EqRel.end(); I != E; ++I) {
594     const NodeSet &S = *I;
595     GepNode *Min = *std::min_element(S.begin(), S.end(), NodeOrder);
596     std::pair<ProjMap::iterator,bool> Ins = PM.insert(std::make_pair(&S, Min));
597     (void)Ins;
598     assert(Ins.second && "Cannot add minimal element");
599 
600     // Update the min element's flags, and user list.
601     uint32_t Flags = 0;
602     UseSet &MinUs = Uses[Min];
603     for (NodeSet::iterator J = S.begin(), F = S.end(); J != F; ++J) {
604       GepNode *N = *J;
605       uint32_t NF = N->Flags;
606       // If N is used, append all original values of N to the list of
607       // original values of Min.
608       if (NF & GepNode::Used)
609         MinUs.insert(Uses[N].begin(), Uses[N].end());
610       Flags |= NF;
611     }
612     if (MinUs.empty())
613       Uses.erase(Min);
614 
615     // The collected flags should include all the flags from the min element.
616     assert((Min->Flags & Flags) == Min->Flags);
617     Min->Flags = Flags;
618   }
619 
620   // Commoning: for each non-root gep node, replace "Parent" with the
621   // selected (minimum) node from the corresponding equivalence class.
622   // If a given parent does not have an equivalence class, leave it
623   // unchanged (it means that it's the only element in its class).
624   for (NodeVect::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
625     GepNode *N = *I;
626     if (N->Flags & GepNode::Root)
627       continue;
628     const NodeSet *PC = node_class(N->Parent, EqRel);
629     if (!PC)
630       continue;
631     ProjMap::iterator F = PM.find(PC);
632     if (F == PM.end())
633       continue;
634     // Found a replacement, use it.
635     GepNode *Rep = F->second;
636     N->Parent = Rep;
637   }
638 
639   DEBUG(dbgs() << "Gep nodes after commoning:\n" << Nodes);
640 
641   // Finally, erase the nodes that are no longer used.
642   NodeSet Erase;
643   for (NodeVect::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
644     GepNode *N = *I;
645     const NodeSet *PC = node_class(N, EqRel);
646     if (!PC)
647       continue;
648     ProjMap::iterator F = PM.find(PC);
649     if (F == PM.end())
650       continue;
651     if (N == F->second)
652       continue;
653     // Node for removal.
654     Erase.insert(*I);
655   }
656   NodeVect::iterator NewE = remove_if(Nodes, in_set(Erase));
657   Nodes.resize(std::distance(Nodes.begin(), NewE));
658 
659   DEBUG(dbgs() << "Gep nodes after post-commoning cleanup:\n" << Nodes);
660 }
661 
662 template <typename T>
663 static BasicBlock *nearest_common_dominator(DominatorTree *DT, T &Blocks) {
664     DEBUG({
665       dbgs() << "NCD of {";
666       for (typename T::iterator I = Blocks.begin(), E = Blocks.end();
667            I != E; ++I) {
668         if (!*I)
669           continue;
670         BasicBlock *B = cast<BasicBlock>(*I);
671         dbgs() << ' ' << B->getName();
672       }
673       dbgs() << " }\n";
674     });
675 
676     // Allow null basic blocks in Blocks.  In such cases, return nullptr.
677     typename T::iterator I = Blocks.begin(), E = Blocks.end();
678     if (I == E || !*I)
679       return nullptr;
680     BasicBlock *Dom = cast<BasicBlock>(*I);
681     while (++I != E) {
682       BasicBlock *B = cast_or_null<BasicBlock>(*I);
683       Dom = B ? DT->findNearestCommonDominator(Dom, B) : nullptr;
684       if (!Dom)
685         return nullptr;
686     }
687     DEBUG(dbgs() << "computed:" << Dom->getName() << '\n');
688     return Dom;
689 }
690 
691 template <typename T>
692 static BasicBlock *nearest_common_dominatee(DominatorTree *DT, T &Blocks) {
693     // If two blocks, A and B, dominate a block C, then A dominates B,
694     // or B dominates A.
695     typename T::iterator I = Blocks.begin(), E = Blocks.end();
696     // Find the first non-null block.
697     while (I != E && !*I)
698       ++I;
699     if (I == E)
700       return DT->getRoot();
701     BasicBlock *DomB = cast<BasicBlock>(*I);
702     while (++I != E) {
703       if (!*I)
704         continue;
705       BasicBlock *B = cast<BasicBlock>(*I);
706       if (DT->dominates(B, DomB))
707         continue;
708       if (!DT->dominates(DomB, B))
709         return nullptr;
710       DomB = B;
711     }
712     return DomB;
713 }
714 
715 // Find the first use in B of any value from Values. If no such use,
716 // return B->end().
717 template <typename T>
718 static BasicBlock::iterator first_use_of_in_block(T &Values, BasicBlock *B) {
719     BasicBlock::iterator FirstUse = B->end(), BEnd = B->end();
720     typedef typename T::iterator iterator;
721     for (iterator I = Values.begin(), E = Values.end(); I != E; ++I) {
722       Value *V = *I;
723       // If V is used in a PHI node, the use belongs to the incoming block,
724       // not the block with the PHI node. In the incoming block, the use
725       // would be considered as being at the end of it, so it cannot
726       // influence the position of the first use (which is assumed to be
727       // at the end to start with).
728       if (isa<PHINode>(V))
729         continue;
730       if (!isa<Instruction>(V))
731         continue;
732       Instruction *In = cast<Instruction>(V);
733       if (In->getParent() != B)
734         continue;
735       BasicBlock::iterator It = In->getIterator();
736       if (std::distance(FirstUse, BEnd) < std::distance(It, BEnd))
737         FirstUse = It;
738     }
739     return FirstUse;
740 }
741 
742 static bool is_empty(const BasicBlock *B) {
743     return B->empty() || (&*B->begin() == B->getTerminator());
744 }
745 
746 BasicBlock *HexagonCommonGEP::recalculatePlacement(GepNode *Node,
747       NodeChildrenMap &NCM, NodeToValueMap &Loc) {
748   DEBUG(dbgs() << "Loc for node:" << Node << '\n');
749   // Recalculate the placement for Node, assuming that the locations of
750   // its children in Loc are valid.
751   // Return nullptr if there is no valid placement for Node (for example, it
752   // uses an index value that is not available at the location required
753   // to dominate all children, etc.).
754 
755   // Find the nearest common dominator for:
756   // - all users, if the node is used, and
757   // - all children.
758   ValueVect Bs;
759   if (Node->Flags & GepNode::Used) {
760     // Append all blocks with uses of the original values to the
761     // block vector Bs.
762     NodeToUsesMap::iterator UF = Uses.find(Node);
763     assert(UF != Uses.end() && "Used node with no use information");
764     UseSet &Us = UF->second;
765     for (UseSet::iterator I = Us.begin(), E = Us.end(); I != E; ++I) {
766       Use *U = *I;
767       User *R = U->getUser();
768       if (!isa<Instruction>(R))
769         continue;
770       BasicBlock *PB = isa<PHINode>(R)
771           ? cast<PHINode>(R)->getIncomingBlock(*U)
772           : cast<Instruction>(R)->getParent();
773       Bs.push_back(PB);
774     }
775   }
776   // Append the location of each child.
777   NodeChildrenMap::iterator CF = NCM.find(Node);
778   if (CF != NCM.end()) {
779     NodeVect &Cs = CF->second;
780     for (NodeVect::iterator I = Cs.begin(), E = Cs.end(); I != E; ++I) {
781       GepNode *CN = *I;
782       NodeToValueMap::iterator LF = Loc.find(CN);
783       // If the child is only used in GEP instructions (i.e. is not used in
784       // non-GEP instructions), the nearest dominator computed for it may
785       // have been null. In such case it won't have a location available.
786       if (LF == Loc.end())
787         continue;
788       Bs.push_back(LF->second);
789     }
790   }
791 
792   BasicBlock *DomB = nearest_common_dominator(DT, Bs);
793   if (!DomB)
794     return nullptr;
795   // Check if the index used by Node dominates the computed dominator.
796   Instruction *IdxI = dyn_cast<Instruction>(Node->Idx);
797   if (IdxI && !DT->dominates(IdxI->getParent(), DomB))
798     return nullptr;
799 
800   // Avoid putting nodes into empty blocks.
801   while (is_empty(DomB)) {
802     DomTreeNode *N = (*DT)[DomB]->getIDom();
803     if (!N)
804       break;
805     DomB = N->getBlock();
806   }
807 
808   // Otherwise, DomB is fine. Update the location map.
809   Loc[Node] = DomB;
810   return DomB;
811 }
812 
813 BasicBlock *HexagonCommonGEP::recalculatePlacementRec(GepNode *Node,
814       NodeChildrenMap &NCM, NodeToValueMap &Loc) {
815   DEBUG(dbgs() << "LocRec begin for node:" << Node << '\n');
816   // Recalculate the placement of Node, after recursively recalculating the
817   // placements of all its children.
818   NodeChildrenMap::iterator CF = NCM.find(Node);
819   if (CF != NCM.end()) {
820     NodeVect &Cs = CF->second;
821     for (NodeVect::iterator I = Cs.begin(), E = Cs.end(); I != E; ++I)
822       recalculatePlacementRec(*I, NCM, Loc);
823   }
824   BasicBlock *LB = recalculatePlacement(Node, NCM, Loc);
825   DEBUG(dbgs() << "LocRec end for node:" << Node << '\n');
826   return LB;
827 }
828 
829 bool HexagonCommonGEP::isInvariantIn(Value *Val, Loop *L) {
830   if (isa<Constant>(Val) || isa<Argument>(Val))
831     return true;
832   Instruction *In = dyn_cast<Instruction>(Val);
833   if (!In)
834     return false;
835   BasicBlock *HdrB = L->getHeader(), *DefB = In->getParent();
836   return DT->properlyDominates(DefB, HdrB);
837 }
838 
839 bool HexagonCommonGEP::isInvariantIn(GepNode *Node, Loop *L) {
840   if (Node->Flags & GepNode::Root)
841     if (!isInvariantIn(Node->BaseVal, L))
842       return false;
843   return isInvariantIn(Node->Idx, L);
844 }
845 
846 bool HexagonCommonGEP::isInMainPath(BasicBlock *B, Loop *L) {
847   BasicBlock *HB = L->getHeader();
848   BasicBlock *LB = L->getLoopLatch();
849   // B must post-dominate the loop header or dominate the loop latch.
850   if (PDT->dominates(B, HB))
851     return true;
852   if (LB && DT->dominates(B, LB))
853     return true;
854   return false;
855 }
856 
857 static BasicBlock *preheader(DominatorTree *DT, Loop *L) {
858   if (BasicBlock *PH = L->getLoopPreheader())
859     return PH;
860   if (!OptSpeculate)
861     return nullptr;
862   DomTreeNode *DN = DT->getNode(L->getHeader());
863   if (!DN)
864     return nullptr;
865   return DN->getIDom()->getBlock();
866 }
867 
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
872   // value.
873   ValueVect Bs;
874   if (Node->Flags & GepNode::Root) {
875     if (Instruction *PIn = dyn_cast<Instruction>(Node->BaseVal))
876       Bs.push_back(PIn->getParent());
877   } else {
878     Bs.push_back(Loc[Node->Parent]);
879   }
880   if (Instruction *IIn = dyn_cast<Instruction>(Node->Idx))
881     Bs.push_back(IIn->getParent());
882   BasicBlock *TopB = nearest_common_dominatee(DT, Bs);
883 
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]);
893   if (LocB) {
894     Loop *Lp = LI->getLoopFor(LocB);
895     while (Lp) {
896       if (!isInvariantIn(Node, Lp) || !isInMainPath(LocB, Lp))
897         break;
898       BasicBlock *NewLoc = preheader(DT, Lp);
899       if (!NewLoc || !DT->dominates(TopB, NewLoc))
900         break;
901       Lp = Lp->getParentLoop();
902       LocB = NewLoc;
903     }
904   }
905   Loc[Node] = LocB;
906 
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);
913   }
914   return LocB;
915 }
916 
917 namespace {
918 
919   struct LocationAsBlock {
920     LocationAsBlock(const NodeToValueMap &L) : Map(L) {}
921 
922     const NodeToValueMap &Map;
923   };
924 
925   raw_ostream &operator<< (raw_ostream &OS,
926                            const LocationAsBlock &Loc) LLVM_ATTRIBUTE_UNUSED ;
927   raw_ostream &operator<< (raw_ostream &OS, const LocationAsBlock &Loc) {
928     for (NodeToValueMap::const_iterator I = Loc.Map.begin(), E = Loc.Map.end();
929          I != E; ++I) {
930       OS << I->first << " -> ";
931       BasicBlock *B = cast<BasicBlock>(I->second);
932       OS << B->getName() << '(' << B << ')';
933       OS << '\n';
934     }
935     return OS;
936   }
937 
938   inline bool is_constant(GepNode *N) {
939     return isa<ConstantInt>(N->Idx);
940   }
941 
942 } // end anonymous namespace
943 
944 void HexagonCommonGEP::separateChainForNode(GepNode *Node, Use *U,
945       NodeToValueMap &Loc) {
946   User *R = U->getUser();
947   DEBUG(dbgs() << "Separating chain for node (" << Node << ") user: "
948                << *R << '\n');
949   BasicBlock *PB = cast<Instruction>(R)->getParent();
950 
951   GepNode *N = Node;
952   GepNode *C = nullptr, *NewNode = nullptr;
953   while (is_constant(N) && !(N->Flags & GepNode::Root)) {
954     // XXX if (single-use) dont-replicate;
955     GepNode *NewN = new (*Mem) GepNode(N);
956     Nodes.push_back(NewN);
957     Loc[NewN] = PB;
958 
959     if (N == Node)
960       NewNode = NewN;
961     NewN->Flags &= ~GepNode::Used;
962     if (C)
963       C->Parent = NewN;
964     C = NewN;
965     N = N->Parent;
966   }
967   if (!NewNode)
968     return;
969 
970   // Move over all uses that share the same user as U from Node to NewNode.
971   NodeToUsesMap::iterator UF = Uses.find(Node);
972   assert(UF != Uses.end());
973   UseSet &Us = UF->second;
974   UseSet NewUs;
975   for (UseSet::iterator I = Us.begin(); I != Us.end(); ) {
976     User *S = (*I)->getUser();
977     UseSet::iterator Nx = std::next(I);
978     if (S == R) {
979       NewUs.insert(*I);
980       Us.erase(I);
981     }
982     I = Nx;
983   }
984   if (Us.empty()) {
985     Node->Flags &= ~GepNode::Used;
986     Uses.erase(UF);
987   }
988 
989   // Should at least have U in NewUs.
990   NewNode->Flags |= GepNode::Used;
991   DEBUG(dbgs() << "new node: " << NewNode << "  " << *NewNode << '\n');
992   assert(!NewUs.empty());
993   Uses[NewNode] = NewUs;
994 }
995 
996 void HexagonCommonGEP::separateConstantChains(GepNode *Node,
997       NodeChildrenMap &NCM, NodeToValueMap &Loc) {
998   // First approximation: extract all chains.
999   NodeSet Ns;
1000   nodes_for_root(Node, NCM, Ns);
1001 
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) {
1007     GepNode *N = *I;
1008     if (!(N->Flags & GepNode::Used))
1009       continue;
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.
1014     UseSet LSs;
1015     for (UseSet::iterator J = Us.begin(), F = Us.end(); J != F; ++J) {
1016       Use *U = *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)
1024           LSs.insert(U);
1025       } else if (StoreInst *St = dyn_cast<StoreInst>(R)) {
1026         unsigned PtrX = StoreInst::getPointerOperandIndex();
1027         if (&St->getOperandUse(PtrX) == U)
1028           LSs.insert(U);
1029       }
1030     }
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
1034     // other children).
1035     if (!LSs.empty())
1036       FNs.insert(std::make_pair(N, LSs));
1037   }
1038 
1039   DEBUG(dbgs() << "Nodes with foldable users:\n" << FNs);
1040 
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);
1046   }
1047 }
1048 
1049 void HexagonCommonGEP::computeNodePlacement(NodeToValueMap &Loc) {
1050   // Compute the inverse of the Node.Parent links. Also, collect the set
1051   // of root nodes.
1052   NodeChildrenMap NCM;
1053   NodeVect Roots;
1054   invert_find_roots(Nodes, NCM, Roots);
1055 
1056   // Compute the initial placement determined by the users' locations, and
1057   // the locations of the child nodes.
1058   for (NodeVect::iterator I = Roots.begin(), E = Roots.end(); I != E; ++I)
1059     recalculatePlacementRec(*I, NCM, Loc);
1060 
1061   DEBUG(dbgs() << "Initial node placement:\n" << LocationAsBlock(Loc));
1062 
1063   if (OptEnableInv) {
1064     for (NodeVect::iterator I = Roots.begin(), E = Roots.end(); I != E; ++I)
1065       adjustForInvariance(*I, NCM, Loc);
1066 
1067     DEBUG(dbgs() << "Node placement after adjustment for invariance:\n"
1068                  << LocationAsBlock(Loc));
1069   }
1070   if (OptEnableConst) {
1071     for (NodeVect::iterator I = Roots.begin(), E = Roots.end(); I != E; ++I)
1072       separateConstantChains(*I, NCM, Loc);
1073   }
1074   DEBUG(dbgs() << "Node use information:\n" << Uses);
1075 
1076   // At the moment, there is no further refinement of the initial placement.
1077   // Such a refinement could include splitting the nodes if they are placed
1078   // too far from some of its users.
1079 
1080   DEBUG(dbgs() << "Final node placement:\n" << LocationAsBlock(Loc));
1081 }
1082 
1083 Value *HexagonCommonGEP::fabricateGEP(NodeVect &NA, BasicBlock::iterator At,
1084       BasicBlock *LocB) {
1085   DEBUG(dbgs() << "Fabricating GEP in " << LocB->getName()
1086                << " for nodes:\n" << NA);
1087   unsigned Num = NA.size();
1088   GepNode *RN = NA[0];
1089   assert((RN->Flags & GepNode::Root) && "Creating GEP for non-root");
1090 
1091   GetElementPtrInst *NewInst = nullptr;
1092   Value *Input = RN->BaseVal;
1093   Value **IdxList = new Value*[Num+1];
1094   unsigned nax = 0;
1095   do {
1096     unsigned IdxC = 0;
1097     // If the type of the input of the first node is not a pointer,
1098     // we need to add an artificial i32 0 to the indices (because the
1099     // actual input in the IR will be a pointer).
1100     if (!NA[nax]->PTy->isPointerTy()) {
1101       Type *Int32Ty = Type::getInt32Ty(*Ctx);
1102       IdxList[IdxC++] = ConstantInt::get(Int32Ty, 0);
1103     }
1104 
1105     // Keep adding indices from NA until we have to stop and generate
1106     // an "intermediate" GEP.
1107     while (++nax <= Num) {
1108       GepNode *N = NA[nax-1];
1109       IdxList[IdxC++] = N->Idx;
1110       if (nax < Num) {
1111         // We have to stop, if the expected type of the output of this node
1112         // is not the same as the input type of the next node.
1113         Type *NextTy = next_type(N->PTy, N->Idx);
1114         if (NextTy != NA[nax]->PTy)
1115           break;
1116       }
1117     }
1118     ArrayRef<Value*> A(IdxList, IdxC);
1119     Type *InpTy = Input->getType();
1120     Type *ElTy = cast<PointerType>(InpTy->getScalarType())->getElementType();
1121     NewInst = GetElementPtrInst::Create(ElTy, Input, A, "cgep", &*At);
1122     NewInst->setIsInBounds(RN->Flags & GepNode::InBounds);
1123     DEBUG(dbgs() << "new GEP: " << *NewInst << '\n');
1124     Input = NewInst;
1125   } while (nax <= Num);
1126 
1127   delete[] IdxList;
1128   return NewInst;
1129 }
1130 
1131 void HexagonCommonGEP::getAllUsersForNode(GepNode *Node, ValueVect &Values,
1132       NodeChildrenMap &NCM) {
1133   NodeVect Work;
1134   Work.push_back(Node);
1135 
1136   while (!Work.empty()) {
1137     NodeVect::iterator First = Work.begin();
1138     GepNode *N = *First;
1139     Work.erase(First);
1140     if (N->Flags & GepNode::Used) {
1141       NodeToUsesMap::iterator UF = Uses.find(N);
1142       assert(UF != Uses.end() && "No use information for used node");
1143       UseSet &Us = UF->second;
1144       for (UseSet::iterator I = Us.begin(), E = Us.end(); I != E; ++I)
1145         Values.push_back((*I)->getUser());
1146     }
1147     NodeChildrenMap::iterator CF = NCM.find(N);
1148     if (CF != NCM.end()) {
1149       NodeVect &Cs = CF->second;
1150       Work.insert(Work.end(), Cs.begin(), Cs.end());
1151     }
1152   }
1153 }
1154 
1155 void HexagonCommonGEP::materialize(NodeToValueMap &Loc) {
1156   DEBUG(dbgs() << "Nodes before materialization:\n" << Nodes << '\n');
1157   NodeChildrenMap NCM;
1158   NodeVect Roots;
1159   // Compute the inversion again, since computing placement could alter
1160   // "parent" relation between nodes.
1161   invert_find_roots(Nodes, NCM, Roots);
1162 
1163   while (!Roots.empty()) {
1164     NodeVect::iterator First = Roots.begin();
1165     GepNode *Root = *First, *Last = *First;
1166     Roots.erase(First);
1167 
1168     NodeVect NA;  // Nodes to assemble.
1169     // Append to NA all child nodes up to (and including) the first child
1170     // that:
1171     // (1) has more than 1 child, or
1172     // (2) is used, or
1173     // (3) has a child located in a different block.
1174     bool LastUsed = false;
1175     unsigned LastCN = 0;
1176     // The location may be null if the computation failed (it can legitimately
1177     // happen for nodes created from dead GEPs).
1178     Value *LocV = Loc[Last];
1179     if (!LocV)
1180       continue;
1181     BasicBlock *LastB = cast<BasicBlock>(LocV);
1182     do {
1183       NA.push_back(Last);
1184       LastUsed = (Last->Flags & GepNode::Used);
1185       if (LastUsed)
1186         break;
1187       NodeChildrenMap::iterator CF = NCM.find(Last);
1188       LastCN = (CF != NCM.end()) ? CF->second.size() : 0;
1189       if (LastCN != 1)
1190         break;
1191       GepNode *Child = CF->second.front();
1192       BasicBlock *ChildB = cast_or_null<BasicBlock>(Loc[Child]);
1193       if (ChildB != nullptr && LastB != ChildB)
1194         break;
1195       Last = Child;
1196     } while (true);
1197 
1198     BasicBlock::iterator InsertAt = LastB->getTerminator()->getIterator();
1199     if (LastUsed || LastCN > 0) {
1200       ValueVect Urs;
1201       getAllUsersForNode(Root, Urs, NCM);
1202       BasicBlock::iterator FirstUse = first_use_of_in_block(Urs, LastB);
1203       if (FirstUse != LastB->end())
1204         InsertAt = FirstUse;
1205     }
1206 
1207     // Generate a new instruction for NA.
1208     Value *NewInst = fabricateGEP(NA, InsertAt, LastB);
1209 
1210     // Convert all the children of Last node into roots, and append them
1211     // to the Roots list.
1212     if (LastCN > 0) {
1213       NodeVect &Cs = NCM[Last];
1214       for (NodeVect::iterator I = Cs.begin(), E = Cs.end(); I != E; ++I) {
1215         GepNode *CN = *I;
1216         CN->Flags &= ~GepNode::Internal;
1217         CN->Flags |= GepNode::Root;
1218         CN->BaseVal = NewInst;
1219         Roots.push_back(CN);
1220       }
1221     }
1222 
1223     // Lastly, if the Last node was used, replace all uses with the new GEP.
1224     // The uses reference the original GEP values.
1225     if (LastUsed) {
1226       NodeToUsesMap::iterator UF = Uses.find(Last);
1227       assert(UF != Uses.end() && "No use information found");
1228       UseSet &Us = UF->second;
1229       for (UseSet::iterator I = Us.begin(), E = Us.end(); I != E; ++I) {
1230         Use *U = *I;
1231         U->set(NewInst);
1232       }
1233     }
1234   }
1235 }
1236 
1237 void HexagonCommonGEP::removeDeadCode() {
1238   ValueVect BO;
1239   BO.push_back(&Fn->front());
1240 
1241   for (unsigned i = 0; i < BO.size(); ++i) {
1242     BasicBlock *B = cast<BasicBlock>(BO[i]);
1243     for (auto DTN : children<DomTreeNode*>(DT->getNode(B)))
1244       BO.push_back(DTN->getBlock());
1245   }
1246 
1247   for (unsigned i = BO.size(); i > 0; --i) {
1248     BasicBlock *B = cast<BasicBlock>(BO[i-1]);
1249     BasicBlock::InstListType &IL = B->getInstList();
1250     typedef BasicBlock::InstListType::reverse_iterator reverse_iterator;
1251     ValueVect Ins;
1252     for (reverse_iterator I = IL.rbegin(), E = IL.rend(); I != E; ++I)
1253       Ins.push_back(&*I);
1254     for (ValueVect::iterator I = Ins.begin(), E = Ins.end(); I != E; ++I) {
1255       Instruction *In = cast<Instruction>(*I);
1256       if (isInstructionTriviallyDead(In))
1257         In->eraseFromParent();
1258     }
1259   }
1260 }
1261 
1262 bool HexagonCommonGEP::runOnFunction(Function &F) {
1263   if (skipFunction(F))
1264     return false;
1265 
1266   // For now bail out on C++ exception handling.
1267   for (Function::iterator A = F.begin(), Z = F.end(); A != Z; ++A)
1268     for (BasicBlock::iterator I = A->begin(), E = A->end(); I != E; ++I)
1269       if (isa<InvokeInst>(I) || isa<LandingPadInst>(I))
1270         return false;
1271 
1272   Fn = &F;
1273   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1274   PDT = &getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
1275   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1276   Ctx = &F.getContext();
1277 
1278   Nodes.clear();
1279   Uses.clear();
1280   NodeOrder.clear();
1281 
1282   SpecificBumpPtrAllocator<GepNode> Allocator;
1283   Mem = &Allocator;
1284 
1285   collect();
1286   common();
1287 
1288   NodeToValueMap Loc;
1289   computeNodePlacement(Loc);
1290   materialize(Loc);
1291   removeDeadCode();
1292 
1293 #ifdef EXPENSIVE_CHECKS
1294   // Run this only when expensive checks are enabled.
1295   verifyFunction(F);
1296 #endif
1297   return true;
1298 }
1299 
1300 namespace llvm {
1301 
1302   FunctionPass *createHexagonCommonGEP() {
1303     return new HexagonCommonGEP();
1304   }
1305 
1306 } // end namespace llvm
1307