blob: a68ea1934ae129487c840516c9f36282528f18a2 [file] [log] [blame]
Puyan Lotfia521c4ac52017-11-02 23:37:32 +00001//===-------------- MIRCanonicalizer.cpp - MIR Canonicalizer --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// The purpose of this pass is to employ a canonical code transformation so
11// that code compiled with slightly different IR passes can be diffed more
12// effectively than otherwise. This is done by renaming vregs in a given
13// LiveRange in a canonical way. This pass also does a pseudo-scheduling to
14// move defs closer to their use inorder to reduce diffs caused by slightly
15// different schedules.
16//
17// Basic Usage:
18//
19// llc -o - -run-pass mir-canonicalizer example.mir
20//
21// Reorders instructions canonically.
22// Renames virtual register operands canonically.
23// Strips certain MIR artifacts (optionally).
24//
25//===----------------------------------------------------------------------===//
26
27#include "llvm/ADT/PostOrderIterator.h"
28#include "llvm/ADT/STLExtras.h"
Puyan Lotfia521c4ac52017-11-02 23:37:32 +000029#include "llvm/CodeGen/MachineFunctionPass.h"
30#include "llvm/CodeGen/MachineInstrBuilder.h"
31#include "llvm/CodeGen/MachineRegisterInfo.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000032#include "llvm/CodeGen/Passes.h"
Puyan Lotfia521c4ac52017-11-02 23:37:32 +000033#include "llvm/Support/raw_ostream.h"
Puyan Lotfia521c4ac52017-11-02 23:37:32 +000034
35#include <queue>
36
37using namespace llvm;
38
39namespace llvm {
40extern char &MIRCanonicalizerID;
41} // namespace llvm
42
43#define DEBUG_TYPE "mir-canonicalizer"
44
45static cl::opt<unsigned>
Puyan Lotfi6ea89b42018-04-16 08:12:15 +000046 CanonicalizeFunctionNumber("canon-nth-function", cl::Hidden, cl::init(~0u),
47 cl::value_desc("N"),
48 cl::desc("Function number to canonicalize."));
Puyan Lotfia521c4ac52017-11-02 23:37:32 +000049
Puyan Lotfi6ea89b42018-04-16 08:12:15 +000050static cl::opt<unsigned> CanonicalizeBasicBlockNumber(
51 "canon-nth-basicblock", cl::Hidden, cl::init(~0u), cl::value_desc("N"),
52 cl::desc("BasicBlock number to canonicalize."));
Puyan Lotfia521c4ac52017-11-02 23:37:32 +000053
54namespace {
55
56class MIRCanonicalizer : public MachineFunctionPass {
57public:
58 static char ID;
59 MIRCanonicalizer() : MachineFunctionPass(ID) {}
60
61 StringRef getPassName() const override {
62 return "Rename register operands in a canonical ordering.";
63 }
64
65 void getAnalysisUsage(AnalysisUsage &AU) const override {
66 AU.setPreservesCFG();
67 MachineFunctionPass::getAnalysisUsage(AU);
68 }
69
70 bool runOnMachineFunction(MachineFunction &MF) override;
71};
72
73} // end anonymous namespace
74
75enum VRType { RSE_Reg = 0, RSE_FrameIndex, RSE_NewCandidate };
76class TypedVReg {
77 VRType type;
78 unsigned reg;
79
80public:
81 TypedVReg(unsigned reg) : type(RSE_Reg), reg(reg) {}
82 TypedVReg(VRType type) : type(type), reg(~0U) {
83 assert(type != RSE_Reg && "Expected a non-register type.");
84 }
85
Puyan Lotfi6ea89b42018-04-16 08:12:15 +000086 bool isReg() const { return type == RSE_Reg; }
87 bool isFrameIndex() const { return type == RSE_FrameIndex; }
88 bool isCandidate() const { return type == RSE_NewCandidate; }
Puyan Lotfia521c4ac52017-11-02 23:37:32 +000089
90 VRType getType() const { return type; }
91 unsigned getReg() const {
92 assert(this->isReg() && "Expected a virtual or physical register.");
93 return reg;
94 }
95};
96
97char MIRCanonicalizer::ID;
98
99char &llvm::MIRCanonicalizerID = MIRCanonicalizer::ID;
100
101INITIALIZE_PASS_BEGIN(MIRCanonicalizer, "mir-canonicalizer",
Craig Topper666e23b2017-11-03 18:02:46 +0000102 "Rename Register Operands Canonically", false, false)
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000103
104INITIALIZE_PASS_END(MIRCanonicalizer, "mir-canonicalizer",
Craig Topper666e23b2017-11-03 18:02:46 +0000105 "Rename Register Operands Canonically", false, false)
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000106
107static std::vector<MachineBasicBlock *> GetRPOList(MachineFunction &MF) {
108 ReversePostOrderTraversal<MachineBasicBlock *> RPOT(&*MF.begin());
109 std::vector<MachineBasicBlock *> RPOList;
110 for (auto MBB : RPOT) {
111 RPOList.push_back(MBB);
112 }
113
114 return RPOList;
115}
116
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000117static bool
118rescheduleLexographically(std::vector<MachineInstr *> instructions,
119 MachineBasicBlock *MBB,
120 std::function<MachineBasicBlock::iterator()> getPos) {
121
122 bool Changed = false;
Puyan Lotfi380a6f52018-05-13 06:07:20 +0000123 using StringInstrPair = std::pair<std::string, MachineInstr *>;
124 std::vector<StringInstrPair> StringInstrMap;
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000125
126 for (auto *II : instructions) {
127 std::string S;
128 raw_string_ostream OS(S);
129 II->print(OS);
130 OS.flush();
131
132 // Trim the assignment, or start from the begining in the case of a store.
133 const size_t i = S.find("=");
Puyan Lotfi380a6f52018-05-13 06:07:20 +0000134 StringInstrMap.push_back({(i == std::string::npos) ? S : S.substr(i), II});
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000135 }
136
Puyan Lotfi380a6f52018-05-13 06:07:20 +0000137 std::sort(StringInstrMap.begin(), StringInstrMap.end(),
138 [](StringInstrPair &a, StringInstrPair &b) {
139 return (a.first < b.first);
140 });
141
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000142 for (auto &II : StringInstrMap) {
143
144 DEBUG({
145 dbgs() << "Splicing ";
146 II.second->dump();
147 dbgs() << " right before: ";
148 getPos()->dump();
149 });
150
151 Changed = true;
152 MBB->splice(getPos(), MBB, II.second);
153 }
154
155 return Changed;
156}
157
158static bool rescheduleCanonically(unsigned &PseudoIdempotentInstCount,
159 MachineBasicBlock *MBB) {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000160
161 bool Changed = false;
162
163 // Calculates the distance of MI from the begining of its parent BB.
164 auto getInstrIdx = [](const MachineInstr &MI) {
165 unsigned i = 0;
166 for (auto &CurMI : *MI.getParent()) {
167 if (&CurMI == &MI)
168 return i;
169 i++;
170 }
171 return ~0U;
172 };
173
174 // Pre-Populate vector of instructions to reschedule so that we don't
175 // clobber the iterator.
176 std::vector<MachineInstr *> Instructions;
177 for (auto &MI : *MBB) {
178 Instructions.push_back(&MI);
179 }
180
Puyan Lotfi26c504f2018-04-05 00:08:15 +0000181 std::map<MachineInstr *, std::vector<MachineInstr *>> MultiUsers;
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000182 std::vector<MachineInstr *> PseudoIdempotentInstructions;
183 std::vector<unsigned> PhysRegDefs;
184 for (auto *II : Instructions) {
185 for (unsigned i = 1; i < II->getNumOperands(); i++) {
186 MachineOperand &MO = II->getOperand(i);
187 if (!MO.isReg())
188 continue;
189
190 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
191 continue;
192
193 if (!MO.isDef())
194 continue;
195
196 PhysRegDefs.push_back(MO.getReg());
197 }
198 }
199
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000200 for (auto *II : Instructions) {
201 if (II->getNumOperands() == 0)
202 continue;
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000203 if (II->mayLoadOrStore())
204 continue;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000205
206 MachineOperand &MO = II->getOperand(0);
207 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
208 continue;
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000209 if (!MO.isDef())
210 continue;
211
212 bool IsPseudoIdempotent = true;
213 for (unsigned i = 1; i < II->getNumOperands(); i++) {
214
215 if (II->getOperand(i).isImm()) {
216 continue;
217 }
218
219 if (II->getOperand(i).isReg()) {
220 if (!TargetRegisterInfo::isVirtualRegister(II->getOperand(i).getReg()))
221 if (llvm::find(PhysRegDefs, II->getOperand(i).getReg()) ==
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000222 PhysRegDefs.end()) {
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000223 continue;
224 }
225 }
226
227 IsPseudoIdempotent = false;
228 break;
229 }
230
231 if (IsPseudoIdempotent) {
232 PseudoIdempotentInstructions.push_back(II);
233 continue;
234 }
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000235
236 DEBUG(dbgs() << "Operand " << 0 << " of "; II->dump(); MO.dump(););
237
238 MachineInstr *Def = II;
239 unsigned Distance = ~0U;
240 MachineInstr *UseToBringDefCloserTo = nullptr;
241 MachineRegisterInfo *MRI = &MBB->getParent()->getRegInfo();
242 for (auto &UO : MRI->use_nodbg_operands(MO.getReg())) {
243 MachineInstr *UseInst = UO.getParent();
244
245 const unsigned DefLoc = getInstrIdx(*Def);
246 const unsigned UseLoc = getInstrIdx(*UseInst);
247 const unsigned Delta = (UseLoc - DefLoc);
248
249 if (UseInst->getParent() != Def->getParent())
250 continue;
251 if (DefLoc >= UseLoc)
252 continue;
253
254 if (Delta < Distance) {
255 Distance = Delta;
256 UseToBringDefCloserTo = UseInst;
257 }
258 }
259
260 const auto BBE = MBB->instr_end();
261 MachineBasicBlock::iterator DefI = BBE;
262 MachineBasicBlock::iterator UseI = BBE;
263
264 for (auto BBI = MBB->instr_begin(); BBI != BBE; ++BBI) {
265
266 if (DefI != BBE && UseI != BBE)
267 break;
268
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000269 if (&*BBI == Def) {
270 DefI = BBI;
271 continue;
272 }
273
274 if (&*BBI == UseToBringDefCloserTo) {
275 UseI = BBI;
276 continue;
277 }
278 }
279
280 if (DefI == BBE || UseI == BBE)
281 continue;
282
283 DEBUG({
284 dbgs() << "Splicing ";
285 DefI->dump();
286 dbgs() << " right before: ";
287 UseI->dump();
288 });
289
Puyan Lotfi26c504f2018-04-05 00:08:15 +0000290 MultiUsers[UseToBringDefCloserTo].push_back(Def);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000291 Changed = true;
292 MBB->splice(UseI, MBB, DefI);
293 }
294
Puyan Lotfi26c504f2018-04-05 00:08:15 +0000295 // Sort the defs for users of multiple defs lexographically.
296 for (const auto &E : MultiUsers) {
297
298 auto UseI =
299 std::find_if(MBB->instr_begin(), MBB->instr_end(),
300 [&](MachineInstr &MI) -> bool { return &MI == E.first; });
301
302 if (UseI == MBB->instr_end())
303 continue;
304
305 DEBUG(dbgs() << "Rescheduling Multi-Use Instructions Lexographically.";);
306 Changed |= rescheduleLexographically(
307 E.second, MBB, [&]() -> MachineBasicBlock::iterator { return UseI; });
308 }
309
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000310 PseudoIdempotentInstCount = PseudoIdempotentInstructions.size();
311 DEBUG(dbgs() << "Rescheduling Idempotent Instructions Lexographically.";);
312 Changed |= rescheduleLexographically(
313 PseudoIdempotentInstructions, MBB,
314 [&]() -> MachineBasicBlock::iterator { return MBB->begin(); });
315
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000316 return Changed;
317}
318
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000319bool propagateLocalCopies(MachineBasicBlock *MBB) {
320 bool Changed = false;
321 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
322
323 std::vector<MachineInstr *> Copies;
324 for (MachineInstr &MI : MBB->instrs()) {
325 if (MI.isCopy())
326 Copies.push_back(&MI);
327 }
328
329 for (MachineInstr *MI : Copies) {
330
331 if (!MI->getOperand(0).isReg())
332 continue;
333 if (!MI->getOperand(1).isReg())
334 continue;
335
336 const unsigned Dst = MI->getOperand(0).getReg();
337 const unsigned Src = MI->getOperand(1).getReg();
338
339 if (!TargetRegisterInfo::isVirtualRegister(Dst))
340 continue;
341 if (!TargetRegisterInfo::isVirtualRegister(Src))
342 continue;
343 if (MRI.getRegClass(Dst) != MRI.getRegClass(Src))
344 continue;
345
346 for (auto UI = MRI.use_begin(Dst); UI != MRI.use_end(); ++UI) {
347 MachineOperand *MO = &*UI;
348 MO->setReg(Src);
349 Changed = true;
350 }
351
352 MI->eraseFromParent();
353 }
354
355 return Changed;
356}
357
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000358/// Here we find our candidates. What makes an interesting candidate?
359/// An candidate for a canonicalization tree root is normally any kind of
360/// instruction that causes side effects such as a store to memory or a copy to
361/// a physical register or a return instruction. We use these as an expression
362/// tree root that we walk inorder to build a canonical walk which should result
363/// in canoncal vreg renaming.
364static std::vector<MachineInstr *> populateCandidates(MachineBasicBlock *MBB) {
365 std::vector<MachineInstr *> Candidates;
366 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
367
368 for (auto II = MBB->begin(), IE = MBB->end(); II != IE; ++II) {
369 MachineInstr *MI = &*II;
370
371 bool DoesMISideEffect = false;
372
373 if (MI->getNumOperands() > 0 && MI->getOperand(0).isReg()) {
374 const unsigned Dst = MI->getOperand(0).getReg();
375 DoesMISideEffect |= !TargetRegisterInfo::isVirtualRegister(Dst);
376
377 for (auto UI = MRI.use_begin(Dst); UI != MRI.use_end(); ++UI) {
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000378 if (DoesMISideEffect)
379 break;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000380 DoesMISideEffect |= (UI->getParent()->getParent() != MI->getParent());
381 }
382 }
383
384 if (!MI->mayStore() && !MI->isBranch() && !DoesMISideEffect)
385 continue;
386
387 DEBUG(dbgs() << "Found Candidate: "; MI->dump(););
388 Candidates.push_back(MI);
389 }
390
391 return Candidates;
392}
393
Benjamin Kramer51ebcaa2017-11-24 14:55:41 +0000394static void doCandidateWalk(std::vector<TypedVReg> &VRegs,
395 std::queue<TypedVReg> &RegQueue,
396 std::vector<MachineInstr *> &VisitedMIs,
397 const MachineBasicBlock *MBB) {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000398
399 const MachineFunction &MF = *MBB->getParent();
400 const MachineRegisterInfo &MRI = MF.getRegInfo();
401
402 while (!RegQueue.empty()) {
403
404 auto TReg = RegQueue.front();
405 RegQueue.pop();
406
407 if (TReg.isFrameIndex()) {
408 DEBUG(dbgs() << "Popping frame index.\n";);
409 VRegs.push_back(TypedVReg(RSE_FrameIndex));
410 continue;
411 }
412
413 assert(TReg.isReg() && "Expected vreg or physreg.");
414 unsigned Reg = TReg.getReg();
415
416 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
417 DEBUG({
418 dbgs() << "Popping vreg ";
419 MRI.def_begin(Reg)->dump();
420 dbgs() << "\n";
421 });
422
423 if (!llvm::any_of(VRegs, [&](const TypedVReg &TR) {
424 return TR.isReg() && TR.getReg() == Reg;
425 })) {
426 VRegs.push_back(TypedVReg(Reg));
427 }
428 } else {
429 DEBUG(dbgs() << "Popping physreg.\n";);
430 VRegs.push_back(TypedVReg(Reg));
431 continue;
432 }
433
434 for (auto RI = MRI.def_begin(Reg), RE = MRI.def_end(); RI != RE; ++RI) {
435 MachineInstr *Def = RI->getParent();
436
437 if (Def->getParent() != MBB)
438 continue;
439
440 if (llvm::any_of(VisitedMIs,
441 [&](const MachineInstr *VMI) { return Def == VMI; })) {
442 break;
443 }
444
445 DEBUG({
446 dbgs() << "\n========================\n";
447 dbgs() << "Visited MI: ";
448 Def->dump();
449 dbgs() << "BB Name: " << Def->getParent()->getName() << "\n";
450 dbgs() << "\n========================\n";
451 });
452 VisitedMIs.push_back(Def);
453 for (unsigned I = 1, E = Def->getNumOperands(); I != E; ++I) {
454
455 MachineOperand &MO = Def->getOperand(I);
456 if (MO.isFI()) {
457 DEBUG(dbgs() << "Pushing frame index.\n";);
458 RegQueue.push(TypedVReg(RSE_FrameIndex));
459 }
460
461 if (!MO.isReg())
462 continue;
463 RegQueue.push(TypedVReg(MO.getReg()));
464 }
465 }
466 }
467}
468
Puyan Lotfid6f73132018-04-05 00:27:15 +0000469class NamedVRegCursor {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000470
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000471private:
472 MachineRegisterInfo &MRI;
473 unsigned virtualVRegNumber;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000474
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000475public:
476 NamedVRegCursor(MachineRegisterInfo &MRI) : MRI(MRI) {
477 unsigned VRegGapIndex = 0;
478 const unsigned VR_GAP = (++VRegGapIndex * 1000);
Puyan Lotfid6f73132018-04-05 00:27:15 +0000479
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000480 unsigned I = MRI.createIncompleteVirtualRegister();
481 const unsigned E = (((I + VR_GAP) / VR_GAP) + 1) * VR_GAP;
Puyan Lotfid6f73132018-04-05 00:27:15 +0000482
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000483 virtualVRegNumber = E;
484 }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000485
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000486 void SkipVRegs() {
487 unsigned VRegGapIndex = 1;
488 const unsigned VR_GAP = (++VRegGapIndex * 1000);
Puyan Lotfid6f73132018-04-05 00:27:15 +0000489
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000490 unsigned I = virtualVRegNumber;
491 const unsigned E = (((I + VR_GAP) / VR_GAP) + 1) * VR_GAP;
Puyan Lotfid6f73132018-04-05 00:27:15 +0000492
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000493 virtualVRegNumber = E;
494 }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000495
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000496 unsigned getVirtualVReg() const { return virtualVRegNumber; }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000497
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000498 unsigned incrementVirtualVReg(unsigned incr = 1) {
499 virtualVRegNumber += incr;
500 return virtualVRegNumber;
501 }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000502
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000503 unsigned createVirtualRegister(const TargetRegisterClass *RC) {
504 std::string S;
505 raw_string_ostream OS(S);
506 OS << "namedVReg" << (virtualVRegNumber & ~0x80000000);
507 OS.flush();
508 virtualVRegNumber++;
Puyan Lotfid6f73132018-04-05 00:27:15 +0000509
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000510 return MRI.createVirtualRegister(RC, OS.str());
511 }
Puyan Lotfid6f73132018-04-05 00:27:15 +0000512};
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000513
514static std::map<unsigned, unsigned>
515GetVRegRenameMap(const std::vector<TypedVReg> &VRegs,
516 const std::vector<unsigned> &renamedInOtherBB,
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000517 MachineRegisterInfo &MRI, NamedVRegCursor &NVC) {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000518 std::map<unsigned, unsigned> VRegRenameMap;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000519 bool FirstCandidate = true;
520
521 for (auto &vreg : VRegs) {
522 if (vreg.isFrameIndex()) {
523 // We skip one vreg for any frame index because there is a good chance
524 // (especially when comparing SelectionDAG to GlobalISel generated MIR)
525 // that in the other file we are just getting an incoming vreg that comes
526 // from a copy from a frame index. So it's safe to skip by one.
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000527 unsigned LastRenameReg = NVC.incrementVirtualVReg();
528 (void)LastRenameReg;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000529 DEBUG(dbgs() << "Skipping rename for FI " << LastRenameReg << "\n";);
530 continue;
531 } else if (vreg.isCandidate()) {
532
533 // After the first candidate, for every subsequent candidate, we skip mod
534 // 10 registers so that the candidates are more likely to start at the
535 // same vreg number making it more likely that the canonical walk from the
536 // candidate insruction. We don't need to skip from the first candidate of
537 // the BasicBlock because we already skip ahead several vregs for each BB.
Puyan Lotfid6f73132018-04-05 00:27:15 +0000538 unsigned LastRenameReg = NVC.getVirtualVReg();
539 if (FirstCandidate)
540 NVC.incrementVirtualVReg(LastRenameReg % 10);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000541 FirstCandidate = false;
542 continue;
543 } else if (!TargetRegisterInfo::isVirtualRegister(vreg.getReg())) {
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000544 unsigned LastRenameReg = NVC.incrementVirtualVReg();
545 (void)LastRenameReg;
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000546 DEBUG({
547 dbgs() << "Skipping rename for Phys Reg " << LastRenameReg << "\n";
548 });
549 continue;
550 }
551
552 auto Reg = vreg.getReg();
553 if (llvm::find(renamedInOtherBB, Reg) != renamedInOtherBB.end()) {
554 DEBUG(dbgs() << "Vreg " << Reg << " already renamed in other BB.\n";);
555 continue;
556 }
557
Puyan Lotfid6f73132018-04-05 00:27:15 +0000558 auto Rename = NVC.createVirtualRegister(MRI.getRegClass(Reg));
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000559
560 if (VRegRenameMap.find(Reg) == VRegRenameMap.end()) {
561 DEBUG(dbgs() << "Mapping vreg ";);
562 if (MRI.reg_begin(Reg) != MRI.reg_end()) {
563 DEBUG(auto foo = &*MRI.reg_begin(Reg); foo->dump(););
564 } else {
565 DEBUG(dbgs() << Reg;);
566 }
567 DEBUG(dbgs() << " to ";);
568 if (MRI.reg_begin(Rename) != MRI.reg_end()) {
569 DEBUG(auto foo = &*MRI.reg_begin(Rename); foo->dump(););
570 } else {
571 DEBUG(dbgs() << Rename;);
572 }
573 DEBUG(dbgs() << "\n";);
574
575 VRegRenameMap.insert(std::pair<unsigned, unsigned>(Reg, Rename));
576 }
577 }
578
579 return VRegRenameMap;
580}
581
582static bool doVRegRenaming(std::vector<unsigned> &RenamedInOtherBB,
583 const std::map<unsigned, unsigned> &VRegRenameMap,
584 MachineRegisterInfo &MRI) {
585 bool Changed = false;
586 for (auto I = VRegRenameMap.begin(), E = VRegRenameMap.end(); I != E; ++I) {
587
588 auto VReg = I->first;
589 auto Rename = I->second;
590
591 RenamedInOtherBB.push_back(Rename);
592
593 std::vector<MachineOperand *> RenameMOs;
594 for (auto &MO : MRI.reg_operands(VReg)) {
595 RenameMOs.push_back(&MO);
596 }
597
598 for (auto *MO : RenameMOs) {
599 Changed = true;
600 MO->setReg(Rename);
601
602 if (!MO->isDef())
603 MO->setIsKill(false);
604 }
605 }
606
607 return Changed;
608}
609
610static bool doDefKillClear(MachineBasicBlock *MBB) {
611 bool Changed = false;
612
613 for (auto &MI : *MBB) {
614 for (auto &MO : MI.operands()) {
615 if (!MO.isReg())
616 continue;
617 if (!MO.isDef() && MO.isKill()) {
618 Changed = true;
619 MO.setIsKill(false);
620 }
621
622 if (MO.isDef() && MO.isDead()) {
623 Changed = true;
624 MO.setIsDead(false);
625 }
626 }
627 }
628
629 return Changed;
630}
631
632static bool runOnBasicBlock(MachineBasicBlock *MBB,
633 std::vector<StringRef> &bbNames,
634 std::vector<unsigned> &renamedInOtherBB,
Puyan Lotfid6f73132018-04-05 00:27:15 +0000635 unsigned &basicBlockNum, unsigned &VRegGapIndex,
636 NamedVRegCursor &NVC) {
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000637
638 if (CanonicalizeBasicBlockNumber != ~0U) {
639 if (CanonicalizeBasicBlockNumber != basicBlockNum++)
640 return false;
641 DEBUG(dbgs() << "\n Canonicalizing BasicBlock " << MBB->getName() << "\n";);
642 }
643
644 if (llvm::find(bbNames, MBB->getName()) != bbNames.end()) {
645 DEBUG({
646 dbgs() << "Found potentially duplicate BasicBlocks: " << MBB->getName()
647 << "\n";
648 });
649 return false;
650 }
651
652 DEBUG({
653 dbgs() << "\n\n NEW BASIC BLOCK: " << MBB->getName() << " \n\n";
654 dbgs() << "\n\n================================================\n\n";
655 });
656
657 bool Changed = false;
658 MachineFunction &MF = *MBB->getParent();
659 MachineRegisterInfo &MRI = MF.getRegInfo();
660
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000661 bbNames.push_back(MBB->getName());
662 DEBUG(dbgs() << "\n\n NEW BASIC BLOCK: " << MBB->getName() << "\n\n";);
663
Puyan Lotfi14b6637e2018-04-16 09:03:03 +0000664 DEBUG(dbgs() << "MBB Before Canonical Copy Propagation:\n"; MBB->dump(););
665 Changed |= propagateLocalCopies(MBB);
666 DEBUG(dbgs() << "MBB After Canonical Copy Propagation:\n"; MBB->dump(););
667
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000668 DEBUG(dbgs() << "MBB Before Scheduling:\n"; MBB->dump(););
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000669 unsigned IdempotentInstCount = 0;
670 Changed |= rescheduleCanonically(IdempotentInstCount, MBB);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000671 DEBUG(dbgs() << "MBB After Scheduling:\n"; MBB->dump(););
672
673 std::vector<MachineInstr *> Candidates = populateCandidates(MBB);
674 std::vector<MachineInstr *> VisitedMIs;
675 std::copy(Candidates.begin(), Candidates.end(),
676 std::back_inserter(VisitedMIs));
677
678 std::vector<TypedVReg> VRegs;
679 for (auto candidate : Candidates) {
680 VRegs.push_back(TypedVReg(RSE_NewCandidate));
681
682 std::queue<TypedVReg> RegQueue;
683
684 // Here we walk the vreg operands of a non-root node along our walk.
685 // The root nodes are the original candidates (stores normally).
686 // These are normally not the root nodes (except for the case of copies to
687 // physical registers).
688 for (unsigned i = 1; i < candidate->getNumOperands(); i++) {
689 if (candidate->mayStore() || candidate->isBranch())
690 break;
691
692 MachineOperand &MO = candidate->getOperand(i);
693 if (!(MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())))
694 continue;
695
696 DEBUG(dbgs() << "Enqueue register"; MO.dump(); dbgs() << "\n";);
697 RegQueue.push(TypedVReg(MO.getReg()));
698 }
699
700 // Here we walk the root candidates. We start from the 0th operand because
701 // the root is normally a store to a vreg.
702 for (unsigned i = 0; i < candidate->getNumOperands(); i++) {
703
704 if (!candidate->mayStore() && !candidate->isBranch())
705 break;
706
707 MachineOperand &MO = candidate->getOperand(i);
708
709 // TODO: Do we want to only add vregs here?
710 if (!MO.isReg() && !MO.isFI())
711 continue;
712
713 DEBUG(dbgs() << "Enqueue Reg/FI"; MO.dump(); dbgs() << "\n";);
714
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000715 RegQueue.push(MO.isReg() ? TypedVReg(MO.getReg())
716 : TypedVReg(RSE_FrameIndex));
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000717 }
718
719 doCandidateWalk(VRegs, RegQueue, VisitedMIs, MBB);
720 }
721
722 // If we have populated no vregs to rename then bail.
723 // The rest of this function does the vreg remaping.
724 if (VRegs.size() == 0)
725 return Changed;
726
Puyan Lotfid6f73132018-04-05 00:27:15 +0000727 auto VRegRenameMap = GetVRegRenameMap(VRegs, renamedInOtherBB, MRI, NVC);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000728 Changed |= doVRegRenaming(renamedInOtherBB, VRegRenameMap, MRI);
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000729
730 // Here we renumber the def vregs for the idempotent instructions from the top
731 // of the MachineBasicBlock so that they are named in the order that we sorted
732 // them alphabetically. Eventually we wont need SkipVRegs because we will use
733 // named vregs instead.
Puyan Lotfid6f73132018-04-05 00:27:15 +0000734 NVC.SkipVRegs();
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000735
736 auto MII = MBB->begin();
737 for (unsigned i = 0; i < IdempotentInstCount && MII != MBB->end(); ++i) {
738 MachineInstr &MI = *MII++;
739 Changed = true;
740 unsigned vRegToRename = MI.getOperand(0).getReg();
Puyan Lotfid6f73132018-04-05 00:27:15 +0000741 auto Rename = NVC.createVirtualRegister(MRI.getRegClass(vRegToRename));
Puyan Lotfi57c4f382018-03-31 05:48:51 +0000742
743 std::vector<MachineOperand *> RenameMOs;
744 for (auto &MO : MRI.reg_operands(vRegToRename)) {
745 RenameMOs.push_back(&MO);
746 }
747
748 for (auto *MO : RenameMOs) {
749 MO->setReg(Rename);
750 }
751 }
752
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000753 Changed |= doDefKillClear(MBB);
754
755 DEBUG(dbgs() << "Updated MachineBasicBlock:\n"; MBB->dump(); dbgs() << "\n";);
756 DEBUG(dbgs() << "\n\n================================================\n\n");
757 return Changed;
758}
759
760bool MIRCanonicalizer::runOnMachineFunction(MachineFunction &MF) {
761
762 static unsigned functionNum = 0;
763 if (CanonicalizeFunctionNumber != ~0U) {
764 if (CanonicalizeFunctionNumber != functionNum++)
765 return false;
766 DEBUG(dbgs() << "\n Canonicalizing Function " << MF.getName() << "\n";);
767 }
768
769 // we need a valid vreg to create a vreg type for skipping all those
770 // stray vreg numbers so reach alignment/canonical vreg values.
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000771 std::vector<MachineBasicBlock *> RPOList = GetRPOList(MF);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000772
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000773 DEBUG(dbgs() << "\n\n NEW MACHINE FUNCTION: " << MF.getName() << " \n\n";
774 dbgs() << "\n\n================================================\n\n";
775 dbgs() << "Total Basic Blocks: " << RPOList.size() << "\n";
776 for (auto MBB
777 : RPOList) { dbgs() << MBB->getName() << "\n"; } dbgs()
778 << "\n\n================================================\n\n";);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000779
780 std::vector<StringRef> BBNames;
781 std::vector<unsigned> RenamedInOtherBB;
782
783 unsigned GapIdx = 0;
784 unsigned BBNum = 0;
785
786 bool Changed = false;
787
Puyan Lotfid6f73132018-04-05 00:27:15 +0000788 MachineRegisterInfo &MRI = MF.getRegInfo();
789 NamedVRegCursor NVC(MRI);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000790 for (auto MBB : RPOList)
Puyan Lotfi6ea89b42018-04-16 08:12:15 +0000791 Changed |=
792 runOnBasicBlock(MBB, BBNames, RenamedInOtherBB, BBNum, GapIdx, NVC);
Puyan Lotfia521c4ac52017-11-02 23:37:32 +0000793
794 return Changed;
795}