1 //===-- HexagonCFGOptimizer.cpp - CFG optimizations -----------------------===//
2 //                     The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Hexagon.h"
10 #include "HexagonMachineFunctionInfo.h"
11 #include "HexagonSubtarget.h"
12 #include "HexagonTargetMachine.h"
13 #include "llvm/CodeGen/MachineDominators.h"
14 #include "llvm/CodeGen/MachineFunctionPass.h"
15 #include "llvm/CodeGen/MachineInstrBuilder.h"
16 #include "llvm/CodeGen/MachineLoopInfo.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 
25 using namespace llvm;
26 
27 #define DEBUG_TYPE "hexagon_cfg"
28 
29 namespace llvm {
30   FunctionPass *createHexagonCFGOptimizer();
31   void initializeHexagonCFGOptimizerPass(PassRegistry&);
32 }
33 
34 
35 namespace {
36 
37 class HexagonCFGOptimizer : public MachineFunctionPass {
38 
39 private:
40   void InvertAndChangeJumpTarget(MachineInstr*, MachineBasicBlock*);
41 
42  public:
43   static char ID;
44   HexagonCFGOptimizer() : MachineFunctionPass(ID) {
45     initializeHexagonCFGOptimizerPass(*PassRegistry::getPassRegistry());
46   }
47 
48   const char *getPassName() const override {
49     return "Hexagon CFG Optimizer";
50   }
51   bool runOnMachineFunction(MachineFunction &Fn) override;
52   MachineFunctionProperties getRequiredProperties() const override {
53     return MachineFunctionProperties().set(
54         MachineFunctionProperties::Property::AllVRegsAllocated);
55   }
56 };
57 
58 
59 char HexagonCFGOptimizer::ID = 0;
60 
61 static bool IsConditionalBranch(int Opc) {
62   return (Opc == Hexagon::J2_jumpt) || (Opc == Hexagon::J2_jumpf)
63     || (Opc == Hexagon::J2_jumptnewpt) || (Opc == Hexagon::J2_jumpfnewpt);
64 }
65 
66 
67 static bool IsUnconditionalJump(int Opc) {
68   return (Opc == Hexagon::J2_jump);
69 }
70 
71 
72 void
73 HexagonCFGOptimizer::InvertAndChangeJumpTarget(MachineInstr* MI,
74                                                MachineBasicBlock* NewTarget) {
75   const TargetInstrInfo *TII =
76       MI->getParent()->getParent()->getSubtarget().getInstrInfo();
77   int NewOpcode = 0;
78   switch(MI->getOpcode()) {
79   case Hexagon::J2_jumpt:
80     NewOpcode = Hexagon::J2_jumpf;
81     break;
82 
83   case Hexagon::J2_jumpf:
84     NewOpcode = Hexagon::J2_jumpt;
85     break;
86 
87   case Hexagon::J2_jumptnewpt:
88     NewOpcode = Hexagon::J2_jumpfnewpt;
89     break;
90 
91   case Hexagon::J2_jumpfnewpt:
92     NewOpcode = Hexagon::J2_jumptnewpt;
93     break;
94 
95   default:
96     llvm_unreachable("Cannot handle this case");
97   }
98 
99   MI->setDesc(TII->get(NewOpcode));
100   MI->getOperand(1).setMBB(NewTarget);
101 }
102 
103 
104 bool HexagonCFGOptimizer::runOnMachineFunction(MachineFunction &Fn) {
105   if (skipFunction(*Fn.getFunction()))
106     return false;
107 
108   // Loop over all of the basic blocks.
109   for (MachineFunction::iterator MBBb = Fn.begin(), MBBe = Fn.end();
110        MBBb != MBBe; ++MBBb) {
111     MachineBasicBlock *MBB = &*MBBb;
112 
113     // Traverse the basic block.
114     MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
115     if (MII != MBB->end()) {
116       MachineInstr *MI = MII;
117       int Opc = MI->getOpcode();
118       if (IsConditionalBranch(Opc)) {
119 
120         //
121         // (Case 1) Transform the code if the following condition occurs:
122         //   BB1: if (p0) jump BB3
123         //   ...falls-through to BB2 ...
124         //   BB2: jump BB4
125         //   ...next block in layout is BB3...
126         //   BB3: ...
127         //
128         //  Transform this to:
129         //  BB1: if (!p0) jump BB4
130         //  Remove BB2
131         //  BB3: ...
132         //
133         // (Case 2) A variation occurs when BB3 contains a JMP to BB4:
134         //   BB1: if (p0) jump BB3
135         //   ...falls-through to BB2 ...
136         //   BB2: jump BB4
137         //   ...other basic blocks ...
138         //   BB4:
139         //   ...not a fall-thru
140         //   BB3: ...
141         //     jump BB4
142         //
143         // Transform this to:
144         //   BB1: if (!p0) jump BB4
145         //   Remove BB2
146         //   BB3: ...
147         //   BB4: ...
148         //
149         unsigned NumSuccs = MBB->succ_size();
150         MachineBasicBlock::succ_iterator SI = MBB->succ_begin();
151         MachineBasicBlock* FirstSucc = *SI;
152         MachineBasicBlock* SecondSucc = *(++SI);
153         MachineBasicBlock* LayoutSucc = nullptr;
154         MachineBasicBlock* JumpAroundTarget = nullptr;
155 
156         if (MBB->isLayoutSuccessor(FirstSucc)) {
157           LayoutSucc = FirstSucc;
158           JumpAroundTarget = SecondSucc;
159         } else if (MBB->isLayoutSuccessor(SecondSucc)) {
160           LayoutSucc = SecondSucc;
161           JumpAroundTarget = FirstSucc;
162         } else {
163           // Odd case...cannot handle.
164         }
165 
166         // The target of the unconditional branch must be JumpAroundTarget.
167         // TODO: If not, we should not invert the unconditional branch.
168         MachineBasicBlock* CondBranchTarget = nullptr;
169         if ((MI->getOpcode() == Hexagon::J2_jumpt) ||
170             (MI->getOpcode() == Hexagon::J2_jumpf)) {
171           CondBranchTarget = MI->getOperand(1).getMBB();
172         }
173 
174         if (!LayoutSucc || (CondBranchTarget != JumpAroundTarget)) {
175           continue;
176         }
177 
178         if ((NumSuccs == 2) && LayoutSucc && (LayoutSucc->pred_size() == 1)) {
179 
180           // Ensure that BB2 has one instruction -- an unconditional jump.
181           if ((LayoutSucc->size() == 1) &&
182               IsUnconditionalJump(LayoutSucc->front().getOpcode())) {
183             assert(JumpAroundTarget && "jump target is needed to process second basic block");
184             MachineBasicBlock* UncondTarget =
185               LayoutSucc->front().getOperand(0).getMBB();
186             // Check if the layout successor of BB2 is BB3.
187             bool case1 = LayoutSucc->isLayoutSuccessor(JumpAroundTarget);
188             bool case2 = JumpAroundTarget->isSuccessor(UncondTarget) &&
189               JumpAroundTarget->size() >= 1 &&
190               IsUnconditionalJump(JumpAroundTarget->back().getOpcode()) &&
191               JumpAroundTarget->pred_size() == 1 &&
192               JumpAroundTarget->succ_size() == 1;
193 
194             if (case1 || case2) {
195               InvertAndChangeJumpTarget(MI, UncondTarget);
196               MBB->replaceSuccessor(JumpAroundTarget, UncondTarget);
197 
198               // Remove the unconditional branch in LayoutSucc.
199               LayoutSucc->erase(LayoutSucc->begin());
200               LayoutSucc->replaceSuccessor(UncondTarget, JumpAroundTarget);
201 
202               // This code performs the conversion for case 2, which moves
203               // the block to the fall-thru case (BB3 in the code above).
204               if (case2 && !case1) {
205                 JumpAroundTarget->moveAfter(LayoutSucc);
206                 // only move a block if it doesn't have a fall-thru. otherwise
207                 // the CFG will be incorrect.
208                 if (!UncondTarget->canFallThrough()) {
209                   UncondTarget->moveAfter(JumpAroundTarget);
210                 }
211               }
212 
213               //
214               // Correct live-in information. Is used by post-RA scheduler
215               // The live-in to LayoutSucc is now all values live-in to
216               // JumpAroundTarget.
217               //
218               std::vector<MachineBasicBlock::RegisterMaskPair> OrigLiveIn(
219                   LayoutSucc->livein_begin(), LayoutSucc->livein_end());
220               std::vector<MachineBasicBlock::RegisterMaskPair> NewLiveIn(
221                   JumpAroundTarget->livein_begin(),
222                   JumpAroundTarget->livein_end());
223               for (const auto &OrigLI : OrigLiveIn)
224                 LayoutSucc->removeLiveIn(OrigLI.PhysReg);
225               for (const auto &NewLI : NewLiveIn)
226                 LayoutSucc->addLiveIn(NewLI);
227             }
228           }
229         }
230       }
231     }
232   }
233   return true;
234 }
235 }
236 
237 
238 //===----------------------------------------------------------------------===//
239 //                         Public Constructor Functions
240 //===----------------------------------------------------------------------===//
241 
242 INITIALIZE_PASS(HexagonCFGOptimizer, "hexagon-cfg", "Hexagon CFG Optimizer",
243                 false, false)
244 
245 FunctionPass *llvm::createHexagonCFGOptimizer() {
246   return new HexagonCFGOptimizer();
247 }
248