1 //===- BranchFolding.h - Fold machine code branch instructions --*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLVM_LIB_CODEGEN_BRANCHFOLDING_H
10 #define LLVM_LIB_CODEGEN_BRANCHFOLDING_H
11 
12 #include "llvm/ADT/DenseMap.h"
13 #include "llvm/ADT/SmallPtrSet.h"
14 #include "llvm/CodeGen/LivePhysRegs.h"
15 #include "llvm/CodeGen/MachineBasicBlock.h"
16 #include "llvm/CodeGen/MBFIWrapper.h"
17 #include "llvm/Support/BlockFrequency.h"
18 #include "llvm/Support/Compiler.h"
19 #include <cstdint>
20 #include <vector>
21 
22 namespace llvm {
23 
24 class BasicBlock;
25 class MachineBlockFrequencyInfo;
26 class MachineBranchProbabilityInfo;
27 class MachineFunction;
28 class MachineLoopInfo;
29 class MachineModuleInfo;
30 class MachineRegisterInfo;
31 class ProfileSummaryInfo;
32 class raw_ostream;
33 class TargetInstrInfo;
34 class TargetRegisterInfo;
35 
36   class LLVM_LIBRARY_VISIBILITY BranchFolder {
37   public:
38     explicit BranchFolder(bool defaultEnableTailMerge,
39                           bool CommonHoist,
40                           MBFIWrapper &FreqInfo,
41                           const MachineBranchProbabilityInfo &ProbInfo,
42                           ProfileSummaryInfo *PSI,
43                           // Min tail length to merge. Defaults to commandline
44                           // flag. Ignored for optsize.
45                           unsigned MinTailLength = 0);
46 
47     /// Perhaps branch folding, tail merging and other CFG optimizations on the
48     /// given function.  Block placement changes the layout and may create new
49     /// tail merging opportunities.
50     bool OptimizeFunction(MachineFunction &MF, const TargetInstrInfo *tii,
51                           const TargetRegisterInfo *tri, MachineModuleInfo *mmi,
52                           MachineLoopInfo *mli = nullptr,
53                           bool AfterPlacement = false);
54 
55   private:
56     class MergePotentialsElt {
57       unsigned Hash;
58       MachineBasicBlock *Block;
59 
60     public:
61       MergePotentialsElt(unsigned h, MachineBasicBlock *b)
62         : Hash(h), Block(b) {}
63 
64       unsigned getHash() const { return Hash; }
65       MachineBasicBlock *getBlock() const { return Block; }
66 
67       void setBlock(MachineBasicBlock *MBB) {
68         Block = MBB;
69       }
70 
71       bool operator<(const MergePotentialsElt &) const;
72     };
73 
74     using MPIterator = std::vector<MergePotentialsElt>::iterator;
75 
76     std::vector<MergePotentialsElt> MergePotentials;
77     SmallPtrSet<const MachineBasicBlock*, 2> TriedMerging;
78     DenseMap<const MachineBasicBlock *, int> EHScopeMembership;
79 
80     class SameTailElt {
81       MPIterator MPIter;
82       MachineBasicBlock::iterator TailStartPos;
83 
84     public:
85       SameTailElt(MPIterator mp, MachineBasicBlock::iterator tsp)
86         : MPIter(mp), TailStartPos(tsp) {}
87 
88       MPIterator getMPIter() const {
89         return MPIter;
90       }
91 
92       MergePotentialsElt &getMergePotentialsElt() const {
93         return *getMPIter();
94       }
95 
96       MachineBasicBlock::iterator getTailStartPos() const {
97         return TailStartPos;
98       }
99 
100       unsigned getHash() const {
101         return getMergePotentialsElt().getHash();
102       }
103 
104       MachineBasicBlock *getBlock() const {
105         return getMergePotentialsElt().getBlock();
106       }
107 
108       bool tailIsWholeBlock() const {
109         return TailStartPos == getBlock()->begin();
110       }
111 
112       void setBlock(MachineBasicBlock *MBB) {
113         getMergePotentialsElt().setBlock(MBB);
114       }
115 
116       void setTailStartPos(MachineBasicBlock::iterator Pos) {
117         TailStartPos = Pos;
118       }
119     };
120     std::vector<SameTailElt> SameTails;
121 
122     bool AfterBlockPlacement;
123     bool EnableTailMerge;
124     bool EnableHoistCommonCode;
125     bool UpdateLiveIns;
126     unsigned MinCommonTailLength;
127     const TargetInstrInfo *TII;
128     const MachineRegisterInfo *MRI;
129     const TargetRegisterInfo *TRI;
130     MachineModuleInfo *MMI;
131     MachineLoopInfo *MLI;
132     LivePhysRegs LiveRegs;
133 
134   private:
135     MBFIWrapper &MBBFreqInfo;
136     const MachineBranchProbabilityInfo &MBPI;
137     ProfileSummaryInfo *PSI;
138 
139     bool TailMergeBlocks(MachineFunction &MF);
140     bool TryTailMergeBlocks(MachineBasicBlock* SuccBB,
141                        MachineBasicBlock* PredBB,
142                        unsigned MinCommonTailLength);
143     void setCommonTailEdgeWeights(MachineBasicBlock &TailMBB);
144 
145     /// Delete the instruction OldInst and everything after it, replacing it
146     /// with an unconditional branch to NewDest.
147     void replaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
148                                  MachineBasicBlock &NewDest);
149 
150     /// Given a machine basic block and an iterator into it, split the MBB so
151     /// that the part before the iterator falls into the part starting at the
152     /// iterator.  This returns the new MBB.
153     MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
154                                   MachineBasicBlock::iterator BBI1,
155                                   const BasicBlock *BB);
156 
157     /// Look through all the blocks in MergePotentials that have hash CurHash
158     /// (guaranteed to match the last element).  Build the vector SameTails of
159     /// all those that have the (same) largest number of instructions in common
160     /// of any pair of these blocks.  SameTails entries contain an iterator into
161     /// MergePotentials (from which the MachineBasicBlock can be found) and a
162     /// MachineBasicBlock::iterator into that MBB indicating the instruction
163     /// where the matching code sequence begins.  Order of elements in SameTails
164     /// is the reverse of the order in which those blocks appear in
165     /// MergePotentials (where they are not necessarily consecutive).
166     unsigned ComputeSameTails(unsigned CurHash, unsigned minCommonTailLength,
167                               MachineBasicBlock *SuccBB,
168                               MachineBasicBlock *PredBB);
169 
170     /// Remove all blocks with hash CurHash from MergePotentials, restoring
171     /// branches at ends of blocks as appropriate.
172     void RemoveBlocksWithHash(unsigned CurHash, MachineBasicBlock* SuccBB,
173                                                 MachineBasicBlock* PredBB);
174 
175     /// None of the blocks to be tail-merged consist only of the common tail.
176     /// Create a block that does by splitting one.
177     bool CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
178                                    MachineBasicBlock *SuccBB,
179                                    unsigned maxCommonTailLength,
180                                    unsigned &commonTailIndex);
181 
182     /// Create merged DebugLocs of identical instructions across SameTails and
183     /// assign it to the instruction in common tail; merge MMOs and undef flags.
184     void mergeCommonTails(unsigned commonTailIndex);
185 
186     bool OptimizeBranches(MachineFunction &MF);
187 
188     /// Analyze and optimize control flow related to the specified block. This
189     /// is never called on the entry block.
190     bool OptimizeBlock(MachineBasicBlock *MBB);
191 
192     /// Remove the specified dead machine basic block from the function,
193     /// updating the CFG.
194     void RemoveDeadBlock(MachineBasicBlock *MBB);
195 
196     /// Hoist common instruction sequences at the start of basic blocks to their
197     /// common predecessor.
198     bool HoistCommonCode(MachineFunction &MF);
199 
200     /// If the successors of MBB has common instruction sequence at the start of
201     /// the function, move the instructions before MBB terminator if it's legal.
202     bool HoistCommonCodeInSuccs(MachineBasicBlock *MBB);
203   };
204 
205 } // end namespace llvm
206 
207 #endif // LLVM_LIB_CODEGEN_BRANCHFOLDING_H
208