109467b48Spatrick //===- HexagonCommonGEP.cpp -----------------------------------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick
909467b48Spatrick #include "llvm/ADT/ArrayRef.h"
1009467b48Spatrick #include "llvm/ADT/FoldingSet.h"
1109467b48Spatrick #include "llvm/ADT/GraphTraits.h"
1209467b48Spatrick #include "llvm/ADT/STLExtras.h"
1309467b48Spatrick #include "llvm/ADT/SetVector.h"
1473471bf0Spatrick #include "llvm/ADT/SmallVector.h"
1509467b48Spatrick #include "llvm/ADT/StringRef.h"
1609467b48Spatrick #include "llvm/Analysis/LoopInfo.h"
1709467b48Spatrick #include "llvm/Analysis/PostDominators.h"
1809467b48Spatrick #include "llvm/IR/BasicBlock.h"
1909467b48Spatrick #include "llvm/IR/Constant.h"
2009467b48Spatrick #include "llvm/IR/Constants.h"
2109467b48Spatrick #include "llvm/IR/DerivedTypes.h"
2209467b48Spatrick #include "llvm/IR/Dominators.h"
2309467b48Spatrick #include "llvm/IR/Function.h"
2409467b48Spatrick #include "llvm/IR/Instruction.h"
2509467b48Spatrick #include "llvm/IR/Instructions.h"
2609467b48Spatrick #include "llvm/IR/Type.h"
2709467b48Spatrick #include "llvm/IR/Use.h"
2809467b48Spatrick #include "llvm/IR/User.h"
2909467b48Spatrick #include "llvm/IR/Value.h"
3009467b48Spatrick #include "llvm/IR/Verifier.h"
3109467b48Spatrick #include "llvm/InitializePasses.h"
3209467b48Spatrick #include "llvm/Pass.h"
3309467b48Spatrick #include "llvm/Support/Allocator.h"
3409467b48Spatrick #include "llvm/Support/Casting.h"
3509467b48Spatrick #include "llvm/Support/CommandLine.h"
3609467b48Spatrick #include "llvm/Support/Compiler.h"
3709467b48Spatrick #include "llvm/Support/Debug.h"
3809467b48Spatrick #include "llvm/Support/raw_ostream.h"
3909467b48Spatrick #include "llvm/Transforms/Utils/Local.h"
4009467b48Spatrick #include <algorithm>
4109467b48Spatrick #include <cassert>
4209467b48Spatrick #include <cstddef>
4309467b48Spatrick #include <cstdint>
4409467b48Spatrick #include <iterator>
4509467b48Spatrick #include <map>
4609467b48Spatrick #include <set>
4709467b48Spatrick #include <utility>
4809467b48Spatrick #include <vector>
4909467b48Spatrick
5009467b48Spatrick #define DEBUG_TYPE "commgep"
5109467b48Spatrick
5209467b48Spatrick using namespace llvm;
5309467b48Spatrick
5409467b48Spatrick static cl::opt<bool> OptSpeculate("commgep-speculate", cl::init(true),
55*d415bd75Srobert cl::Hidden);
5609467b48Spatrick
57*d415bd75Srobert static cl::opt<bool> OptEnableInv("commgep-inv", cl::init(true), cl::Hidden);
5809467b48Spatrick
5909467b48Spatrick static cl::opt<bool> OptEnableConst("commgep-const", cl::init(true),
60*d415bd75Srobert cl::Hidden);
6109467b48Spatrick
6209467b48Spatrick namespace llvm {
6309467b48Spatrick
6409467b48Spatrick void initializeHexagonCommonGEPPass(PassRegistry&);
6509467b48Spatrick
6609467b48Spatrick } // end namespace llvm
6709467b48Spatrick
6809467b48Spatrick namespace {
6909467b48Spatrick
7009467b48Spatrick struct GepNode;
7109467b48Spatrick using NodeSet = std::set<GepNode *>;
7209467b48Spatrick using NodeToValueMap = std::map<GepNode *, Value *>;
7309467b48Spatrick using NodeVect = std::vector<GepNode *>;
7409467b48Spatrick using NodeChildrenMap = std::map<GepNode *, NodeVect>;
7509467b48Spatrick using UseSet = SetVector<Use *>;
7609467b48Spatrick using NodeToUsesMap = std::map<GepNode *, UseSet>;
7709467b48Spatrick
7809467b48Spatrick // Numbering map for gep nodes. Used to keep track of ordering for
7909467b48Spatrick // gep nodes.
8009467b48Spatrick struct NodeOrdering {
8109467b48Spatrick NodeOrdering() = default;
8209467b48Spatrick
insert__anon16873bc50111::NodeOrdering8309467b48Spatrick void insert(const GepNode *N) { Map.insert(std::make_pair(N, ++LastNum)); }
clear__anon16873bc50111::NodeOrdering8409467b48Spatrick void clear() { Map.clear(); }
8509467b48Spatrick
operator ()__anon16873bc50111::NodeOrdering8609467b48Spatrick bool operator()(const GepNode *N1, const GepNode *N2) const {
8709467b48Spatrick auto F1 = Map.find(N1), F2 = Map.find(N2);
8809467b48Spatrick assert(F1 != Map.end() && F2 != Map.end());
8909467b48Spatrick return F1->second < F2->second;
9009467b48Spatrick }
9109467b48Spatrick
9209467b48Spatrick private:
9309467b48Spatrick std::map<const GepNode *, unsigned> Map;
9409467b48Spatrick unsigned LastNum = 0;
9509467b48Spatrick };
9609467b48Spatrick
9709467b48Spatrick class HexagonCommonGEP : public FunctionPass {
9809467b48Spatrick public:
9909467b48Spatrick static char ID;
10009467b48Spatrick
HexagonCommonGEP()10109467b48Spatrick HexagonCommonGEP() : FunctionPass(ID) {
10209467b48Spatrick initializeHexagonCommonGEPPass(*PassRegistry::getPassRegistry());
10309467b48Spatrick }
10409467b48Spatrick
10509467b48Spatrick bool runOnFunction(Function &F) override;
getPassName() const10609467b48Spatrick StringRef getPassName() const override { return "Hexagon Common GEP"; }
10709467b48Spatrick
getAnalysisUsage(AnalysisUsage & AU) const10809467b48Spatrick void getAnalysisUsage(AnalysisUsage &AU) const override {
10909467b48Spatrick AU.addRequired<DominatorTreeWrapperPass>();
11009467b48Spatrick AU.addPreserved<DominatorTreeWrapperPass>();
11109467b48Spatrick AU.addRequired<PostDominatorTreeWrapperPass>();
11209467b48Spatrick AU.addPreserved<PostDominatorTreeWrapperPass>();
11309467b48Spatrick AU.addRequired<LoopInfoWrapperPass>();
11409467b48Spatrick AU.addPreserved<LoopInfoWrapperPass>();
11509467b48Spatrick FunctionPass::getAnalysisUsage(AU);
11609467b48Spatrick }
11709467b48Spatrick
11809467b48Spatrick private:
11909467b48Spatrick using ValueToNodeMap = std::map<Value *, GepNode *>;
12009467b48Spatrick using ValueVect = std::vector<Value *>;
12109467b48Spatrick using NodeToValuesMap = std::map<GepNode *, ValueVect>;
12209467b48Spatrick
12309467b48Spatrick void getBlockTraversalOrder(BasicBlock *Root, ValueVect &Order);
12409467b48Spatrick bool isHandledGepForm(GetElementPtrInst *GepI);
12509467b48Spatrick void processGepInst(GetElementPtrInst *GepI, ValueToNodeMap &NM);
12609467b48Spatrick void collect();
12709467b48Spatrick void common();
12809467b48Spatrick
12909467b48Spatrick BasicBlock *recalculatePlacement(GepNode *Node, NodeChildrenMap &NCM,
13009467b48Spatrick NodeToValueMap &Loc);
13109467b48Spatrick BasicBlock *recalculatePlacementRec(GepNode *Node, NodeChildrenMap &NCM,
13209467b48Spatrick NodeToValueMap &Loc);
13309467b48Spatrick bool isInvariantIn(Value *Val, Loop *L);
13409467b48Spatrick bool isInvariantIn(GepNode *Node, Loop *L);
13509467b48Spatrick bool isInMainPath(BasicBlock *B, Loop *L);
13609467b48Spatrick BasicBlock *adjustForInvariance(GepNode *Node, NodeChildrenMap &NCM,
13709467b48Spatrick NodeToValueMap &Loc);
13809467b48Spatrick void separateChainForNode(GepNode *Node, Use *U, NodeToValueMap &Loc);
13909467b48Spatrick void separateConstantChains(GepNode *Node, NodeChildrenMap &NCM,
14009467b48Spatrick NodeToValueMap &Loc);
14109467b48Spatrick void computeNodePlacement(NodeToValueMap &Loc);
14209467b48Spatrick
14309467b48Spatrick Value *fabricateGEP(NodeVect &NA, BasicBlock::iterator At,
14409467b48Spatrick BasicBlock *LocB);
14509467b48Spatrick void getAllUsersForNode(GepNode *Node, ValueVect &Values,
14609467b48Spatrick NodeChildrenMap &NCM);
14709467b48Spatrick void materialize(NodeToValueMap &Loc);
14809467b48Spatrick
14909467b48Spatrick void removeDeadCode();
15009467b48Spatrick
15109467b48Spatrick NodeVect Nodes;
15209467b48Spatrick NodeToUsesMap Uses;
15309467b48Spatrick NodeOrdering NodeOrder; // Node ordering, for deterministic behavior.
15409467b48Spatrick SpecificBumpPtrAllocator<GepNode> *Mem;
15509467b48Spatrick LLVMContext *Ctx;
15609467b48Spatrick LoopInfo *LI;
15709467b48Spatrick DominatorTree *DT;
15809467b48Spatrick PostDominatorTree *PDT;
15909467b48Spatrick Function *Fn;
16009467b48Spatrick };
16109467b48Spatrick
16209467b48Spatrick } // end anonymous namespace
16309467b48Spatrick
16409467b48Spatrick char HexagonCommonGEP::ID = 0;
16509467b48Spatrick
16609467b48Spatrick INITIALIZE_PASS_BEGIN(HexagonCommonGEP, "hcommgep", "Hexagon Common GEP",
16709467b48Spatrick false, false)
16809467b48Spatrick INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
16909467b48Spatrick INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
17009467b48Spatrick INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
17109467b48Spatrick INITIALIZE_PASS_END(HexagonCommonGEP, "hcommgep", "Hexagon Common GEP",
17209467b48Spatrick false, false)
17309467b48Spatrick
17409467b48Spatrick namespace {
17509467b48Spatrick
17609467b48Spatrick struct GepNode {
17709467b48Spatrick enum {
17809467b48Spatrick None = 0,
17909467b48Spatrick Root = 0x01,
18009467b48Spatrick Internal = 0x02,
18109467b48Spatrick Used = 0x04,
18273471bf0Spatrick InBounds = 0x08,
18373471bf0Spatrick Pointer = 0x10, // See note below.
18409467b48Spatrick };
18573471bf0Spatrick // Note: GEP indices generally traverse nested types, and so a GepNode
18673471bf0Spatrick // (representing a single index) can be associated with some composite
18773471bf0Spatrick // type. The exception is the GEP input, which is a pointer, and not
18873471bf0Spatrick // a composite type (at least not in the sense of having sub-types).
18973471bf0Spatrick // Also, the corresponding index plays a different role as well: it is
19073471bf0Spatrick // simply added to the input pointer. Since pointer types are becoming
19173471bf0Spatrick // opaque (i.e. are no longer going to include the pointee type), the
19273471bf0Spatrick // two pieces of information (1) the fact that it's a pointer, and
19373471bf0Spatrick // (2) the pointee type, need to be stored separately. The pointee type
19473471bf0Spatrick // will be stored in the PTy member, while the fact that the node
19573471bf0Spatrick // operates on a pointer will be reflected by the flag "Pointer".
19609467b48Spatrick
19709467b48Spatrick uint32_t Flags = 0;
19809467b48Spatrick union {
19909467b48Spatrick GepNode *Parent;
20009467b48Spatrick Value *BaseVal;
20109467b48Spatrick };
20209467b48Spatrick Value *Idx = nullptr;
20373471bf0Spatrick Type *PTy = nullptr; // Type indexed by this node. For pointer nodes
20473471bf0Spatrick // this is the "pointee" type, and indexing a
20573471bf0Spatrick // pointer does not change the type.
20609467b48Spatrick
GepNode__anon16873bc50211::GepNode20709467b48Spatrick GepNode() : Parent(nullptr) {}
GepNode__anon16873bc50211::GepNode20809467b48Spatrick GepNode(const GepNode *N) : Flags(N->Flags), Idx(N->Idx), PTy(N->PTy) {
20909467b48Spatrick if (Flags & Root)
21009467b48Spatrick BaseVal = N->BaseVal;
21109467b48Spatrick else
21209467b48Spatrick Parent = N->Parent;
21309467b48Spatrick }
21409467b48Spatrick
21509467b48Spatrick friend raw_ostream &operator<< (raw_ostream &OS, const GepNode &GN);
21609467b48Spatrick };
21709467b48Spatrick
operator <<(raw_ostream & OS,const GepNode & GN)21809467b48Spatrick raw_ostream &operator<< (raw_ostream &OS, const GepNode &GN) {
21909467b48Spatrick OS << "{ {";
22009467b48Spatrick bool Comma = false;
22109467b48Spatrick if (GN.Flags & GepNode::Root) {
22209467b48Spatrick OS << "root";
22309467b48Spatrick Comma = true;
22409467b48Spatrick }
22509467b48Spatrick if (GN.Flags & GepNode::Internal) {
22609467b48Spatrick if (Comma)
22709467b48Spatrick OS << ',';
22809467b48Spatrick OS << "internal";
22909467b48Spatrick Comma = true;
23009467b48Spatrick }
23109467b48Spatrick if (GN.Flags & GepNode::Used) {
23209467b48Spatrick if (Comma)
23309467b48Spatrick OS << ',';
23409467b48Spatrick OS << "used";
23509467b48Spatrick }
23609467b48Spatrick if (GN.Flags & GepNode::InBounds) {
23709467b48Spatrick if (Comma)
23809467b48Spatrick OS << ',';
23909467b48Spatrick OS << "inbounds";
24009467b48Spatrick }
24173471bf0Spatrick if (GN.Flags & GepNode::Pointer) {
24273471bf0Spatrick if (Comma)
24373471bf0Spatrick OS << ',';
24473471bf0Spatrick OS << "pointer";
24573471bf0Spatrick }
24609467b48Spatrick OS << "} ";
24709467b48Spatrick if (GN.Flags & GepNode::Root)
24809467b48Spatrick OS << "BaseVal:" << GN.BaseVal->getName() << '(' << GN.BaseVal << ')';
24909467b48Spatrick else
25009467b48Spatrick OS << "Parent:" << GN.Parent;
25109467b48Spatrick
25209467b48Spatrick OS << " Idx:";
25309467b48Spatrick if (ConstantInt *CI = dyn_cast<ConstantInt>(GN.Idx))
25409467b48Spatrick OS << CI->getValue().getSExtValue();
25509467b48Spatrick else if (GN.Idx->hasName())
25609467b48Spatrick OS << GN.Idx->getName();
25709467b48Spatrick else
25809467b48Spatrick OS << "<anon> =" << *GN.Idx;
25909467b48Spatrick
26009467b48Spatrick OS << " PTy:";
26109467b48Spatrick if (GN.PTy->isStructTy()) {
26209467b48Spatrick StructType *STy = cast<StructType>(GN.PTy);
26309467b48Spatrick if (!STy->isLiteral())
26409467b48Spatrick OS << GN.PTy->getStructName();
26509467b48Spatrick else
26609467b48Spatrick OS << "<anon-struct>:" << *STy;
26709467b48Spatrick }
26809467b48Spatrick else
26909467b48Spatrick OS << *GN.PTy;
27009467b48Spatrick OS << " }";
27109467b48Spatrick return OS;
27209467b48Spatrick }
27309467b48Spatrick
27409467b48Spatrick template <typename NodeContainer>
dump_node_container(raw_ostream & OS,const NodeContainer & S)27509467b48Spatrick void dump_node_container(raw_ostream &OS, const NodeContainer &S) {
27609467b48Spatrick using const_iterator = typename NodeContainer::const_iterator;
27709467b48Spatrick
27809467b48Spatrick for (const_iterator I = S.begin(), E = S.end(); I != E; ++I)
27909467b48Spatrick OS << *I << ' ' << **I << '\n';
28009467b48Spatrick }
28109467b48Spatrick
28209467b48Spatrick raw_ostream &operator<< (raw_ostream &OS,
28309467b48Spatrick const NodeVect &S) LLVM_ATTRIBUTE_UNUSED;
operator <<(raw_ostream & OS,const NodeVect & S)28409467b48Spatrick raw_ostream &operator<< (raw_ostream &OS, const NodeVect &S) {
28509467b48Spatrick dump_node_container(OS, S);
28609467b48Spatrick return OS;
28709467b48Spatrick }
28809467b48Spatrick
28909467b48Spatrick raw_ostream &operator<< (raw_ostream &OS,
29009467b48Spatrick const NodeToUsesMap &M) LLVM_ATTRIBUTE_UNUSED;
operator <<(raw_ostream & OS,const NodeToUsesMap & M)29109467b48Spatrick raw_ostream &operator<< (raw_ostream &OS, const NodeToUsesMap &M){
292*d415bd75Srobert for (const auto &I : M) {
293*d415bd75Srobert const UseSet &Us = I.second;
294*d415bd75Srobert OS << I.first << " -> #" << Us.size() << '{';
295*d415bd75Srobert for (const Use *U : Us) {
296*d415bd75Srobert User *R = U->getUser();
29709467b48Spatrick if (R->hasName())
29809467b48Spatrick OS << ' ' << R->getName();
29909467b48Spatrick else
30009467b48Spatrick OS << " <?>(" << *R << ')';
30109467b48Spatrick }
30209467b48Spatrick OS << " }\n";
30309467b48Spatrick }
30409467b48Spatrick return OS;
30509467b48Spatrick }
30609467b48Spatrick
30709467b48Spatrick struct in_set {
in_set__anon16873bc50211::in_set30809467b48Spatrick in_set(const NodeSet &S) : NS(S) {}
30909467b48Spatrick
operator ()__anon16873bc50211::in_set31009467b48Spatrick bool operator() (GepNode *N) const {
31109467b48Spatrick return NS.find(N) != NS.end();
31209467b48Spatrick }
31309467b48Spatrick
31409467b48Spatrick private:
31509467b48Spatrick const NodeSet &NS;
31609467b48Spatrick };
31709467b48Spatrick
31809467b48Spatrick } // end anonymous namespace
31909467b48Spatrick
operator new(size_t,SpecificBumpPtrAllocator<GepNode> & A)32009467b48Spatrick inline void *operator new(size_t, SpecificBumpPtrAllocator<GepNode> &A) {
32109467b48Spatrick return A.Allocate();
32209467b48Spatrick }
32309467b48Spatrick
getBlockTraversalOrder(BasicBlock * Root,ValueVect & Order)32409467b48Spatrick void HexagonCommonGEP::getBlockTraversalOrder(BasicBlock *Root,
32509467b48Spatrick ValueVect &Order) {
32609467b48Spatrick // Compute block ordering for a typical DT-based traversal of the flow
32709467b48Spatrick // graph: "before visiting a block, all of its dominators must have been
32809467b48Spatrick // visited".
32909467b48Spatrick
33009467b48Spatrick Order.push_back(Root);
33109467b48Spatrick for (auto *DTN : children<DomTreeNode*>(DT->getNode(Root)))
33209467b48Spatrick getBlockTraversalOrder(DTN->getBlock(), Order);
33309467b48Spatrick }
33409467b48Spatrick
isHandledGepForm(GetElementPtrInst * GepI)33509467b48Spatrick bool HexagonCommonGEP::isHandledGepForm(GetElementPtrInst *GepI) {
33609467b48Spatrick // No vector GEPs.
33709467b48Spatrick if (!GepI->getType()->isPointerTy())
33809467b48Spatrick return false;
33909467b48Spatrick // No GEPs without any indices. (Is this possible?)
34009467b48Spatrick if (GepI->idx_begin() == GepI->idx_end())
34109467b48Spatrick return false;
34209467b48Spatrick return true;
34309467b48Spatrick }
34409467b48Spatrick
processGepInst(GetElementPtrInst * GepI,ValueToNodeMap & NM)34509467b48Spatrick void HexagonCommonGEP::processGepInst(GetElementPtrInst *GepI,
34609467b48Spatrick ValueToNodeMap &NM) {
34709467b48Spatrick LLVM_DEBUG(dbgs() << "Visiting GEP: " << *GepI << '\n');
34809467b48Spatrick GepNode *N = new (*Mem) GepNode;
34909467b48Spatrick Value *PtrOp = GepI->getPointerOperand();
35009467b48Spatrick uint32_t InBounds = GepI->isInBounds() ? GepNode::InBounds : 0;
35109467b48Spatrick ValueToNodeMap::iterator F = NM.find(PtrOp);
35209467b48Spatrick if (F == NM.end()) {
35309467b48Spatrick N->BaseVal = PtrOp;
35409467b48Spatrick N->Flags |= GepNode::Root | InBounds;
35509467b48Spatrick } else {
35609467b48Spatrick // If PtrOp was a GEP instruction, it must have already been processed.
35709467b48Spatrick // The ValueToNodeMap entry for it is the last gep node in the generated
35809467b48Spatrick // chain. Link to it here.
35909467b48Spatrick N->Parent = F->second;
36009467b48Spatrick }
36173471bf0Spatrick N->PTy = GepI->getSourceElementType();
36273471bf0Spatrick N->Flags |= GepNode::Pointer;
36309467b48Spatrick N->Idx = *GepI->idx_begin();
36409467b48Spatrick
36509467b48Spatrick // Collect the list of users of this GEP instruction. Will add it to the
36609467b48Spatrick // last node created for it.
36709467b48Spatrick UseSet Us;
36809467b48Spatrick for (Value::user_iterator UI = GepI->user_begin(), UE = GepI->user_end();
36909467b48Spatrick UI != UE; ++UI) {
37009467b48Spatrick // Check if this gep is used by anything other than other geps that
37109467b48Spatrick // we will process.
37209467b48Spatrick if (isa<GetElementPtrInst>(*UI)) {
37309467b48Spatrick GetElementPtrInst *UserG = cast<GetElementPtrInst>(*UI);
37409467b48Spatrick if (isHandledGepForm(UserG))
37509467b48Spatrick continue;
37609467b48Spatrick }
37709467b48Spatrick Us.insert(&UI.getUse());
37809467b48Spatrick }
37909467b48Spatrick Nodes.push_back(N);
38009467b48Spatrick NodeOrder.insert(N);
38109467b48Spatrick
38273471bf0Spatrick // Skip the first index operand, since it was already handled above. This
38373471bf0Spatrick // dereferences the pointer operand.
38409467b48Spatrick GepNode *PN = N;
38573471bf0Spatrick Type *PtrTy = GepI->getSourceElementType();
386*d415bd75Srobert for (Use &U : llvm::drop_begin(GepI->indices())) {
387*d415bd75Srobert Value *Op = U;
38809467b48Spatrick GepNode *Nx = new (*Mem) GepNode;
38909467b48Spatrick Nx->Parent = PN; // Link Nx to the previous node.
39009467b48Spatrick Nx->Flags |= GepNode::Internal | InBounds;
39109467b48Spatrick Nx->PTy = PtrTy;
39209467b48Spatrick Nx->Idx = Op;
39309467b48Spatrick Nodes.push_back(Nx);
39409467b48Spatrick NodeOrder.insert(Nx);
39509467b48Spatrick PN = Nx;
39609467b48Spatrick
39773471bf0Spatrick PtrTy = GetElementPtrInst::getTypeAtIndex(PtrTy, Op);
39809467b48Spatrick }
39909467b48Spatrick
40009467b48Spatrick // After last node has been created, update the use information.
40109467b48Spatrick if (!Us.empty()) {
40209467b48Spatrick PN->Flags |= GepNode::Used;
40309467b48Spatrick Uses[PN].insert(Us.begin(), Us.end());
40409467b48Spatrick }
40509467b48Spatrick
40609467b48Spatrick // Link the last node with the originating GEP instruction. This is to
40709467b48Spatrick // help with linking chained GEP instructions.
40809467b48Spatrick NM.insert(std::make_pair(GepI, PN));
40909467b48Spatrick }
41009467b48Spatrick
collect()41109467b48Spatrick void HexagonCommonGEP::collect() {
41209467b48Spatrick // Establish depth-first traversal order of the dominator tree.
41309467b48Spatrick ValueVect BO;
41409467b48Spatrick getBlockTraversalOrder(&Fn->front(), BO);
41509467b48Spatrick
41609467b48Spatrick // The creation of gep nodes requires DT-traversal. When processing a GEP
41709467b48Spatrick // instruction that uses another GEP instruction as the base pointer, the
41809467b48Spatrick // gep node for the base pointer should already exist.
41909467b48Spatrick ValueToNodeMap NM;
420*d415bd75Srobert for (Value *I : BO) {
421*d415bd75Srobert BasicBlock *B = cast<BasicBlock>(I);
422*d415bd75Srobert for (Instruction &J : *B)
423*d415bd75Srobert if (auto *GepI = dyn_cast<GetElementPtrInst>(&J))
42409467b48Spatrick if (isHandledGepForm(GepI))
42509467b48Spatrick processGepInst(GepI, NM);
42609467b48Spatrick }
42709467b48Spatrick
42809467b48Spatrick LLVM_DEBUG(dbgs() << "Gep nodes after initial collection:\n" << Nodes);
42909467b48Spatrick }
43009467b48Spatrick
invert_find_roots(const NodeVect & Nodes,NodeChildrenMap & NCM,NodeVect & Roots)43109467b48Spatrick static void invert_find_roots(const NodeVect &Nodes, NodeChildrenMap &NCM,
43209467b48Spatrick NodeVect &Roots) {
433*d415bd75Srobert for (GepNode *N : Nodes) {
43409467b48Spatrick if (N->Flags & GepNode::Root) {
43509467b48Spatrick Roots.push_back(N);
43609467b48Spatrick continue;
43709467b48Spatrick }
43809467b48Spatrick GepNode *PN = N->Parent;
43909467b48Spatrick NCM[PN].push_back(N);
44009467b48Spatrick }
44109467b48Spatrick }
44209467b48Spatrick
nodes_for_root(GepNode * Root,NodeChildrenMap & NCM,NodeSet & Nodes)44309467b48Spatrick static void nodes_for_root(GepNode *Root, NodeChildrenMap &NCM,
44409467b48Spatrick NodeSet &Nodes) {
44509467b48Spatrick NodeVect Work;
44609467b48Spatrick Work.push_back(Root);
44709467b48Spatrick Nodes.insert(Root);
44809467b48Spatrick
44909467b48Spatrick while (!Work.empty()) {
45009467b48Spatrick NodeVect::iterator First = Work.begin();
45109467b48Spatrick GepNode *N = *First;
45209467b48Spatrick Work.erase(First);
45309467b48Spatrick NodeChildrenMap::iterator CF = NCM.find(N);
45409467b48Spatrick if (CF != NCM.end()) {
45573471bf0Spatrick llvm::append_range(Work, CF->second);
45609467b48Spatrick Nodes.insert(CF->second.begin(), CF->second.end());
45709467b48Spatrick }
45809467b48Spatrick }
45909467b48Spatrick }
46009467b48Spatrick
46109467b48Spatrick namespace {
46209467b48Spatrick
46309467b48Spatrick using NodeSymRel = std::set<NodeSet>;
46409467b48Spatrick using NodePair = std::pair<GepNode *, GepNode *>;
46509467b48Spatrick using NodePairSet = std::set<NodePair>;
46609467b48Spatrick
46709467b48Spatrick } // end anonymous namespace
46809467b48Spatrick
node_class(GepNode * N,NodeSymRel & Rel)46909467b48Spatrick static const NodeSet *node_class(GepNode *N, NodeSymRel &Rel) {
470*d415bd75Srobert for (const NodeSet &S : Rel)
471*d415bd75Srobert if (S.count(N))
472*d415bd75Srobert return &S;
47309467b48Spatrick return nullptr;
47409467b48Spatrick }
47509467b48Spatrick
47609467b48Spatrick // Create an ordered pair of GepNode pointers. The pair will be used in
47709467b48Spatrick // determining equality. The only purpose of the ordering is to eliminate
47809467b48Spatrick // duplication due to the commutativity of equality/non-equality.
node_pair(GepNode * N1,GepNode * N2)47909467b48Spatrick static NodePair node_pair(GepNode *N1, GepNode *N2) {
48073471bf0Spatrick uintptr_t P1 = reinterpret_cast<uintptr_t>(N1);
48173471bf0Spatrick uintptr_t P2 = reinterpret_cast<uintptr_t>(N2);
48209467b48Spatrick if (P1 <= P2)
48309467b48Spatrick return std::make_pair(N1, N2);
48409467b48Spatrick return std::make_pair(N2, N1);
48509467b48Spatrick }
48609467b48Spatrick
node_hash(GepNode * N)48709467b48Spatrick static unsigned node_hash(GepNode *N) {
48809467b48Spatrick // Include everything except flags and parent.
48909467b48Spatrick FoldingSetNodeID ID;
49009467b48Spatrick ID.AddPointer(N->Idx);
49109467b48Spatrick ID.AddPointer(N->PTy);
49209467b48Spatrick return ID.ComputeHash();
49309467b48Spatrick }
49409467b48Spatrick
node_eq(GepNode * N1,GepNode * N2,NodePairSet & Eq,NodePairSet & Ne)49509467b48Spatrick static bool node_eq(GepNode *N1, GepNode *N2, NodePairSet &Eq,
49609467b48Spatrick NodePairSet &Ne) {
49709467b48Spatrick // Don't cache the result for nodes with different hashes. The hash
49809467b48Spatrick // comparison is fast enough.
49909467b48Spatrick if (node_hash(N1) != node_hash(N2))
50009467b48Spatrick return false;
50109467b48Spatrick
50209467b48Spatrick NodePair NP = node_pair(N1, N2);
50309467b48Spatrick NodePairSet::iterator FEq = Eq.find(NP);
50409467b48Spatrick if (FEq != Eq.end())
50509467b48Spatrick return true;
50609467b48Spatrick NodePairSet::iterator FNe = Ne.find(NP);
50709467b48Spatrick if (FNe != Ne.end())
50809467b48Spatrick return false;
50909467b48Spatrick // Not previously compared.
51009467b48Spatrick bool Root1 = N1->Flags & GepNode::Root;
51173471bf0Spatrick uint32_t CmpFlags = GepNode::Root | GepNode::Pointer;
51273471bf0Spatrick bool Different = (N1->Flags & CmpFlags) != (N2->Flags & CmpFlags);
51309467b48Spatrick NodePair P = node_pair(N1, N2);
51473471bf0Spatrick // If the root/pointer flags have different values, the nodes are
51573471bf0Spatrick // different.
51609467b48Spatrick // If both nodes are root nodes, but their base pointers differ,
51709467b48Spatrick // they are different.
51873471bf0Spatrick if (Different || (Root1 && N1->BaseVal != N2->BaseVal)) {
51909467b48Spatrick Ne.insert(P);
52009467b48Spatrick return false;
52109467b48Spatrick }
52273471bf0Spatrick // Here the root/pointer flags are identical, and for root nodes the
52309467b48Spatrick // base pointers are equal, so the root nodes are equal.
52409467b48Spatrick // For non-root nodes, compare their parent nodes.
52509467b48Spatrick if (Root1 || node_eq(N1->Parent, N2->Parent, Eq, Ne)) {
52609467b48Spatrick Eq.insert(P);
52709467b48Spatrick return true;
52809467b48Spatrick }
52909467b48Spatrick return false;
53009467b48Spatrick }
53109467b48Spatrick
common()53209467b48Spatrick void HexagonCommonGEP::common() {
53309467b48Spatrick // The essence of this commoning is finding gep nodes that are equal.
53409467b48Spatrick // To do this we need to compare all pairs of nodes. To save time,
53509467b48Spatrick // first, partition the set of all nodes into sets of potentially equal
53609467b48Spatrick // nodes, and then compare pairs from within each partition.
53709467b48Spatrick using NodeSetMap = std::map<unsigned, NodeSet>;
53809467b48Spatrick NodeSetMap MaybeEq;
53909467b48Spatrick
540*d415bd75Srobert for (GepNode *N : Nodes) {
54109467b48Spatrick unsigned H = node_hash(N);
54209467b48Spatrick MaybeEq[H].insert(N);
54309467b48Spatrick }
54409467b48Spatrick
54509467b48Spatrick // Compute the equivalence relation for the gep nodes. Use two caches,
54609467b48Spatrick // one for equality and the other for non-equality.
54709467b48Spatrick NodeSymRel EqRel; // Equality relation (as set of equivalence classes).
54809467b48Spatrick NodePairSet Eq, Ne; // Caches.
549*d415bd75Srobert for (auto &I : MaybeEq) {
550*d415bd75Srobert NodeSet &S = I.second;
55109467b48Spatrick for (NodeSet::iterator NI = S.begin(), NE = S.end(); NI != NE; ++NI) {
55209467b48Spatrick GepNode *N = *NI;
55309467b48Spatrick // If node already has a class, then the class must have been created
55409467b48Spatrick // in a prior iteration of this loop. Since equality is transitive,
55509467b48Spatrick // nothing more will be added to that class, so skip it.
55609467b48Spatrick if (node_class(N, EqRel))
55709467b48Spatrick continue;
55809467b48Spatrick
55909467b48Spatrick // Create a new class candidate now.
56009467b48Spatrick NodeSet C;
56109467b48Spatrick for (NodeSet::iterator NJ = std::next(NI); NJ != NE; ++NJ)
56209467b48Spatrick if (node_eq(N, *NJ, Eq, Ne))
56309467b48Spatrick C.insert(*NJ);
56409467b48Spatrick // If Tmp is empty, N would be the only element in it. Don't bother
56509467b48Spatrick // creating a class for it then.
56609467b48Spatrick if (!C.empty()) {
56709467b48Spatrick C.insert(N); // Finalize the set before adding it to the relation.
56809467b48Spatrick std::pair<NodeSymRel::iterator, bool> Ins = EqRel.insert(C);
56909467b48Spatrick (void)Ins;
57009467b48Spatrick assert(Ins.second && "Cannot add a class");
57109467b48Spatrick }
57209467b48Spatrick }
57309467b48Spatrick }
57409467b48Spatrick
57509467b48Spatrick LLVM_DEBUG({
57609467b48Spatrick dbgs() << "Gep node equality:\n";
57709467b48Spatrick for (NodePairSet::iterator I = Eq.begin(), E = Eq.end(); I != E; ++I)
57809467b48Spatrick dbgs() << "{ " << I->first << ", " << I->second << " }\n";
57909467b48Spatrick
58009467b48Spatrick dbgs() << "Gep equivalence classes:\n";
581*d415bd75Srobert for (const NodeSet &S : EqRel) {
58209467b48Spatrick dbgs() << '{';
58309467b48Spatrick for (NodeSet::const_iterator J = S.begin(), F = S.end(); J != F; ++J) {
58409467b48Spatrick if (J != S.begin())
58509467b48Spatrick dbgs() << ',';
58609467b48Spatrick dbgs() << ' ' << *J;
58709467b48Spatrick }
58809467b48Spatrick dbgs() << " }\n";
58909467b48Spatrick }
59009467b48Spatrick });
59109467b48Spatrick
59209467b48Spatrick // Create a projection from a NodeSet to the minimal element in it.
59309467b48Spatrick using ProjMap = std::map<const NodeSet *, GepNode *>;
59409467b48Spatrick ProjMap PM;
595*d415bd75Srobert for (const NodeSet &S : EqRel) {
59609467b48Spatrick GepNode *Min = *std::min_element(S.begin(), S.end(), NodeOrder);
59709467b48Spatrick std::pair<ProjMap::iterator,bool> Ins = PM.insert(std::make_pair(&S, Min));
59809467b48Spatrick (void)Ins;
59909467b48Spatrick assert(Ins.second && "Cannot add minimal element");
60009467b48Spatrick
60109467b48Spatrick // Update the min element's flags, and user list.
60209467b48Spatrick uint32_t Flags = 0;
60309467b48Spatrick UseSet &MinUs = Uses[Min];
604*d415bd75Srobert for (GepNode *N : S) {
60509467b48Spatrick uint32_t NF = N->Flags;
60609467b48Spatrick // If N is used, append all original values of N to the list of
60709467b48Spatrick // original values of Min.
60809467b48Spatrick if (NF & GepNode::Used)
60909467b48Spatrick MinUs.insert(Uses[N].begin(), Uses[N].end());
61009467b48Spatrick Flags |= NF;
61109467b48Spatrick }
61209467b48Spatrick if (MinUs.empty())
61309467b48Spatrick Uses.erase(Min);
61409467b48Spatrick
61509467b48Spatrick // The collected flags should include all the flags from the min element.
61609467b48Spatrick assert((Min->Flags & Flags) == Min->Flags);
61709467b48Spatrick Min->Flags = Flags;
61809467b48Spatrick }
61909467b48Spatrick
62009467b48Spatrick // Commoning: for each non-root gep node, replace "Parent" with the
62109467b48Spatrick // selected (minimum) node from the corresponding equivalence class.
62209467b48Spatrick // If a given parent does not have an equivalence class, leave it
62309467b48Spatrick // unchanged (it means that it's the only element in its class).
624*d415bd75Srobert for (GepNode *N : Nodes) {
62509467b48Spatrick if (N->Flags & GepNode::Root)
62609467b48Spatrick continue;
62709467b48Spatrick const NodeSet *PC = node_class(N->Parent, EqRel);
62809467b48Spatrick if (!PC)
62909467b48Spatrick continue;
63009467b48Spatrick ProjMap::iterator F = PM.find(PC);
63109467b48Spatrick if (F == PM.end())
63209467b48Spatrick continue;
63309467b48Spatrick // Found a replacement, use it.
63409467b48Spatrick GepNode *Rep = F->second;
63509467b48Spatrick N->Parent = Rep;
63609467b48Spatrick }
63709467b48Spatrick
63809467b48Spatrick LLVM_DEBUG(dbgs() << "Gep nodes after commoning:\n" << Nodes);
63909467b48Spatrick
64009467b48Spatrick // Finally, erase the nodes that are no longer used.
64109467b48Spatrick NodeSet Erase;
642*d415bd75Srobert for (GepNode *N : Nodes) {
64309467b48Spatrick const NodeSet *PC = node_class(N, EqRel);
64409467b48Spatrick if (!PC)
64509467b48Spatrick continue;
64609467b48Spatrick ProjMap::iterator F = PM.find(PC);
64709467b48Spatrick if (F == PM.end())
64809467b48Spatrick continue;
64909467b48Spatrick if (N == F->second)
65009467b48Spatrick continue;
65109467b48Spatrick // Node for removal.
652*d415bd75Srobert Erase.insert(N);
65309467b48Spatrick }
65473471bf0Spatrick erase_if(Nodes, in_set(Erase));
65509467b48Spatrick
65609467b48Spatrick LLVM_DEBUG(dbgs() << "Gep nodes after post-commoning cleanup:\n" << Nodes);
65709467b48Spatrick }
65809467b48Spatrick
65909467b48Spatrick template <typename T>
nearest_common_dominator(DominatorTree * DT,T & Blocks)66009467b48Spatrick static BasicBlock *nearest_common_dominator(DominatorTree *DT, T &Blocks) {
66109467b48Spatrick LLVM_DEBUG({
66209467b48Spatrick dbgs() << "NCD of {";
66309467b48Spatrick for (typename T::iterator I = Blocks.begin(), E = Blocks.end(); I != E;
66409467b48Spatrick ++I) {
66509467b48Spatrick if (!*I)
66609467b48Spatrick continue;
66709467b48Spatrick BasicBlock *B = cast<BasicBlock>(*I);
66809467b48Spatrick dbgs() << ' ' << B->getName();
66909467b48Spatrick }
67009467b48Spatrick dbgs() << " }\n";
67109467b48Spatrick });
67209467b48Spatrick
67309467b48Spatrick // Allow null basic blocks in Blocks. In such cases, return nullptr.
67409467b48Spatrick typename T::iterator I = Blocks.begin(), E = Blocks.end();
67509467b48Spatrick if (I == E || !*I)
67609467b48Spatrick return nullptr;
67709467b48Spatrick BasicBlock *Dom = cast<BasicBlock>(*I);
67809467b48Spatrick while (++I != E) {
67909467b48Spatrick BasicBlock *B = cast_or_null<BasicBlock>(*I);
68009467b48Spatrick Dom = B ? DT->findNearestCommonDominator(Dom, B) : nullptr;
68109467b48Spatrick if (!Dom)
68209467b48Spatrick return nullptr;
68309467b48Spatrick }
68409467b48Spatrick LLVM_DEBUG(dbgs() << "computed:" << Dom->getName() << '\n');
68509467b48Spatrick return Dom;
68609467b48Spatrick }
68709467b48Spatrick
68809467b48Spatrick template <typename T>
nearest_common_dominatee(DominatorTree * DT,T & Blocks)68909467b48Spatrick static BasicBlock *nearest_common_dominatee(DominatorTree *DT, T &Blocks) {
69009467b48Spatrick // If two blocks, A and B, dominate a block C, then A dominates B,
69109467b48Spatrick // or B dominates A.
69209467b48Spatrick typename T::iterator I = Blocks.begin(), E = Blocks.end();
69309467b48Spatrick // Find the first non-null block.
69409467b48Spatrick while (I != E && !*I)
69509467b48Spatrick ++I;
69609467b48Spatrick if (I == E)
69709467b48Spatrick return DT->getRoot();
69809467b48Spatrick BasicBlock *DomB = cast<BasicBlock>(*I);
69909467b48Spatrick while (++I != E) {
70009467b48Spatrick if (!*I)
70109467b48Spatrick continue;
70209467b48Spatrick BasicBlock *B = cast<BasicBlock>(*I);
70309467b48Spatrick if (DT->dominates(B, DomB))
70409467b48Spatrick continue;
70509467b48Spatrick if (!DT->dominates(DomB, B))
70609467b48Spatrick return nullptr;
70709467b48Spatrick DomB = B;
70809467b48Spatrick }
70909467b48Spatrick return DomB;
71009467b48Spatrick }
71109467b48Spatrick
71209467b48Spatrick // Find the first use in B of any value from Values. If no such use,
71309467b48Spatrick // return B->end().
71409467b48Spatrick template <typename T>
first_use_of_in_block(T & Values,BasicBlock * B)71509467b48Spatrick static BasicBlock::iterator first_use_of_in_block(T &Values, BasicBlock *B) {
71609467b48Spatrick BasicBlock::iterator FirstUse = B->end(), BEnd = B->end();
71709467b48Spatrick
71809467b48Spatrick using iterator = typename T::iterator;
71909467b48Spatrick
72009467b48Spatrick for (iterator I = Values.begin(), E = Values.end(); I != E; ++I) {
72109467b48Spatrick Value *V = *I;
72209467b48Spatrick // If V is used in a PHI node, the use belongs to the incoming block,
72309467b48Spatrick // not the block with the PHI node. In the incoming block, the use
72409467b48Spatrick // would be considered as being at the end of it, so it cannot
72509467b48Spatrick // influence the position of the first use (which is assumed to be
72609467b48Spatrick // at the end to start with).
72709467b48Spatrick if (isa<PHINode>(V))
72809467b48Spatrick continue;
72909467b48Spatrick if (!isa<Instruction>(V))
73009467b48Spatrick continue;
73109467b48Spatrick Instruction *In = cast<Instruction>(V);
73209467b48Spatrick if (In->getParent() != B)
73309467b48Spatrick continue;
73409467b48Spatrick BasicBlock::iterator It = In->getIterator();
73509467b48Spatrick if (std::distance(FirstUse, BEnd) < std::distance(It, BEnd))
73609467b48Spatrick FirstUse = It;
73709467b48Spatrick }
73809467b48Spatrick return FirstUse;
73909467b48Spatrick }
74009467b48Spatrick
is_empty(const BasicBlock * B)74109467b48Spatrick static bool is_empty(const BasicBlock *B) {
74209467b48Spatrick return B->empty() || (&*B->begin() == B->getTerminator());
74309467b48Spatrick }
74409467b48Spatrick
recalculatePlacement(GepNode * Node,NodeChildrenMap & NCM,NodeToValueMap & Loc)74509467b48Spatrick BasicBlock *HexagonCommonGEP::recalculatePlacement(GepNode *Node,
74609467b48Spatrick NodeChildrenMap &NCM, NodeToValueMap &Loc) {
74709467b48Spatrick LLVM_DEBUG(dbgs() << "Loc for node:" << Node << '\n');
74809467b48Spatrick // Recalculate the placement for Node, assuming that the locations of
74909467b48Spatrick // its children in Loc are valid.
75009467b48Spatrick // Return nullptr if there is no valid placement for Node (for example, it
75109467b48Spatrick // uses an index value that is not available at the location required
75209467b48Spatrick // to dominate all children, etc.).
75309467b48Spatrick
75409467b48Spatrick // Find the nearest common dominator for:
75509467b48Spatrick // - all users, if the node is used, and
75609467b48Spatrick // - all children.
75709467b48Spatrick ValueVect Bs;
75809467b48Spatrick if (Node->Flags & GepNode::Used) {
75909467b48Spatrick // Append all blocks with uses of the original values to the
76009467b48Spatrick // block vector Bs.
76109467b48Spatrick NodeToUsesMap::iterator UF = Uses.find(Node);
76209467b48Spatrick assert(UF != Uses.end() && "Used node with no use information");
76309467b48Spatrick UseSet &Us = UF->second;
764*d415bd75Srobert for (Use *U : Us) {
76509467b48Spatrick User *R = U->getUser();
76609467b48Spatrick if (!isa<Instruction>(R))
76709467b48Spatrick continue;
76809467b48Spatrick BasicBlock *PB = isa<PHINode>(R)
76909467b48Spatrick ? cast<PHINode>(R)->getIncomingBlock(*U)
77009467b48Spatrick : cast<Instruction>(R)->getParent();
77109467b48Spatrick Bs.push_back(PB);
77209467b48Spatrick }
77309467b48Spatrick }
77409467b48Spatrick // Append the location of each child.
77509467b48Spatrick NodeChildrenMap::iterator CF = NCM.find(Node);
77609467b48Spatrick if (CF != NCM.end()) {
77709467b48Spatrick NodeVect &Cs = CF->second;
778*d415bd75Srobert for (GepNode *CN : Cs) {
77909467b48Spatrick NodeToValueMap::iterator LF = Loc.find(CN);
78009467b48Spatrick // If the child is only used in GEP instructions (i.e. is not used in
78109467b48Spatrick // non-GEP instructions), the nearest dominator computed for it may
78209467b48Spatrick // have been null. In such case it won't have a location available.
78309467b48Spatrick if (LF == Loc.end())
78409467b48Spatrick continue;
78509467b48Spatrick Bs.push_back(LF->second);
78609467b48Spatrick }
78709467b48Spatrick }
78809467b48Spatrick
78909467b48Spatrick BasicBlock *DomB = nearest_common_dominator(DT, Bs);
79009467b48Spatrick if (!DomB)
79109467b48Spatrick return nullptr;
79209467b48Spatrick // Check if the index used by Node dominates the computed dominator.
79309467b48Spatrick Instruction *IdxI = dyn_cast<Instruction>(Node->Idx);
79409467b48Spatrick if (IdxI && !DT->dominates(IdxI->getParent(), DomB))
79509467b48Spatrick return nullptr;
79609467b48Spatrick
79709467b48Spatrick // Avoid putting nodes into empty blocks.
79809467b48Spatrick while (is_empty(DomB)) {
79909467b48Spatrick DomTreeNode *N = (*DT)[DomB]->getIDom();
80009467b48Spatrick if (!N)
80109467b48Spatrick break;
80209467b48Spatrick DomB = N->getBlock();
80309467b48Spatrick }
80409467b48Spatrick
80509467b48Spatrick // Otherwise, DomB is fine. Update the location map.
80609467b48Spatrick Loc[Node] = DomB;
80709467b48Spatrick return DomB;
80809467b48Spatrick }
80909467b48Spatrick
recalculatePlacementRec(GepNode * Node,NodeChildrenMap & NCM,NodeToValueMap & Loc)81009467b48Spatrick BasicBlock *HexagonCommonGEP::recalculatePlacementRec(GepNode *Node,
81109467b48Spatrick NodeChildrenMap &NCM, NodeToValueMap &Loc) {
81209467b48Spatrick LLVM_DEBUG(dbgs() << "LocRec begin for node:" << Node << '\n');
81309467b48Spatrick // Recalculate the placement of Node, after recursively recalculating the
81409467b48Spatrick // placements of all its children.
81509467b48Spatrick NodeChildrenMap::iterator CF = NCM.find(Node);
81609467b48Spatrick if (CF != NCM.end()) {
81709467b48Spatrick NodeVect &Cs = CF->second;
818*d415bd75Srobert for (GepNode *C : Cs)
819*d415bd75Srobert recalculatePlacementRec(C, NCM, Loc);
82009467b48Spatrick }
82109467b48Spatrick BasicBlock *LB = recalculatePlacement(Node, NCM, Loc);
82209467b48Spatrick LLVM_DEBUG(dbgs() << "LocRec end for node:" << Node << '\n');
82309467b48Spatrick return LB;
82409467b48Spatrick }
82509467b48Spatrick
isInvariantIn(Value * Val,Loop * L)82609467b48Spatrick bool HexagonCommonGEP::isInvariantIn(Value *Val, Loop *L) {
82709467b48Spatrick if (isa<Constant>(Val) || isa<Argument>(Val))
82809467b48Spatrick return true;
82909467b48Spatrick Instruction *In = dyn_cast<Instruction>(Val);
83009467b48Spatrick if (!In)
83109467b48Spatrick return false;
83209467b48Spatrick BasicBlock *HdrB = L->getHeader(), *DefB = In->getParent();
83309467b48Spatrick return DT->properlyDominates(DefB, HdrB);
83409467b48Spatrick }
83509467b48Spatrick
isInvariantIn(GepNode * Node,Loop * L)83609467b48Spatrick bool HexagonCommonGEP::isInvariantIn(GepNode *Node, Loop *L) {
83709467b48Spatrick if (Node->Flags & GepNode::Root)
83809467b48Spatrick if (!isInvariantIn(Node->BaseVal, L))
83909467b48Spatrick return false;
84009467b48Spatrick return isInvariantIn(Node->Idx, L);
84109467b48Spatrick }
84209467b48Spatrick
isInMainPath(BasicBlock * B,Loop * L)84309467b48Spatrick bool HexagonCommonGEP::isInMainPath(BasicBlock *B, Loop *L) {
84409467b48Spatrick BasicBlock *HB = L->getHeader();
84509467b48Spatrick BasicBlock *LB = L->getLoopLatch();
84609467b48Spatrick // B must post-dominate the loop header or dominate the loop latch.
84709467b48Spatrick if (PDT->dominates(B, HB))
84809467b48Spatrick return true;
84909467b48Spatrick if (LB && DT->dominates(B, LB))
85009467b48Spatrick return true;
85109467b48Spatrick return false;
85209467b48Spatrick }
85309467b48Spatrick
preheader(DominatorTree * DT,Loop * L)85409467b48Spatrick static BasicBlock *preheader(DominatorTree *DT, Loop *L) {
85509467b48Spatrick if (BasicBlock *PH = L->getLoopPreheader())
85609467b48Spatrick return PH;
85709467b48Spatrick if (!OptSpeculate)
85809467b48Spatrick return nullptr;
85909467b48Spatrick DomTreeNode *DN = DT->getNode(L->getHeader());
86009467b48Spatrick if (!DN)
86109467b48Spatrick return nullptr;
86209467b48Spatrick return DN->getIDom()->getBlock();
86309467b48Spatrick }
86409467b48Spatrick
adjustForInvariance(GepNode * Node,NodeChildrenMap & NCM,NodeToValueMap & Loc)86509467b48Spatrick BasicBlock *HexagonCommonGEP::adjustForInvariance(GepNode *Node,
86609467b48Spatrick NodeChildrenMap &NCM, NodeToValueMap &Loc) {
86709467b48Spatrick // Find the "topmost" location for Node: it must be dominated by both,
86809467b48Spatrick // its parent (or the BaseVal, if it's a root node), and by the index
86909467b48Spatrick // value.
87009467b48Spatrick ValueVect Bs;
87109467b48Spatrick if (Node->Flags & GepNode::Root) {
87209467b48Spatrick if (Instruction *PIn = dyn_cast<Instruction>(Node->BaseVal))
87309467b48Spatrick Bs.push_back(PIn->getParent());
87409467b48Spatrick } else {
87509467b48Spatrick Bs.push_back(Loc[Node->Parent]);
87609467b48Spatrick }
87709467b48Spatrick if (Instruction *IIn = dyn_cast<Instruction>(Node->Idx))
87809467b48Spatrick Bs.push_back(IIn->getParent());
87909467b48Spatrick BasicBlock *TopB = nearest_common_dominatee(DT, Bs);
88009467b48Spatrick
88109467b48Spatrick // Traverse the loop nest upwards until we find a loop in which Node
88209467b48Spatrick // is no longer invariant, or until we get to the upper limit of Node's
88309467b48Spatrick // placement. The traversal will also stop when a suitable "preheader"
88409467b48Spatrick // cannot be found for a given loop. The "preheader" may actually be
88509467b48Spatrick // a regular block outside of the loop (i.e. not guarded), in which case
88609467b48Spatrick // the Node will be speculated.
88709467b48Spatrick // For nodes that are not in the main path of the containing loop (i.e.
88809467b48Spatrick // are not executed in each iteration), do not move them out of the loop.
88909467b48Spatrick BasicBlock *LocB = cast_or_null<BasicBlock>(Loc[Node]);
89009467b48Spatrick if (LocB) {
89109467b48Spatrick Loop *Lp = LI->getLoopFor(LocB);
89209467b48Spatrick while (Lp) {
89309467b48Spatrick if (!isInvariantIn(Node, Lp) || !isInMainPath(LocB, Lp))
89409467b48Spatrick break;
89509467b48Spatrick BasicBlock *NewLoc = preheader(DT, Lp);
89609467b48Spatrick if (!NewLoc || !DT->dominates(TopB, NewLoc))
89709467b48Spatrick break;
89809467b48Spatrick Lp = Lp->getParentLoop();
89909467b48Spatrick LocB = NewLoc;
90009467b48Spatrick }
90109467b48Spatrick }
90209467b48Spatrick Loc[Node] = LocB;
90309467b48Spatrick
90409467b48Spatrick // Recursively compute the locations of all children nodes.
90509467b48Spatrick NodeChildrenMap::iterator CF = NCM.find(Node);
90609467b48Spatrick if (CF != NCM.end()) {
90709467b48Spatrick NodeVect &Cs = CF->second;
908*d415bd75Srobert for (GepNode *C : Cs)
909*d415bd75Srobert adjustForInvariance(C, NCM, Loc);
91009467b48Spatrick }
91109467b48Spatrick return LocB;
91209467b48Spatrick }
91309467b48Spatrick
91409467b48Spatrick namespace {
91509467b48Spatrick
91609467b48Spatrick struct LocationAsBlock {
LocationAsBlock__anon16873bc50611::LocationAsBlock91709467b48Spatrick LocationAsBlock(const NodeToValueMap &L) : Map(L) {}
91809467b48Spatrick
91909467b48Spatrick const NodeToValueMap ⤅
92009467b48Spatrick };
92109467b48Spatrick
92209467b48Spatrick raw_ostream &operator<< (raw_ostream &OS,
92309467b48Spatrick const LocationAsBlock &Loc) LLVM_ATTRIBUTE_UNUSED ;
operator <<(raw_ostream & OS,const LocationAsBlock & Loc)92409467b48Spatrick raw_ostream &operator<< (raw_ostream &OS, const LocationAsBlock &Loc) {
925*d415bd75Srobert for (const auto &I : Loc.Map) {
926*d415bd75Srobert OS << I.first << " -> ";
927*d415bd75Srobert if (BasicBlock *B = cast_or_null<BasicBlock>(I.second))
92809467b48Spatrick OS << B->getName() << '(' << B << ')';
92973471bf0Spatrick else
93073471bf0Spatrick OS << "<null-block>";
93109467b48Spatrick OS << '\n';
93209467b48Spatrick }
93309467b48Spatrick return OS;
93409467b48Spatrick }
93509467b48Spatrick
is_constant(GepNode * N)93609467b48Spatrick inline bool is_constant(GepNode *N) {
93709467b48Spatrick return isa<ConstantInt>(N->Idx);
93809467b48Spatrick }
93909467b48Spatrick
94009467b48Spatrick } // end anonymous namespace
94109467b48Spatrick
separateChainForNode(GepNode * Node,Use * U,NodeToValueMap & Loc)94209467b48Spatrick void HexagonCommonGEP::separateChainForNode(GepNode *Node, Use *U,
94309467b48Spatrick NodeToValueMap &Loc) {
94409467b48Spatrick User *R = U->getUser();
94509467b48Spatrick LLVM_DEBUG(dbgs() << "Separating chain for node (" << Node << ") user: " << *R
94609467b48Spatrick << '\n');
94709467b48Spatrick BasicBlock *PB = cast<Instruction>(R)->getParent();
94809467b48Spatrick
94909467b48Spatrick GepNode *N = Node;
95009467b48Spatrick GepNode *C = nullptr, *NewNode = nullptr;
95109467b48Spatrick while (is_constant(N) && !(N->Flags & GepNode::Root)) {
95209467b48Spatrick // XXX if (single-use) dont-replicate;
95309467b48Spatrick GepNode *NewN = new (*Mem) GepNode(N);
95409467b48Spatrick Nodes.push_back(NewN);
95509467b48Spatrick Loc[NewN] = PB;
95609467b48Spatrick
95709467b48Spatrick if (N == Node)
95809467b48Spatrick NewNode = NewN;
95909467b48Spatrick NewN->Flags &= ~GepNode::Used;
96009467b48Spatrick if (C)
96109467b48Spatrick C->Parent = NewN;
96209467b48Spatrick C = NewN;
96309467b48Spatrick N = N->Parent;
96409467b48Spatrick }
96509467b48Spatrick if (!NewNode)
96609467b48Spatrick return;
96709467b48Spatrick
96809467b48Spatrick // Move over all uses that share the same user as U from Node to NewNode.
96909467b48Spatrick NodeToUsesMap::iterator UF = Uses.find(Node);
97009467b48Spatrick assert(UF != Uses.end());
97109467b48Spatrick UseSet &Us = UF->second;
97209467b48Spatrick UseSet NewUs;
97309467b48Spatrick for (Use *U : Us) {
97409467b48Spatrick if (U->getUser() == R)
97509467b48Spatrick NewUs.insert(U);
97609467b48Spatrick }
97709467b48Spatrick for (Use *U : NewUs)
97809467b48Spatrick Us.remove(U); // erase takes an iterator.
97909467b48Spatrick
98009467b48Spatrick if (Us.empty()) {
98109467b48Spatrick Node->Flags &= ~GepNode::Used;
98209467b48Spatrick Uses.erase(UF);
98309467b48Spatrick }
98409467b48Spatrick
98509467b48Spatrick // Should at least have U in NewUs.
98609467b48Spatrick NewNode->Flags |= GepNode::Used;
98709467b48Spatrick LLVM_DEBUG(dbgs() << "new node: " << NewNode << " " << *NewNode << '\n');
98809467b48Spatrick assert(!NewUs.empty());
98909467b48Spatrick Uses[NewNode] = NewUs;
99009467b48Spatrick }
99109467b48Spatrick
separateConstantChains(GepNode * Node,NodeChildrenMap & NCM,NodeToValueMap & Loc)99209467b48Spatrick void HexagonCommonGEP::separateConstantChains(GepNode *Node,
99309467b48Spatrick NodeChildrenMap &NCM, NodeToValueMap &Loc) {
99409467b48Spatrick // First approximation: extract all chains.
99509467b48Spatrick NodeSet Ns;
99609467b48Spatrick nodes_for_root(Node, NCM, Ns);
99709467b48Spatrick
99809467b48Spatrick LLVM_DEBUG(dbgs() << "Separating constant chains for node: " << Node << '\n');
99909467b48Spatrick // Collect all used nodes together with the uses from loads and stores,
100009467b48Spatrick // where the GEP node could be folded into the load/store instruction.
100109467b48Spatrick NodeToUsesMap FNs; // Foldable nodes.
1002*d415bd75Srobert for (GepNode *N : Ns) {
100309467b48Spatrick if (!(N->Flags & GepNode::Used))
100409467b48Spatrick continue;
100509467b48Spatrick NodeToUsesMap::iterator UF = Uses.find(N);
100609467b48Spatrick assert(UF != Uses.end());
100709467b48Spatrick UseSet &Us = UF->second;
100809467b48Spatrick // Loads/stores that use the node N.
100909467b48Spatrick UseSet LSs;
1010*d415bd75Srobert for (Use *U : Us) {
101109467b48Spatrick User *R = U->getUser();
101209467b48Spatrick // We're interested in uses that provide the address. It can happen
101309467b48Spatrick // that the value may also be provided via GEP, but we won't handle
101409467b48Spatrick // those cases here for now.
101509467b48Spatrick if (LoadInst *Ld = dyn_cast<LoadInst>(R)) {
101609467b48Spatrick unsigned PtrX = LoadInst::getPointerOperandIndex();
101709467b48Spatrick if (&Ld->getOperandUse(PtrX) == U)
101809467b48Spatrick LSs.insert(U);
101909467b48Spatrick } else if (StoreInst *St = dyn_cast<StoreInst>(R)) {
102009467b48Spatrick unsigned PtrX = StoreInst::getPointerOperandIndex();
102109467b48Spatrick if (&St->getOperandUse(PtrX) == U)
102209467b48Spatrick LSs.insert(U);
102309467b48Spatrick }
102409467b48Spatrick }
102509467b48Spatrick // Even if the total use count is 1, separating the chain may still be
102609467b48Spatrick // beneficial, since the constant chain may be longer than the GEP alone
102709467b48Spatrick // would be (e.g. if the parent node has a constant index and also has
102809467b48Spatrick // other children).
102909467b48Spatrick if (!LSs.empty())
103009467b48Spatrick FNs.insert(std::make_pair(N, LSs));
103109467b48Spatrick }
103209467b48Spatrick
103309467b48Spatrick LLVM_DEBUG(dbgs() << "Nodes with foldable users:\n" << FNs);
103409467b48Spatrick
1035*d415bd75Srobert for (auto &FN : FNs) {
1036*d415bd75Srobert GepNode *N = FN.first;
1037*d415bd75Srobert UseSet &Us = FN.second;
1038*d415bd75Srobert for (Use *U : Us)
1039*d415bd75Srobert separateChainForNode(N, U, Loc);
104009467b48Spatrick }
104109467b48Spatrick }
104209467b48Spatrick
computeNodePlacement(NodeToValueMap & Loc)104309467b48Spatrick void HexagonCommonGEP::computeNodePlacement(NodeToValueMap &Loc) {
104409467b48Spatrick // Compute the inverse of the Node.Parent links. Also, collect the set
104509467b48Spatrick // of root nodes.
104609467b48Spatrick NodeChildrenMap NCM;
104709467b48Spatrick NodeVect Roots;
104809467b48Spatrick invert_find_roots(Nodes, NCM, Roots);
104909467b48Spatrick
105009467b48Spatrick // Compute the initial placement determined by the users' locations, and
105109467b48Spatrick // the locations of the child nodes.
1052*d415bd75Srobert for (GepNode *Root : Roots)
1053*d415bd75Srobert recalculatePlacementRec(Root, NCM, Loc);
105409467b48Spatrick
105509467b48Spatrick LLVM_DEBUG(dbgs() << "Initial node placement:\n" << LocationAsBlock(Loc));
105609467b48Spatrick
105709467b48Spatrick if (OptEnableInv) {
1058*d415bd75Srobert for (GepNode *Root : Roots)
1059*d415bd75Srobert adjustForInvariance(Root, NCM, Loc);
106009467b48Spatrick
106109467b48Spatrick LLVM_DEBUG(dbgs() << "Node placement after adjustment for invariance:\n"
106209467b48Spatrick << LocationAsBlock(Loc));
106309467b48Spatrick }
106409467b48Spatrick if (OptEnableConst) {
1065*d415bd75Srobert for (GepNode *Root : Roots)
1066*d415bd75Srobert separateConstantChains(Root, NCM, Loc);
106709467b48Spatrick }
106809467b48Spatrick LLVM_DEBUG(dbgs() << "Node use information:\n" << Uses);
106909467b48Spatrick
107009467b48Spatrick // At the moment, there is no further refinement of the initial placement.
107109467b48Spatrick // Such a refinement could include splitting the nodes if they are placed
107209467b48Spatrick // too far from some of its users.
107309467b48Spatrick
107409467b48Spatrick LLVM_DEBUG(dbgs() << "Final node placement:\n" << LocationAsBlock(Loc));
107509467b48Spatrick }
107609467b48Spatrick
fabricateGEP(NodeVect & NA,BasicBlock::iterator At,BasicBlock * LocB)107709467b48Spatrick Value *HexagonCommonGEP::fabricateGEP(NodeVect &NA, BasicBlock::iterator At,
107809467b48Spatrick BasicBlock *LocB) {
107909467b48Spatrick LLVM_DEBUG(dbgs() << "Fabricating GEP in " << LocB->getName()
108009467b48Spatrick << " for nodes:\n"
108109467b48Spatrick << NA);
108209467b48Spatrick unsigned Num = NA.size();
108309467b48Spatrick GepNode *RN = NA[0];
108409467b48Spatrick assert((RN->Flags & GepNode::Root) && "Creating GEP for non-root");
108509467b48Spatrick
108609467b48Spatrick GetElementPtrInst *NewInst = nullptr;
108709467b48Spatrick Value *Input = RN->BaseVal;
108873471bf0Spatrick Type *InpTy = RN->PTy;
108973471bf0Spatrick
109073471bf0Spatrick unsigned Idx = 0;
109109467b48Spatrick do {
109273471bf0Spatrick SmallVector<Value*, 4> IdxList;
109309467b48Spatrick // If the type of the input of the first node is not a pointer,
109409467b48Spatrick // we need to add an artificial i32 0 to the indices (because the
109509467b48Spatrick // actual input in the IR will be a pointer).
109673471bf0Spatrick if (!(NA[Idx]->Flags & GepNode::Pointer)) {
109709467b48Spatrick Type *Int32Ty = Type::getInt32Ty(*Ctx);
109873471bf0Spatrick IdxList.push_back(ConstantInt::get(Int32Ty, 0));
109909467b48Spatrick }
110009467b48Spatrick
110109467b48Spatrick // Keep adding indices from NA until we have to stop and generate
110209467b48Spatrick // an "intermediate" GEP.
110373471bf0Spatrick while (++Idx <= Num) {
110473471bf0Spatrick GepNode *N = NA[Idx-1];
110573471bf0Spatrick IdxList.push_back(N->Idx);
110673471bf0Spatrick if (Idx < Num) {
110773471bf0Spatrick // We have to stop if we reach a pointer.
110873471bf0Spatrick if (NA[Idx]->Flags & GepNode::Pointer)
110909467b48Spatrick break;
111009467b48Spatrick }
111109467b48Spatrick }
111273471bf0Spatrick NewInst = GetElementPtrInst::Create(InpTy, Input, IdxList, "cgep", &*At);
111309467b48Spatrick NewInst->setIsInBounds(RN->Flags & GepNode::InBounds);
111409467b48Spatrick LLVM_DEBUG(dbgs() << "new GEP: " << *NewInst << '\n');
111573471bf0Spatrick if (Idx < Num) {
111609467b48Spatrick Input = NewInst;
111773471bf0Spatrick InpTy = NA[Idx]->PTy;
111873471bf0Spatrick }
111973471bf0Spatrick } while (Idx <= Num);
112009467b48Spatrick
112109467b48Spatrick return NewInst;
112209467b48Spatrick }
112309467b48Spatrick
getAllUsersForNode(GepNode * Node,ValueVect & Values,NodeChildrenMap & NCM)112409467b48Spatrick void HexagonCommonGEP::getAllUsersForNode(GepNode *Node, ValueVect &Values,
112509467b48Spatrick NodeChildrenMap &NCM) {
112609467b48Spatrick NodeVect Work;
112709467b48Spatrick Work.push_back(Node);
112809467b48Spatrick
112909467b48Spatrick while (!Work.empty()) {
113009467b48Spatrick NodeVect::iterator First = Work.begin();
113109467b48Spatrick GepNode *N = *First;
113209467b48Spatrick Work.erase(First);
113309467b48Spatrick if (N->Flags & GepNode::Used) {
113409467b48Spatrick NodeToUsesMap::iterator UF = Uses.find(N);
113509467b48Spatrick assert(UF != Uses.end() && "No use information for used node");
113609467b48Spatrick UseSet &Us = UF->second;
1137*d415bd75Srobert for (const auto &U : Us)
1138*d415bd75Srobert Values.push_back(U->getUser());
113909467b48Spatrick }
114009467b48Spatrick NodeChildrenMap::iterator CF = NCM.find(N);
114109467b48Spatrick if (CF != NCM.end()) {
114209467b48Spatrick NodeVect &Cs = CF->second;
114373471bf0Spatrick llvm::append_range(Work, Cs);
114409467b48Spatrick }
114509467b48Spatrick }
114609467b48Spatrick }
114709467b48Spatrick
materialize(NodeToValueMap & Loc)114809467b48Spatrick void HexagonCommonGEP::materialize(NodeToValueMap &Loc) {
114909467b48Spatrick LLVM_DEBUG(dbgs() << "Nodes before materialization:\n" << Nodes << '\n');
115009467b48Spatrick NodeChildrenMap NCM;
115109467b48Spatrick NodeVect Roots;
115209467b48Spatrick // Compute the inversion again, since computing placement could alter
115309467b48Spatrick // "parent" relation between nodes.
115409467b48Spatrick invert_find_roots(Nodes, NCM, Roots);
115509467b48Spatrick
115609467b48Spatrick while (!Roots.empty()) {
115709467b48Spatrick NodeVect::iterator First = Roots.begin();
115809467b48Spatrick GepNode *Root = *First, *Last = *First;
115909467b48Spatrick Roots.erase(First);
116009467b48Spatrick
116109467b48Spatrick NodeVect NA; // Nodes to assemble.
116209467b48Spatrick // Append to NA all child nodes up to (and including) the first child
116309467b48Spatrick // that:
116409467b48Spatrick // (1) has more than 1 child, or
116509467b48Spatrick // (2) is used, or
116609467b48Spatrick // (3) has a child located in a different block.
116709467b48Spatrick bool LastUsed = false;
116809467b48Spatrick unsigned LastCN = 0;
116909467b48Spatrick // The location may be null if the computation failed (it can legitimately
117009467b48Spatrick // happen for nodes created from dead GEPs).
117109467b48Spatrick Value *LocV = Loc[Last];
117209467b48Spatrick if (!LocV)
117309467b48Spatrick continue;
117409467b48Spatrick BasicBlock *LastB = cast<BasicBlock>(LocV);
117509467b48Spatrick do {
117609467b48Spatrick NA.push_back(Last);
117709467b48Spatrick LastUsed = (Last->Flags & GepNode::Used);
117809467b48Spatrick if (LastUsed)
117909467b48Spatrick break;
118009467b48Spatrick NodeChildrenMap::iterator CF = NCM.find(Last);
118109467b48Spatrick LastCN = (CF != NCM.end()) ? CF->second.size() : 0;
118209467b48Spatrick if (LastCN != 1)
118309467b48Spatrick break;
118409467b48Spatrick GepNode *Child = CF->second.front();
118509467b48Spatrick BasicBlock *ChildB = cast_or_null<BasicBlock>(Loc[Child]);
118609467b48Spatrick if (ChildB != nullptr && LastB != ChildB)
118709467b48Spatrick break;
118809467b48Spatrick Last = Child;
118909467b48Spatrick } while (true);
119009467b48Spatrick
119109467b48Spatrick BasicBlock::iterator InsertAt = LastB->getTerminator()->getIterator();
119209467b48Spatrick if (LastUsed || LastCN > 0) {
119309467b48Spatrick ValueVect Urs;
119409467b48Spatrick getAllUsersForNode(Root, Urs, NCM);
119509467b48Spatrick BasicBlock::iterator FirstUse = first_use_of_in_block(Urs, LastB);
119609467b48Spatrick if (FirstUse != LastB->end())
119709467b48Spatrick InsertAt = FirstUse;
119809467b48Spatrick }
119909467b48Spatrick
120009467b48Spatrick // Generate a new instruction for NA.
120109467b48Spatrick Value *NewInst = fabricateGEP(NA, InsertAt, LastB);
120209467b48Spatrick
120309467b48Spatrick // Convert all the children of Last node into roots, and append them
120409467b48Spatrick // to the Roots list.
120509467b48Spatrick if (LastCN > 0) {
120609467b48Spatrick NodeVect &Cs = NCM[Last];
1207*d415bd75Srobert for (GepNode *CN : Cs) {
120809467b48Spatrick CN->Flags &= ~GepNode::Internal;
120909467b48Spatrick CN->Flags |= GepNode::Root;
121009467b48Spatrick CN->BaseVal = NewInst;
121109467b48Spatrick Roots.push_back(CN);
121209467b48Spatrick }
121309467b48Spatrick }
121409467b48Spatrick
121509467b48Spatrick // Lastly, if the Last node was used, replace all uses with the new GEP.
121609467b48Spatrick // The uses reference the original GEP values.
121709467b48Spatrick if (LastUsed) {
121809467b48Spatrick NodeToUsesMap::iterator UF = Uses.find(Last);
121909467b48Spatrick assert(UF != Uses.end() && "No use information found");
122009467b48Spatrick UseSet &Us = UF->second;
1221*d415bd75Srobert for (Use *U : Us)
122209467b48Spatrick U->set(NewInst);
122309467b48Spatrick }
122409467b48Spatrick }
122509467b48Spatrick }
122609467b48Spatrick
removeDeadCode()122709467b48Spatrick void HexagonCommonGEP::removeDeadCode() {
122809467b48Spatrick ValueVect BO;
122909467b48Spatrick BO.push_back(&Fn->front());
123009467b48Spatrick
123109467b48Spatrick for (unsigned i = 0; i < BO.size(); ++i) {
123209467b48Spatrick BasicBlock *B = cast<BasicBlock>(BO[i]);
1233*d415bd75Srobert for (auto *DTN : children<DomTreeNode *>(DT->getNode(B)))
123409467b48Spatrick BO.push_back(DTN->getBlock());
123509467b48Spatrick }
123609467b48Spatrick
1237*d415bd75Srobert for (Value *V : llvm::reverse(BO)) {
1238*d415bd75Srobert BasicBlock *B = cast<BasicBlock>(V);
123909467b48Spatrick ValueVect Ins;
1240*d415bd75Srobert for (Instruction &I : llvm::reverse(*B))
1241*d415bd75Srobert Ins.push_back(&I);
1242*d415bd75Srobert for (Value *I : Ins) {
1243*d415bd75Srobert Instruction *In = cast<Instruction>(I);
124409467b48Spatrick if (isInstructionTriviallyDead(In))
124509467b48Spatrick In->eraseFromParent();
124609467b48Spatrick }
124709467b48Spatrick }
124809467b48Spatrick }
124909467b48Spatrick
runOnFunction(Function & F)125009467b48Spatrick bool HexagonCommonGEP::runOnFunction(Function &F) {
125109467b48Spatrick if (skipFunction(F))
125209467b48Spatrick return false;
125309467b48Spatrick
125409467b48Spatrick // For now bail out on C++ exception handling.
1255*d415bd75Srobert for (const BasicBlock &BB : F)
1256*d415bd75Srobert for (const Instruction &I : BB)
125709467b48Spatrick if (isa<InvokeInst>(I) || isa<LandingPadInst>(I))
125809467b48Spatrick return false;
125909467b48Spatrick
126009467b48Spatrick Fn = &F;
126109467b48Spatrick DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
126209467b48Spatrick PDT = &getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
126309467b48Spatrick LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
126409467b48Spatrick Ctx = &F.getContext();
126509467b48Spatrick
126609467b48Spatrick Nodes.clear();
126709467b48Spatrick Uses.clear();
126809467b48Spatrick NodeOrder.clear();
126909467b48Spatrick
127009467b48Spatrick SpecificBumpPtrAllocator<GepNode> Allocator;
127109467b48Spatrick Mem = &Allocator;
127209467b48Spatrick
127309467b48Spatrick collect();
127409467b48Spatrick common();
127509467b48Spatrick
127609467b48Spatrick NodeToValueMap Loc;
127709467b48Spatrick computeNodePlacement(Loc);
127809467b48Spatrick materialize(Loc);
127909467b48Spatrick removeDeadCode();
128009467b48Spatrick
128109467b48Spatrick #ifdef EXPENSIVE_CHECKS
128209467b48Spatrick // Run this only when expensive checks are enabled.
1283097a140dSpatrick if (verifyFunction(F, &dbgs()))
1284097a140dSpatrick report_fatal_error("Broken function");
128509467b48Spatrick #endif
128609467b48Spatrick return true;
128709467b48Spatrick }
128809467b48Spatrick
128909467b48Spatrick namespace llvm {
129009467b48Spatrick
createHexagonCommonGEP()129109467b48Spatrick FunctionPass *createHexagonCommonGEP() {
129209467b48Spatrick return new HexagonCommonGEP();
129309467b48Spatrick }
129409467b48Spatrick
129509467b48Spatrick } // end namespace llvm
1296