LLVM  9.0.0svn
MachineCSE.cpp
Go to the documentation of this file.
1 //===- MachineCSE.cpp - Machine Common Subexpression Elimination Pass -----===//
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 // This pass performs global common subexpression elimination on machine
10 // instructions using a scoped hash table based value numbering scheme. It
11 // must be run while the machine function is still in SSA form.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/CFG.h"
30 #include "llvm/CodeGen/Passes.h"
35 #include "llvm/MC/MCInstrDesc.h"
36 #include "llvm/MC/MCRegisterInfo.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/Allocator.h"
39 #include "llvm/Support/Debug.h"
42 #include <cassert>
43 #include <iterator>
44 #include <utility>
45 #include <vector>
46 
47 using namespace llvm;
48 
49 #define DEBUG_TYPE "machine-cse"
50 
51 STATISTIC(NumCoalesces, "Number of copies coalesced");
52 STATISTIC(NumCSEs, "Number of common subexpression eliminated");
53 STATISTIC(NumPREs, "Number of partial redundant expression"
54  " transformed to fully redundant");
55 STATISTIC(NumPhysCSEs,
56  "Number of physreg referencing common subexpr eliminated");
57 STATISTIC(NumCrossBBCSEs,
58  "Number of cross-MBB physreg referencing CS eliminated");
59 STATISTIC(NumCommutes, "Number of copies coalesced after commuting");
60 
61 namespace {
62 
63  class MachineCSE : public MachineFunctionPass {
64  const TargetInstrInfo *TII;
65  const TargetRegisterInfo *TRI;
66  AliasAnalysis *AA;
69 
70  public:
71  static char ID; // Pass identification
72 
73  MachineCSE() : MachineFunctionPass(ID) {
75  }
76 
77  bool runOnMachineFunction(MachineFunction &MF) override;
78 
79  void getAnalysisUsage(AnalysisUsage &AU) const override {
80  AU.setPreservesCFG();
86  }
87 
88  void releaseMemory() override {
89  ScopeMap.clear();
90  PREMap.clear();
91  Exps.clear();
92  }
93 
94  private:
95  using AllocatorTy = RecyclingAllocator<BumpPtrAllocator,
97  using ScopedHTType =
99  AllocatorTy>;
100  using ScopeType = ScopedHTType::ScopeTy;
101  using PhysDefVector = SmallVector<std::pair<unsigned, unsigned>, 2>;
102 
103  unsigned LookAheadLimit = 0;
106  ScopedHTType VNT;
108  unsigned CurrVN = 0;
109 
110  bool PerformTrivialCopyPropagation(MachineInstr *MI,
111  MachineBasicBlock *MBB);
112  bool isPhysDefTriviallyDead(unsigned Reg,
115  bool hasLivePhysRegDefUses(const MachineInstr *MI,
116  const MachineBasicBlock *MBB,
117  SmallSet<unsigned, 8> &PhysRefs,
118  PhysDefVector &PhysDefs, bool &PhysUseDef) const;
119  bool PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
120  SmallSet<unsigned, 8> &PhysRefs,
121  PhysDefVector &PhysDefs, bool &NonLocal) const;
122  bool isCSECandidate(MachineInstr *MI);
123  bool isProfitableToCSE(unsigned CSReg, unsigned Reg,
124  MachineBasicBlock *CSBB, MachineInstr *MI);
125  void EnterScope(MachineBasicBlock *MBB);
126  void ExitScope(MachineBasicBlock *MBB);
127  bool ProcessBlockCSE(MachineBasicBlock *MBB);
128  void ExitScopeIfDone(MachineDomTreeNode *Node,
130  bool PerformCSE(MachineDomTreeNode *Node);
131 
132  bool isPRECandidate(MachineInstr *MI);
133  bool ProcessBlockPRE(MachineDominatorTree *MDT, MachineBasicBlock *MBB);
134  bool PerformSimplePRE(MachineDominatorTree *DT);
135  };
136 
137 } // end anonymous namespace
138 
139 char MachineCSE::ID = 0;
140 
142 
144  "Machine Common Subexpression Elimination", false, false)
148  "Machine Common Subexpression Elimination", false, false)
149 
150 /// The source register of a COPY machine instruction can be propagated to all
151 /// its users, and this propagation could increase the probability of finding
152 /// common subexpressions. If the COPY has only one user, the COPY itself can
153 /// be removed.
154 bool MachineCSE::PerformTrivialCopyPropagation(MachineInstr *MI,
155  MachineBasicBlock *MBB) {
156  bool Changed = false;
157  for (MachineOperand &MO : MI->operands()) {
158  if (!MO.isReg() || !MO.isUse())
159  continue;
160  unsigned Reg = MO.getReg();
162  continue;
163  bool OnlyOneUse = MRI->hasOneNonDBGUse(Reg);
164  MachineInstr *DefMI = MRI->getVRegDef(Reg);
165  if (!DefMI->isCopy())
166  continue;
167  unsigned SrcReg = DefMI->getOperand(1).getReg();
169  continue;
170  if (DefMI->getOperand(0).getSubReg())
171  continue;
172  // FIXME: We should trivially coalesce subregister copies to expose CSE
173  // opportunities on instructions with truncated operands (see
174  // cse-add-with-overflow.ll). This can be done here as follows:
175  // if (SrcSubReg)
176  // RC = TRI->getMatchingSuperRegClass(MRI->getRegClass(SrcReg), RC,
177  // SrcSubReg);
178  // MO.substVirtReg(SrcReg, SrcSubReg, *TRI);
179  //
180  // The 2-addr pass has been updated to handle coalesced subregs. However,
181  // some machine-specific code still can't handle it.
182  // To handle it properly we also need a way find a constrained subregister
183  // class given a super-reg class and subreg index.
184  if (DefMI->getOperand(1).getSubReg())
185  continue;
186  if (!MRI->constrainRegAttrs(SrcReg, Reg))
187  continue;
188  LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
189  LLVM_DEBUG(dbgs() << "*** to: " << *MI);
190 
191  // Update matching debug values.
192  DefMI->changeDebugValuesDefReg(SrcReg);
193 
194  // Propagate SrcReg of copies to MI.
195  MO.setReg(SrcReg);
196  MRI->clearKillFlags(SrcReg);
197  // Coalesce single use copies.
198  if (OnlyOneUse) {
199  DefMI->eraseFromParent();
200  ++NumCoalesces;
201  }
202  Changed = true;
203  }
204 
205  return Changed;
206 }
207 
208 bool
209 MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
212  unsigned LookAheadLeft = LookAheadLimit;
213  while (LookAheadLeft) {
214  // Skip over dbg_value's.
216 
217  if (I == E)
218  // Reached end of block, we don't know if register is dead or not.
219  return false;
220 
221  bool SeenDef = false;
222  for (const MachineOperand &MO : I->operands()) {
223  if (MO.isRegMask() && MO.clobbersPhysReg(Reg))
224  SeenDef = true;
225  if (!MO.isReg() || !MO.getReg())
226  continue;
227  if (!TRI->regsOverlap(MO.getReg(), Reg))
228  continue;
229  if (MO.isUse())
230  // Found a use!
231  return false;
232  SeenDef = true;
233  }
234  if (SeenDef)
235  // See a def of Reg (or an alias) before encountering any use, it's
236  // trivially dead.
237  return true;
238 
239  --LookAheadLeft;
240  ++I;
241  }
242  return false;
243 }
244 
245 static bool isCallerPreservedOrConstPhysReg(unsigned Reg,
246  const MachineFunction &MF,
247  const TargetRegisterInfo &TRI) {
248  // MachineRegisterInfo::isConstantPhysReg directly called by
249  // MachineRegisterInfo::isCallerPreservedOrConstPhysReg expects the
250  // reserved registers to be frozen. That doesn't cause a problem post-ISel as
251  // most (if not all) targets freeze reserved registers right after ISel.
252  //
253  // It does cause issues mid-GlobalISel, however, hence the additional
254  // reservedRegsFrozen check.
255  const MachineRegisterInfo &MRI = MF.getRegInfo();
256  return TRI.isCallerPreservedPhysReg(Reg, MF) ||
257  (MRI.reservedRegsFrozen() && MRI.isConstantPhysReg(Reg));
258 }
259 
260 /// hasLivePhysRegDefUses - Return true if the specified instruction read/write
261 /// physical registers (except for dead defs of physical registers). It also
262 /// returns the physical register def by reference if it's the only one and the
263 /// instruction does not uses a physical register.
264 bool MachineCSE::hasLivePhysRegDefUses(const MachineInstr *MI,
265  const MachineBasicBlock *MBB,
266  SmallSet<unsigned, 8> &PhysRefs,
267  PhysDefVector &PhysDefs,
268  bool &PhysUseDef) const {
269  // First, add all uses to PhysRefs.
270  for (const MachineOperand &MO : MI->operands()) {
271  if (!MO.isReg() || MO.isDef())
272  continue;
273  unsigned Reg = MO.getReg();
274  if (!Reg)
275  continue;
277  continue;
278  // Reading either caller preserved or constant physregs is ok.
279  if (!isCallerPreservedOrConstPhysReg(Reg, *MI->getMF(), *TRI))
280  for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
281  PhysRefs.insert(*AI);
282  }
283 
284  // Next, collect all defs into PhysDefs. If any is already in PhysRefs
285  // (which currently contains only uses), set the PhysUseDef flag.
286  PhysUseDef = false;
287  MachineBasicBlock::const_iterator I = MI; I = std::next(I);
288  for (const auto &MOP : llvm::enumerate(MI->operands())) {
289  const MachineOperand &MO = MOP.value();
290  if (!MO.isReg() || !MO.isDef())
291  continue;
292  unsigned Reg = MO.getReg();
293  if (!Reg)
294  continue;
296  continue;
297  // Check against PhysRefs even if the def is "dead".
298  if (PhysRefs.count(Reg))
299  PhysUseDef = true;
300  // If the def is dead, it's ok. But the def may not marked "dead". That's
301  // common since this pass is run before livevariables. We can scan
302  // forward a few instructions and check if it is obviously dead.
303  if (!MO.isDead() && !isPhysDefTriviallyDead(Reg, I, MBB->end()))
304  PhysDefs.push_back(std::make_pair(MOP.index(), Reg));
305  }
306 
307  // Finally, add all defs to PhysRefs as well.
308  for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i)
309  for (MCRegAliasIterator AI(PhysDefs[i].second, TRI, true); AI.isValid();
310  ++AI)
311  PhysRefs.insert(*AI);
312 
313  return !PhysRefs.empty();
314 }
315 
316 bool MachineCSE::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
317  SmallSet<unsigned, 8> &PhysRefs,
318  PhysDefVector &PhysDefs,
319  bool &NonLocal) const {
320  // For now conservatively returns false if the common subexpression is
321  // not in the same basic block as the given instruction. The only exception
322  // is if the common subexpression is in the sole predecessor block.
323  const MachineBasicBlock *MBB = MI->getParent();
324  const MachineBasicBlock *CSMBB = CSMI->getParent();
325 
326  bool CrossMBB = false;
327  if (CSMBB != MBB) {
328  if (MBB->pred_size() != 1 || *MBB->pred_begin() != CSMBB)
329  return false;
330 
331  for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) {
332  if (MRI->isAllocatable(PhysDefs[i].second) ||
333  MRI->isReserved(PhysDefs[i].second))
334  // Avoid extending live range of physical registers if they are
335  //allocatable or reserved.
336  return false;
337  }
338  CrossMBB = true;
339  }
340  MachineBasicBlock::const_iterator I = CSMI; I = std::next(I);
343  unsigned LookAheadLeft = LookAheadLimit;
344  while (LookAheadLeft) {
345  // Skip over dbg_value's.
346  while (I != E && I != EE && I->isDebugInstr())
347  ++I;
348 
349  if (I == EE) {
350  assert(CrossMBB && "Reaching end-of-MBB without finding MI?");
351  (void)CrossMBB;
352  CrossMBB = false;
353  NonLocal = true;
354  I = MBB->begin();
355  EE = MBB->end();
356  continue;
357  }
358 
359  if (I == E)
360  return true;
361 
362  for (const MachineOperand &MO : I->operands()) {
363  // RegMasks go on instructions like calls that clobber lots of physregs.
364  // Don't attempt to CSE across such an instruction.
365  if (MO.isRegMask())
366  return false;
367  if (!MO.isReg() || !MO.isDef())
368  continue;
369  unsigned MOReg = MO.getReg();
371  continue;
372  if (PhysRefs.count(MOReg))
373  return false;
374  }
375 
376  --LookAheadLeft;
377  ++I;
378  }
379 
380  return false;
381 }
382 
383 bool MachineCSE::isCSECandidate(MachineInstr *MI) {
384  if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() || MI->isKill() ||
385  MI->isInlineAsm() || MI->isDebugInstr())
386  return false;
387 
388  // Ignore copies.
389  if (MI->isCopyLike())
390  return false;
391 
392  // Ignore stuff that we obviously can't move.
393  if (MI->mayStore() || MI->isCall() || MI->isTerminator() ||
395  return false;
396 
397  if (MI->mayLoad()) {
398  // Okay, this instruction does a load. As a refinement, we allow the target
399  // to decide whether the loaded value is actually a constant. If so, we can
400  // actually use it as a load.
401  if (!MI->isDereferenceableInvariantLoad(AA))
402  // FIXME: we should be able to hoist loads with no other side effects if
403  // there are no other instructions which can change memory in this loop.
404  // This is a trivial form of alias analysis.
405  return false;
406  }
407 
408  // Ignore stack guard loads, otherwise the register that holds CSEed value may
409  // be spilled and get loaded back with corrupted data.
410  if (MI->getOpcode() == TargetOpcode::LOAD_STACK_GUARD)
411  return false;
412 
413  return true;
414 }
415 
416 /// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
417 /// common expression that defines Reg. CSBB is basic block where CSReg is
418 /// defined.
419 bool MachineCSE::isProfitableToCSE(unsigned CSReg, unsigned Reg,
420  MachineBasicBlock *CSBB, MachineInstr *MI) {
421  // FIXME: Heuristics that works around the lack the live range splitting.
422 
423  // If CSReg is used at all uses of Reg, CSE should not increase register
424  // pressure of CSReg.
425  bool MayIncreasePressure = true;
428  MayIncreasePressure = false;
430  for (MachineInstr &MI : MRI->use_nodbg_instructions(CSReg)) {
431  CSUses.insert(&MI);
432  }
433  for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
434  if (!CSUses.count(&MI)) {
435  MayIncreasePressure = true;
436  break;
437  }
438  }
439  }
440  if (!MayIncreasePressure) return true;
441 
442  // Heuristics #1: Don't CSE "cheap" computation if the def is not local or in
443  // an immediate predecessor. We don't want to increase register pressure and
444  // end up causing other computation to be spilled.
445  if (TII->isAsCheapAsAMove(*MI)) {
446  MachineBasicBlock *BB = MI->getParent();
447  if (CSBB != BB && !CSBB->isSuccessor(BB))
448  return false;
449  }
450 
451  // Heuristics #2: If the expression doesn't not use a vr and the only use
452  // of the redundant computation are copies, do not cse.
453  bool HasVRegUse = false;
454  for (const MachineOperand &MO : MI->operands()) {
455  if (MO.isReg() && MO.isUse() &&
457  HasVRegUse = true;
458  break;
459  }
460  }
461  if (!HasVRegUse) {
462  bool HasNonCopyUse = false;
463  for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
464  // Ignore copies.
465  if (!MI.isCopyLike()) {
466  HasNonCopyUse = true;
467  break;
468  }
469  }
470  if (!HasNonCopyUse)
471  return false;
472  }
473 
474  // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
475  // it unless the defined value is already used in the BB of the new use.
476  bool HasPHI = false;
477  for (MachineInstr &UseMI : MRI->use_nodbg_instructions(CSReg)) {
478  HasPHI |= UseMI.isPHI();
479  if (UseMI.getParent() == MI->getParent())
480  return true;
481  }
482 
483  return !HasPHI;
484 }
485 
486 void MachineCSE::EnterScope(MachineBasicBlock *MBB) {
487  LLVM_DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
488  ScopeType *Scope = new ScopeType(VNT);
489  ScopeMap[MBB] = Scope;
490 }
491 
492 void MachineCSE::ExitScope(MachineBasicBlock *MBB) {
493  LLVM_DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
495  assert(SI != ScopeMap.end());
496  delete SI->second;
497  ScopeMap.erase(SI);
498 }
499 
500 bool MachineCSE::ProcessBlockCSE(MachineBasicBlock *MBB) {
501  bool Changed = false;
502 
504  SmallVector<unsigned, 2> ImplicitDefsToUpdate;
505  SmallVector<unsigned, 2> ImplicitDefs;
506  for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
507  MachineInstr *MI = &*I;
508  ++I;
509 
510  if (!isCSECandidate(MI))
511  continue;
512 
513  bool FoundCSE = VNT.count(MI);
514  if (!FoundCSE) {
515  // Using trivial copy propagation to find more CSE opportunities.
516  if (PerformTrivialCopyPropagation(MI, MBB)) {
517  Changed = true;
518 
519  // After coalescing MI itself may become a copy.
520  if (MI->isCopyLike())
521  continue;
522 
523  // Try again to see if CSE is possible.
524  FoundCSE = VNT.count(MI);
525  }
526  }
527 
528  // Commute commutable instructions.
529  bool Commuted = false;
530  if (!FoundCSE && MI->isCommutable()) {
531  if (MachineInstr *NewMI = TII->commuteInstruction(*MI)) {
532  Commuted = true;
533  FoundCSE = VNT.count(NewMI);
534  if (NewMI != MI) {
535  // New instruction. It doesn't need to be kept.
536  NewMI->eraseFromParent();
537  Changed = true;
538  } else if (!FoundCSE)
539  // MI was changed but it didn't help, commute it back!
540  (void)TII->commuteInstruction(*MI);
541  }
542  }
543 
544  // If the instruction defines physical registers and the values *may* be
545  // used, then it's not safe to replace it with a common subexpression.
546  // It's also not safe if the instruction uses physical registers.
547  bool CrossMBBPhysDef = false;
548  SmallSet<unsigned, 8> PhysRefs;
549  PhysDefVector PhysDefs;
550  bool PhysUseDef = false;
551  if (FoundCSE && hasLivePhysRegDefUses(MI, MBB, PhysRefs,
552  PhysDefs, PhysUseDef)) {
553  FoundCSE = false;
554 
555  // ... Unless the CS is local or is in the sole predecessor block
556  // and it also defines the physical register which is not clobbered
557  // in between and the physical register uses were not clobbered.
558  // This can never be the case if the instruction both uses and
559  // defines the same physical register, which was detected above.
560  if (!PhysUseDef) {
561  unsigned CSVN = VNT.lookup(MI);
562  MachineInstr *CSMI = Exps[CSVN];
563  if (PhysRegDefsReach(CSMI, MI, PhysRefs, PhysDefs, CrossMBBPhysDef))
564  FoundCSE = true;
565  }
566  }
567 
568  if (!FoundCSE) {
569  VNT.insert(MI, CurrVN++);
570  Exps.push_back(MI);
571  continue;
572  }
573 
574  // Found a common subexpression, eliminate it.
575  unsigned CSVN = VNT.lookup(MI);
576  MachineInstr *CSMI = Exps[CSVN];
577  LLVM_DEBUG(dbgs() << "Examining: " << *MI);
578  LLVM_DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
579 
580  // Check if it's profitable to perform this CSE.
581  bool DoCSE = true;
582  unsigned NumDefs = MI->getNumDefs();
583 
584  for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
585  MachineOperand &MO = MI->getOperand(i);
586  if (!MO.isReg() || !MO.isDef())
587  continue;
588  unsigned OldReg = MO.getReg();
589  unsigned NewReg = CSMI->getOperand(i).getReg();
590 
591  // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
592  // we should make sure it is not dead at CSMI.
593  if (MO.isImplicit() && !MO.isDead() && CSMI->getOperand(i).isDead())
594  ImplicitDefsToUpdate.push_back(i);
595 
596  // Keep track of implicit defs of CSMI and MI, to clear possibly
597  // made-redundant kill flags.
598  if (MO.isImplicit() && !MO.isDead() && OldReg == NewReg)
599  ImplicitDefs.push_back(OldReg);
600 
601  if (OldReg == NewReg) {
602  --NumDefs;
603  continue;
604  }
605 
608  "Do not CSE physical register defs!");
609 
610  if (!isProfitableToCSE(NewReg, OldReg, CSMI->getParent(), MI)) {
611  LLVM_DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
612  DoCSE = false;
613  break;
614  }
615 
616  // Don't perform CSE if the result of the new instruction cannot exist
617  // within the constraints (register class, bank, or low-level type) of
618  // the old instruction.
619  if (!MRI->constrainRegAttrs(NewReg, OldReg)) {
620  LLVM_DEBUG(
621  dbgs() << "*** Not the same register constraints, avoid CSE!\n");
622  DoCSE = false;
623  break;
624  }
625 
626  CSEPairs.push_back(std::make_pair(OldReg, NewReg));
627  --NumDefs;
628  }
629 
630  // Actually perform the elimination.
631  if (DoCSE) {
632  for (std::pair<unsigned, unsigned> &CSEPair : CSEPairs) {
633  unsigned OldReg = CSEPair.first;
634  unsigned NewReg = CSEPair.second;
635  // OldReg may have been unused but is used now, clear the Dead flag
636  MachineInstr *Def = MRI->getUniqueVRegDef(NewReg);
637  assert(Def != nullptr && "CSEd register has no unique definition?");
638  Def->clearRegisterDeads(NewReg);
639  // Replace with NewReg and clear kill flags which may be wrong now.
640  MRI->replaceRegWith(OldReg, NewReg);
641  MRI->clearKillFlags(NewReg);
642  }
643 
644  // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
645  // we should make sure it is not dead at CSMI.
646  for (unsigned ImplicitDefToUpdate : ImplicitDefsToUpdate)
647  CSMI->getOperand(ImplicitDefToUpdate).setIsDead(false);
648  for (auto PhysDef : PhysDefs)
649  if (!MI->getOperand(PhysDef.first).isDead())
650  CSMI->getOperand(PhysDef.first).setIsDead(false);
651 
652  // Go through implicit defs of CSMI and MI, and clear the kill flags on
653  // their uses in all the instructions between CSMI and MI.
654  // We might have made some of the kill flags redundant, consider:
655  // subs ... implicit-def %nzcv <- CSMI
656  // csinc ... implicit killed %nzcv <- this kill flag isn't valid anymore
657  // subs ... implicit-def %nzcv <- MI, to be eliminated
658  // csinc ... implicit killed %nzcv
659  // Since we eliminated MI, and reused a register imp-def'd by CSMI
660  // (here %nzcv), that register, if it was killed before MI, should have
661  // that kill flag removed, because it's lifetime was extended.
662  if (CSMI->getParent() == MI->getParent()) {
663  for (MachineBasicBlock::iterator II = CSMI, IE = MI; II != IE; ++II)
664  for (auto ImplicitDef : ImplicitDefs)
665  if (MachineOperand *MO = II->findRegisterUseOperand(
666  ImplicitDef, /*isKill=*/true, TRI))
667  MO->setIsKill(false);
668  } else {
669  // If the instructions aren't in the same BB, bail out and clear the
670  // kill flag on all uses of the imp-def'd register.
671  for (auto ImplicitDef : ImplicitDefs)
672  MRI->clearKillFlags(ImplicitDef);
673  }
674 
675  if (CrossMBBPhysDef) {
676  // Add physical register defs now coming in from a predecessor to MBB
677  // livein list.
678  while (!PhysDefs.empty()) {
679  auto LiveIn = PhysDefs.pop_back_val();
680  if (!MBB->isLiveIn(LiveIn.second))
681  MBB->addLiveIn(LiveIn.second);
682  }
683  ++NumCrossBBCSEs;
684  }
685 
686  MI->eraseFromParent();
687  ++NumCSEs;
688  if (!PhysRefs.empty())
689  ++NumPhysCSEs;
690  if (Commuted)
691  ++NumCommutes;
692  Changed = true;
693  } else {
694  VNT.insert(MI, CurrVN++);
695  Exps.push_back(MI);
696  }
697  CSEPairs.clear();
698  ImplicitDefsToUpdate.clear();
699  ImplicitDefs.clear();
700  }
701 
702  return Changed;
703 }
704 
705 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
706 /// dominator tree node if its a leaf or all of its children are done. Walk
707 /// up the dominator tree to destroy ancestors which are now done.
708 void
709 MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
711  if (OpenChildren[Node])
712  return;
713 
714  // Pop scope.
715  ExitScope(Node->getBlock());
716 
717  // Now traverse upwards to pop ancestors whose offsprings are all done.
718  while (MachineDomTreeNode *Parent = Node->getIDom()) {
719  unsigned Left = --OpenChildren[Parent];
720  if (Left != 0)
721  break;
722  ExitScope(Parent->getBlock());
723  Node = Parent;
724  }
725 }
726 
727 bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
731 
732  CurrVN = 0;
733 
734  // Perform a DFS walk to determine the order of visit.
735  WorkList.push_back(Node);
736  do {
737  Node = WorkList.pop_back_val();
738  Scopes.push_back(Node);
739  const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
740  OpenChildren[Node] = Children.size();
741  for (MachineDomTreeNode *Child : Children)
742  WorkList.push_back(Child);
743  } while (!WorkList.empty());
744 
745  // Now perform CSE.
746  bool Changed = false;
747  for (MachineDomTreeNode *Node : Scopes) {
748  MachineBasicBlock *MBB = Node->getBlock();
749  EnterScope(MBB);
750  Changed |= ProcessBlockCSE(MBB);
751  // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
752  ExitScopeIfDone(Node, OpenChildren);
753  }
754 
755  return Changed;
756 }
757 
758 // We use stronger checks for PRE candidate rather than for CSE ones to embrace
759 // checks inside ProcessBlockCSE(), not only inside isCSECandidate(). This helps
760 // to exclude instrs created by PRE that won't be CSEed later.
761 bool MachineCSE::isPRECandidate(MachineInstr *MI) {
762  if (!isCSECandidate(MI) ||
763  MI->isNotDuplicable() ||
764  MI->isAsCheapAsAMove() ||
765  MI->getNumDefs() != 1 ||
766  MI->getNumExplicitDefs() != 1)
767  return false;
768 
769  for (auto def: MI->defs())
770  if (!TRI->isVirtualRegister(def.getReg()))
771  return false;
772 
773  for (auto use: MI->uses())
774  if (use.isReg() && !TRI->isVirtualRegister(use.getReg()))
775  return false;
776 
777  return true;
778 }
779 
780 bool MachineCSE::ProcessBlockPRE(MachineDominatorTree *DT, MachineBasicBlock *MBB) {
781  bool Changed = false;
782  for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
783  MachineInstr *MI = &*I;
784  ++I;
785 
786  if (!isPRECandidate(MI))
787  continue;
788 
789  if (!PREMap.count(MI)) {
790  PREMap[MI] = MBB;
791  continue;
792  }
793 
794  auto MBB1 = PREMap[MI];
795  assert(!DT->properlyDominates(MBB, MBB1) &&
796  "MBB cannot properly dominate MBB1 while DFS through dominators tree!");
797  auto CMBB = DT->findNearestCommonDominator(MBB, MBB1);
798 
799  // Two instrs are partial redundant if their basic blocks are reachable
800  // from one to another but one doesn't dominate another.
801  if (CMBB != MBB1) {
802  auto BB = MBB->getBasicBlock(), BB1 = MBB1->getBasicBlock();
803  if (BB != nullptr && BB1 != nullptr &&
804  (isPotentiallyReachable(BB1, BB) ||
805  isPotentiallyReachable(BB, BB1))) {
806 
807  assert(MI->getOperand(0).isDef() &&
808  "First operand of instr with one explicit def must be this def");
809  unsigned VReg = MI->getOperand(0).getReg();
810  unsigned NewReg = MRI->cloneVirtualRegister(VReg);
811  if (!isProfitableToCSE(NewReg, VReg, CMBB, MI))
812  continue;
813  MachineInstr &NewMI = TII->duplicate(*CMBB, CMBB->getFirstTerminator(), *MI);
814  NewMI.getOperand(0).setReg(NewReg);
815 
816  PREMap[MI] = CMBB;
817  ++NumPREs;
818  Changed = true;
819  }
820  }
821  }
822  return Changed;
823 }
824 
825 // This simple PRE (partial redundancy elimination) pass doesn't actually
826 // eliminate partial redundancy but transforms it to full redundancy,
827 // anticipating that the next CSE step will eliminate this created redundancy.
828 // If CSE doesn't eliminate this, than created instruction will remain dead
829 // and eliminated later by Remove Dead Machine Instructions pass.
830 bool MachineCSE::PerformSimplePRE(MachineDominatorTree *DT) {
832 
833  PREMap.clear();
834  bool Changed = false;
835  BBs.push_back(DT->getRootNode());
836  do {
837  auto Node = BBs.pop_back_val();
838  const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
839  for (MachineDomTreeNode *Child : Children)
840  BBs.push_back(Child);
841 
842  MachineBasicBlock *MBB = Node->getBlock();
843  Changed |= ProcessBlockPRE(DT, MBB);
844 
845  } while (!BBs.empty());
846 
847  return Changed;
848 }
849 
850 bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
851  if (skipFunction(MF.getFunction()))
852  return false;
853 
854  TII = MF.getSubtarget().getInstrInfo();
855  TRI = MF.getSubtarget().getRegisterInfo();
856  MRI = &MF.getRegInfo();
857  AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
858  DT = &getAnalysis<MachineDominatorTree>();
859  LookAheadLimit = TII->getMachineCSELookAheadLimit();
860  bool ChangedPRE, ChangedCSE;
861  ChangedPRE = PerformSimplePRE(DT);
862  ChangedCSE = PerformCSE(DT->getRootNode());
863  return ChangedPRE || ChangedCSE;
864 }
Machine Common Subexpression Elimination
Definition: MachineCSE.cpp:147
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
bool isCall(QueryType Type=AnyInBundle) const
Definition: MachineInstr.h:632
bool isAllocatable(unsigned PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn&#39;t been...
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
iterator_range< mop_iterator > uses()
Returns a range that includes all operands that are register uses.
Definition: MachineInstr.h:491
bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const SmallPtrSetImpl< BasicBlock *> *ExclusionSet=nullptr, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr)
Determine whether instruction &#39;To&#39; is reachable from &#39;From&#39;, without passing through any blocks in Ex...
Definition: CFG.cpp:211
INITIALIZE_PASS_BEGIN(MachineCSE, DEBUG_TYPE, "Machine Common Subexpression Elimination", false, false) INITIALIZE_PASS_END(MachineCSE
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
void push_back(const T &Elt)
Definition: SmallVector.h:211
void initializeMachineCSEPass(PassRegistry &)
unsigned getReg() const
getReg - Returns the register number.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
#define DEBUG_TYPE
Definition: MachineCSE.cpp:49
unsigned Reg
virtual MachineInstr & duplicate(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) const
Clones instruction or the whole instruction bundle Orig and insert into MBB before InsertBefore...
MachineInstr * commuteInstruction(MachineInstr &MI, bool NewMI=false, unsigned OpIdx1=CommuteAnyOperandIndex, unsigned OpIdx2=CommuteAnyOperandIndex) const
This method commutes the operands of the given machine instruction MI.
unsigned getSubReg() const
bool isInlineAsm() const
bool constrainRegAttrs(unsigned Reg, unsigned ConstrainingReg, unsigned MinNumRegs=0)
Constrain the register class or the register bank of the virtual register Reg (and low-level type) to...
unsigned second
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
void setIsDead(bool Val=true)
bool reservedRegsFrozen() const
reservedRegsFrozen - Returns true after freezeReservedRegs() was called to ensure the set of reserved...
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:458
bool isCopyLike() const
Return true if the instruction behaves like a copy.
bool isPHI() const
Special DenseMapInfo traits to compare MachineInstr* by value of the instruction rather than by point...
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
virtual unsigned getMachineCSELookAheadLimit() const
Return the value to use for the MachineCSE&#39;s LookAheadLimit, which is a heuristic used for CSE&#39;ing ph...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
LLVM_NODISCARD bool empty() const
Definition: SmallSet.h:155
char & MachineLoopInfoID
MachineLoopInfo - This pass is a loop analysis pass.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:411
void eraseFromParent()
Unlink &#39;this&#39; from the containing basic block and delete it.
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
Definition: MachineInstr.h:648
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:408
RecyclingAllocator - This class wraps an Allocator, adding the functionality of recycling deleted obj...
MachineInstr * getVRegDef(unsigned Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
char & MachineCSEID
MachineCSE - This pass performs global CSE on machine instructions.
Definition: MachineCSE.cpp:141
void clearKillFlags(unsigned Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
void changeDebugValuesDefReg(unsigned Reg)
Find all DBG_VALUEs immediately following this instruction that point to a register def in this instr...
Base class for the actual dominator tree node.
const std::vector< DomTreeNodeBase * > & getChildren() const
AnalysisUsage & addPreservedID(const void *ID)
COFF::MachineTypes Machine
Definition: COFFYAML.cpp:365
virtual const TargetInstrInfo * getInstrInfo() const
MachineBasicBlock * findNearestCommonDominator(MachineBasicBlock *A, MachineBasicBlock *B)
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
bool isDereferenceableInvariantLoad(AliasAnalysis *AA) const
Return true if this load instruction never traps and points to a memory location whose value doesn&#39;t ...
TargetInstrInfo - Interface to description of machine instruction set.
BumpPtrAllocatorImpl BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition: Allocator.h:434
NodeT * getBlock() const
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
Definition: MachineInstr.h:819
void addLiveIn(MCPhysReg PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
unsigned const MachineRegisterInfo * MRI
StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
void clearRegisterDeads(unsigned Reg)
Clear all dead flags on operands defining register Reg.
MachineInstrBuilder & UseMI
DomTreeNodeBase * getIDom() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
MCRegAliasIterator enumerates all registers aliasing Reg.
Represent the analysis usage information of a pass.
iterator_range< mop_iterator > defs()
Returns a range over all explicit operands that are register definitions.
Definition: MachineInstr.h:480
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn&#39;t already there.
Definition: SmallSet.h:180
bool isCopy() const
bool isImplicitDef() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool isDebugInstr() const
Definition: MachineInstr.h:998
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
bool isConstantPhysReg(unsigned PhysReg) const
Returns true if PhysReg is unallocatable and constant throughout the function.
virtual bool isAsCheapAsAMove(const MachineInstr &MI) const
Return true if the instruction is as cheap as a move instruction.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
bool regsOverlap(unsigned regA, unsigned regB) const
Returns true if the two registers are equal or alias each other.
MachineDomTreeNode * getRootNode() const
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
MachineInstrBuilder MachineInstrBuilder & DefMI
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:374
bool properlyDominates(const MachineDomTreeNode *A, const MachineDomTreeNode *B) const
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:301
unsigned pred_size() const
MachineInstr * getUniqueVRegDef(unsigned Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
const Function & getFunction() const
Return the LLVM function that this machine code represents.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
bool isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
unsigned cloneVirtualRegister(unsigned VReg, StringRef Name="")
Create and return a new virtual register in the function with the same attributes as the given regist...
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
IterT skipDebugInstructionsForward(IterT It, IterT End)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator...
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:253
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
Definition: MachineInstr.h:63
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
void setReg(unsigned Reg)
Change the register this operand corresponds to.
#define I(x, y, z)
Definition: MD5.cpp:58
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
unsigned getNumDefs() const
Returns the total number of definitions.
Definition: MachineInstr.h:423
virtual bool isCallerPreservedPhysReg(unsigned PhysReg, const MachineFunction &MF) const
Physical registers that may be modified within a function but are guaranteed to be restored before an...
bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
pgo instr use
bool hasOneNonDBGUse(unsigned RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug instruction using the specified regis...
bool isKill() const
unsigned getNumExplicitDefs() const
Returns the number of non-implicit definitions.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
static bool isCallerPreservedOrConstPhysReg(unsigned Reg, const MachineFunction &MF, const TargetRegisterInfo &TRI)
Definition: MachineCSE.cpp:245
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
Definition: MachineInstr.h:806
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isPosition() const
Definition: MachineInstr.h:994
bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore...
IRTranslator LLVM IR MI
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
#define LLVM_DEBUG(X)
Definition: Debug.h:122
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:413
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(unsigned Reg) const
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool isAsCheapAsAMove(QueryType Type=AllInBundle) const
Returns true if this instruction has the same cost (or less) than a move instruction.
Definition: MachineInstr.h:905
bool isCommutable(QueryType Type=IgnoreBundle) const
Return true if this may be a 2- or 3-address instruction (of the form "X = op Y, Z, ..."), which produces the same result if Y and Z are exchanged.
Definition: MachineInstr.h:847
bool isReserved(unsigned PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
detail::enumerator< R > enumerate(R &&TheRange)
Given an input range, returns a new range whose values are are pair (A,B) such that A is the 0-based ...
Definition: STLExtras.h:1571
bool isNotDuplicable(QueryType Type=AnyInBundle) const
Return true if this instruction cannot be safely duplicated.
Definition: MachineInstr.h:722
bool isImplicit() const
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:164