llvm.org GIT mirror llvm / 0f940c9
Initial commit of the machine code LICM pass. It successfully hoists this: _foo: li r2, 0 LBB1_1: ; bb li r5, 0 stw r5, 0(r3) addi r2, r2, 1 addi r3, r3, 4 cmplw cr0, r2, r4 bne cr0, LBB1_1 ; bb LBB1_2: ; return blr to: _foo: li r2, 0 li r5, 0 LBB1_1: ; bb stw r5, 0(r3) addi r2, r2, 1 addi r3, r3, 4 cmplw cr0, r2, r4 bne cr0, LBB1_1 ; bb LBB1_2: ; return blr ZOMG!! :-) Moar to come... git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@44687 91177308-0d34-0410-b5e6-96231b3b80d8 Bill Wendling 12 years ago
4 changed file(s) with 357 addition(s) and 10 deletion(s). Raw diff Collapse all Expand all
134134 /// for the Sparc.
135135 FunctionPass *getRegisterAllocator(TargetMachine &T);
136136
137 /// createMachineLICMPass - This pass performs LICM on machine instructions.
138 ///
139 FunctionPass *createMachineLICMPass();
140
137141 } // End llvm namespace
138142
139143 #endif
6565 // Print the instruction selected machine code...
6666 if (PrintMachineCode)
6767 PM.add(createMachineFunctionPrinterPass(cerr));
68
68
69 PM.add(createMachineLICMPass());
70
6971 // Perform register allocation to convert to a concrete x86 representation
7072 PM.add(createRegisterAllocator());
7173
9193 // Branch folding must be run after regalloc and prolog/epilog insertion.
9294 if (!Fast)
9395 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
94
96
9597 // Fold redundant debug labels.
9698 PM.add(createDebugLabelFoldingPass());
9799
174176 // Print the instruction selected machine code...
175177 if (PrintMachineCode)
176178 PM.add(createMachineFunctionPrinterPass(cerr));
177
179
180 PM.add(createMachineLICMPass());
181
178182 // Perform register allocation to convert to a concrete x86 representation
179183 PM.add(createRegisterAllocator());
180184
203207 // Branch folding must be run after regalloc and prolog/epilog insertion.
204208 if (!Fast)
205209 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
206
210
207211 if (addPreEmitPass(PM, Fast) && PrintMachineCode)
208212 PM.add(createMachineFunctionPrinterPass(cerr));
209213
0 //===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file was developed by Bill Wendling and is distributed under the
5 // University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass performs loop invariant code motion on machine instructions. We
10 // attempt to remove as much code from the body of a loop as possible.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "machine-licm"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/CodeGen/MachineBasicBlock.h"
18 #include "llvm/CodeGen/MachineDominators.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/CodeGen/MachineLoopInfo.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Support/CFG.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Target/MRegisterInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include
30
31 using namespace llvm;
32
33 namespace {
34 // Hidden options to help debugging
35 cl::opt
36 PerformLICM("machine-licm",
37 cl::init(false), cl::Hidden);
38 }
39
40 namespace {
41 class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
42 // Various analyses that we use...
43 MachineLoopInfo *LI; // Current MachineLoopInfo
44 MachineDominatorTree *DT; // Machine dominator tree for the current Loop
45
46 const TargetInstrInfo *TII;
47
48 // State that is updated as we process loops
49 bool Changed; // True if a loop is changed.
50 MachineLoop *CurLoop; // The current loop we are working on.
51
52 // Map the def of a virtual register to the machine instruction.
53 std::map VRegDefs;
54 public:
55 static char ID; // Pass identification, replacement for typeid
56 MachineLICM() : MachineFunctionPass((intptr_t)&ID) {}
57
58 virtual bool runOnMachineFunction(MachineFunction &MF);
59
60 /// FIXME: Loop preheaders?
61 ///
62 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
63 AU.setPreservesCFG();
64 AU.addRequired();
65 AU.addRequired();
66 }
67 private:
68 /// GatherAllLoops - Get all loops in depth first order.
69 ///
70 void GatherAllLoops(MachineLoop *L, SmallVectorImpl &Loops) {
71 const std::vector &SubLoops = L->getSubLoops();
72
73 for (MachineLoop::iterator
74 I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I)
75 GatherAllLoops(*I, Loops);
76
77 Loops.push_back(L);
78 }
79
80 /// MapVirtualRegisterDefs - Create a map of which machine instruction
81 /// defines a virtual register.
82 ///
83 void MapVirtualRegisterDefs(const MachineFunction &MF);
84
85 /// isInSubLoop - A little predicate that returns true if the specified
86 /// basic block is in a subloop of the current one, not the current one
87 /// itself.
88 ///
89 bool isInSubLoop(MachineBasicBlock *BB) {
90 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
91
92 for (MachineLoop::iterator
93 I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
94 if ((*I)->contains(BB))
95 return true; // A subloop actually contains this block!
96
97 return false;
98 }
99
100 /// CanHoistInst - Checks that this instructions is one that can be hoisted
101 /// out of the loop. I.e., it has no side effects, isn't a control flow
102 /// instr, etc.
103 ///
104 bool CanHoistInst(MachineInstr &I) const {
105 const TargetInstrDescriptor *TID = I.getInstrDescriptor();
106 MachineOpCode Opcode = TID->Opcode;
107
108 return TII->isTriviallyReMaterializable(&I) &&
109 // FIXME: Below necessary?
110 !(TII->isReturn(Opcode) ||
111 TII->isTerminatorInstr(Opcode) ||
112 TII->isBranch(Opcode) ||
113 TII->isIndirectBranch(Opcode) ||
114 TII->isBarrier(Opcode) ||
115 TII->isCall(Opcode) ||
116 TII->isLoad(Opcode) || // TODO: Do loads and stores.
117 TII->isStore(Opcode));
118 }
119
120 /// isLoopInvariantInst - Returns true if the instruction is loop
121 /// invariant. I.e., all virtual register operands are defined outside of
122 /// the loop, physical registers aren't accessed (explicitly or implicitly),
123 /// and the instruction is hoistable.
124 ///
125 bool isLoopInvariantInst(MachineInstr &I);
126
127 /// FindPredecessors - Get all of the predecessors of the loop that are not
128 /// back-edges.
129 ///
130 void FindPredecessors(std::vector &Preds){
131 const MachineBasicBlock *Header = CurLoop->getHeader();
132
133 for (MachineBasicBlock::const_pred_iterator
134 I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
135 if (!CurLoop->contains(*I))
136 Preds.push_back(*I);
137 }
138
139 /// MoveInstToBlock - Moves the machine instruction to the bottom of the
140 /// predecessor basic block (but before the terminator instructions).
141 ///
142 void MoveInstToBlock(MachineBasicBlock *MBB, MachineInstr *MI) {
143 MachineBasicBlock::iterator Iter = MBB->getFirstTerminator();
144 MBB->insert(Iter, MI);
145 }
146
147 /// HoistRegion - Walk the specified region of the CFG (defined by all
148 /// blocks dominated by the specified block, and that are in the current
149 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
150 /// visit definitions before uses, allowing us to hoist a loop body in one
151 /// pass without iteration.
152 ///
153 void HoistRegion(MachineDomTreeNode *N);
154
155 /// Hoist - When an instruction is found to only use loop invariant operands
156 /// that is safe to hoist, this instruction is called to do the dirty work.
157 ///
158 bool Hoist(MachineInstr &MI);
159 };
160
161 char MachineLICM::ID = 0;
162 RegisterPass X("machine-licm",
163 "Machine Loop Invariant Code Motion");
164 } // end anonymous namespace
165
166 FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
167
168 /// Hoist expressions out of the specified loop. Note, alias info for inner loop
169 /// is not preserved so it is not a good idea to run LICM multiple times on one
170 /// loop.
171 ///
172 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
173 if (!PerformLICM) return false; // For debugging.
174
175 Changed = false;
176 TII = MF.getTarget().getInstrInfo();
177
178 // Get our Loop information...
179 LI = &getAnalysis();
180 DT = &getAnalysis();
181
182 for (MachineLoopInfo::iterator
183 I = LI->begin(), E = LI->end(); I != E; ++I) {
184 MachineLoop *L = *I;
185 CurLoop = L;
186
187 // Visit all of the instructions of the loop. We want to visit the subloops
188 // first, though, so that we can hoist their invariants first into their
189 // containing loop before we process that loop.
190 SmallVector Loops;
191 GatherAllLoops(L, Loops);
192
193 for (SmallVector::iterator
194 II = Loops.begin(), IE = Loops.end(); II != IE; ++II) {
195 L = *II;
196
197 // Traverse the body of the loop in depth first order on the dominator
198 // tree so that we are guaranteed to see definitions before we see uses.
199 HoistRegion(DT->getNode(L->getHeader()));
200 }
201 }
202
203 return Changed;
204 }
205
206 /// MapVirtualRegisterDefs - Create a map of which machine instruction defines a
207 /// virtual register.
208 ///
209 void MachineLICM::MapVirtualRegisterDefs(const MachineFunction &MF) {
210 for (MachineFunction::const_iterator
211 I = MF.begin(), E = MF.end(); I != E; ++I) {
212 const MachineBasicBlock &MBB = *I;
213
214 for (MachineBasicBlock::const_iterator
215 II = MBB.begin(), IE = MBB.end(); II != IE; ++II) {
216 const MachineInstr &MI = *II;
217
218 if (MI.getNumOperands() > 0) {
219 const MachineOperand &MO = MI.getOperand(0);
220
221 if (MO.isRegister() && MO.isDef() &&
222 MRegisterInfo::isVirtualRegister(MO.getReg()))
223 VRegDefs[MO.getReg()] = &MI;
224 }
225 }
226 }
227 }
228
229 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
230 /// dominated by the specified block, and that are in the current loop) in depth
231 /// first order w.r.t the DominatorTree. This allows us to visit definitions
232 /// before uses, allowing us to hoist a loop body in one pass without iteration.
233 ///
234 void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
235 assert(N != 0 && "Null dominator tree node?");
236 MachineBasicBlock *BB = N->getBlock();
237
238 // If this subregion is not in the top level loop at all, exit.
239 if (!CurLoop->contains(BB)) return;
240
241 // Only need to process the contents of this block if it is not part of a
242 // subloop (which would already have been processed).
243 if (!isInSubLoop(BB))
244 for (MachineBasicBlock::iterator
245 I = BB->begin(), E = BB->end(); I != E; ) {
246 MachineInstr &MI = *I++;
247
248 // Try hoisting the instruction out of the loop. We can only do this if
249 // all of the operands of the instruction are loop invariant and if it is
250 // safe to hoist the instruction.
251 if (Hoist(MI))
252 // Hoisting was successful! Remove bothersome instruction now.
253 MI.getParent()->remove(&MI);
254 }
255
256 const std::vector &Children = N->getChildren();
257
258 for (unsigned I = 0, E = Children.size(); I != E; ++I)
259 HoistRegion(Children[I]);
260 }
261
262 /// isLoopInvariantInst - Returns true if the instruction is loop
263 /// invariant. I.e., all virtual register operands are defined outside of the
264 /// loop, physical registers aren't accessed (explicitly or implicitly), and the
265 /// instruction is hoistable.
266 ///
267 bool MachineLICM::isLoopInvariantInst(MachineInstr &I) {
268 const TargetInstrDescriptor *TID = I.getInstrDescriptor();
269
270 // Don't hoist if this instruction implicitly reads physical registers or
271 // doesn't take any operands.
272 if (TID->ImplicitUses || !I.getNumOperands()) return false;
273
274 if (!CanHoistInst(I)) return false;
275
276 // The instruction is loop invariant if all of its operands are loop-invariant
277 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
278 const MachineOperand &MO = I.getOperand(i);
279
280 if (!MO.isRegister() || !MO.isUse())
281 continue;
282
283 unsigned Reg = MO.getReg();
284
285 // Don't hoist instructions that access physical registers.
286 if (!MRegisterInfo::isVirtualRegister(Reg))
287 return false;
288
289 assert(VRegDefs[Reg] && "Machine instr not mapped for this vreg?!");
290
291 // If the loop contains the definition of an operand, then the instruction
292 // isn't loop invariant.
293 if (CurLoop->contains(VRegDefs[Reg]->getParent()))
294 return false;
295 }
296
297 // If we got this far, the instruction is loop invariant!
298 return true;
299 }
300
301 /// Hoist - When an instruction is found to only use loop invariant operands
302 /// that is safe to hoist, this instruction is called to do the dirty work.
303 ///
304 bool MachineLICM::Hoist(MachineInstr &MI) {
305 if (!isLoopInvariantInst(MI)) return false;
306
307 std::vector Preds;
308
309 // Non-back-edge predecessors.
310 FindPredecessors(Preds);
311 if (Preds.empty()) return false;
312
313 // Check that the predecessors are qualified to take the hoisted
314 // instruction. I.e., there is only one edge from each predecessor, and it's
315 // to the loop header.
316 for (std::vector::iterator
317 I = Preds.begin(), E = Preds.end(); I != E; ++I) {
318 MachineBasicBlock *MBB = *I;
319
320 // FIXME: We are assuming at first that the basic blocks coming into this
321 // loop have only one successor each. This isn't the case in general because
322 // we haven't broken critical edges or added preheaders.
323 if (MBB->succ_size() != 1) return false;
324 assert(*MBB->succ_begin() == CurLoop->getHeader() &&
325 "The predecessor doesn't feed directly into the loop header!");
326 }
327
328 // Now move the instructions to the predecessors.
329 for (std::vector::iterator
330 I = Preds.begin(), E = Preds.end(); I != E; ++I)
331 MoveInstToBlock(*I, MI.clone());
332
333 Changed = true;
334 return true;
335 }
683683 def SUBFIC : DForm_2< 8, (outs GPRC:$rD), (ins GPRC:$rA, s16imm:$imm),
684684 "subfic $rD, $rA, $imm", IntGeneral,
685685 [(set GPRC:$rD, (subc immSExt16:$imm, GPRC:$rA))]>;
686 def LI : DForm_2_r0<14, (outs GPRC:$rD), (ins symbolLo:$imm),
687 "li $rD, $imm", IntGeneral,
688 [(set GPRC:$rD, immSExt16:$imm)]>;
689 def LIS : DForm_2_r0<15, (outs GPRC:$rD), (ins symbolHi:$imm),
690 "lis $rD, $imm", IntGeneral,
691 [(set GPRC:$rD, imm16ShiftedSExt:$imm)]>;
686
687 let isReMaterializable = 1 in {
688 def LI : DForm_2_r0<14, (outs GPRC:$rD), (ins symbolLo:$imm),
689 "li $rD, $imm", IntGeneral,
690 [(set GPRC:$rD, immSExt16:$imm)]>;
691 def LIS : DForm_2_r0<15, (outs GPRC:$rD), (ins symbolHi:$imm),
692 "lis $rD, $imm", IntGeneral,
693 [(set GPRC:$rD, imm16ShiftedSExt:$imm)]>;
694 }
692695 }
693696
694697 let PPC970_Unit = 1 in { // FXU Operations.