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  PREMap;
107  ScopedHTType VNT;
109  unsigned CurrVN = 0;
110 
111  bool PerformTrivialCopyPropagation(MachineInstr *MI,
112  MachineBasicBlock *MBB);
113  bool isPhysDefTriviallyDead(unsigned Reg,
116  bool hasLivePhysRegDefUses(const MachineInstr *MI,
117  const MachineBasicBlock *MBB,
118  SmallSet<unsigned, 8> &PhysRefs,
119  PhysDefVector &PhysDefs, bool &PhysUseDef) const;
120  bool PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
121  SmallSet<unsigned, 8> &PhysRefs,
122  PhysDefVector &PhysDefs, bool &NonLocal) const;
123  bool isCSECandidate(MachineInstr *MI);
124  bool isProfitableToCSE(unsigned CSReg, unsigned Reg,
125  MachineBasicBlock *CSBB, MachineInstr *MI);
126  void EnterScope(MachineBasicBlock *MBB);
127  void ExitScope(MachineBasicBlock *MBB);
128  bool ProcessBlockCSE(MachineBasicBlock *MBB);
129  void ExitScopeIfDone(MachineDomTreeNode *Node,
131  bool PerformCSE(MachineDomTreeNode *Node);
132 
133  bool isPRECandidate(MachineInstr *MI);
134  bool ProcessBlockPRE(MachineDominatorTree *MDT, MachineBasicBlock *MBB);
135  bool PerformSimplePRE(MachineDominatorTree *DT);
136  };
137 
138 } // end anonymous namespace
139 
140 char MachineCSE::ID = 0;
141 
143 
145  "Machine Common Subexpression Elimination", false, false)
149  "Machine Common Subexpression Elimination", false, false)
150 
151 /// The source register of a COPY machine instruction can be propagated to all
152 /// its users, and this propagation could increase the probability of finding
153 /// common subexpressions. If the COPY has only one user, the COPY itself can
154 /// be removed.
155 bool MachineCSE::PerformTrivialCopyPropagation(MachineInstr *MI,
156  MachineBasicBlock *MBB) {
157  bool Changed = false;
158  for (MachineOperand &MO : MI->operands()) {
159  if (!MO.isReg() || !MO.isUse())
160  continue;
161  unsigned Reg = MO.getReg();
163  continue;
164  bool OnlyOneUse = MRI->hasOneNonDBGUse(Reg);
165  MachineInstr *DefMI = MRI->getVRegDef(Reg);
166  if (!DefMI->isCopy())
167  continue;
168  unsigned SrcReg = DefMI->getOperand(1).getReg();
170  continue;
171  if (DefMI->getOperand(0).getSubReg())
172  continue;
173  // FIXME: We should trivially coalesce subregister copies to expose CSE
174  // opportunities on instructions with truncated operands (see
175  // cse-add-with-overflow.ll). This can be done here as follows:
176  // if (SrcSubReg)
177  // RC = TRI->getMatchingSuperRegClass(MRI->getRegClass(SrcReg), RC,
178  // SrcSubReg);
179  // MO.substVirtReg(SrcReg, SrcSubReg, *TRI);
180  //
181  // The 2-addr pass has been updated to handle coalesced subregs. However,
182  // some machine-specific code still can't handle it.
183  // To handle it properly we also need a way find a constrained subregister
184  // class given a super-reg class and subreg index.
185  if (DefMI->getOperand(1).getSubReg())
186  continue;
187  if (!MRI->constrainRegAttrs(SrcReg, Reg))
188  continue;
189  LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
190  LLVM_DEBUG(dbgs() << "*** to: " << *MI);
191 
192  // Update matching debug values.
193  DefMI->changeDebugValuesDefReg(SrcReg);
194 
195  // Propagate SrcReg of copies to MI.
196  MO.setReg(SrcReg);
197  MRI->clearKillFlags(SrcReg);
198  // Coalesce single use copies.
199  if (OnlyOneUse) {
200  DefMI->eraseFromParent();
201  ++NumCoalesces;
202  }
203  Changed = true;
204  }
205 
206  return Changed;
207 }
208 
209 bool
210 MachineCSE::isPhysDefTriviallyDead(unsigned Reg,
213  unsigned LookAheadLeft = LookAheadLimit;
214  while (LookAheadLeft) {
215  // Skip over dbg_value's.
217 
218  if (I == E)
219  // Reached end of block, we don't know if register is dead or not.
220  return false;
221 
222  bool SeenDef = false;
223  for (const MachineOperand &MO : I->operands()) {
224  if (MO.isRegMask() && MO.clobbersPhysReg(Reg))
225  SeenDef = true;
226  if (!MO.isReg() || !MO.getReg())
227  continue;
228  if (!TRI->regsOverlap(MO.getReg(), Reg))
229  continue;
230  if (MO.isUse())
231  // Found a use!
232  return false;
233  SeenDef = true;
234  }
235  if (SeenDef)
236  // See a def of Reg (or an alias) before encountering any use, it's
237  // trivially dead.
238  return true;
239 
240  --LookAheadLeft;
241  ++I;
242  }
243  return false;
244 }
245 
246 static bool isCallerPreservedOrConstPhysReg(unsigned Reg,
247  const MachineFunction &MF,
248  const TargetRegisterInfo &TRI) {
249  // MachineRegisterInfo::isConstantPhysReg directly called by
250  // MachineRegisterInfo::isCallerPreservedOrConstPhysReg expects the
251  // reserved registers to be frozen. That doesn't cause a problem post-ISel as
252  // most (if not all) targets freeze reserved registers right after ISel.
253  //
254  // It does cause issues mid-GlobalISel, however, hence the additional
255  // reservedRegsFrozen check.
256  const MachineRegisterInfo &MRI = MF.getRegInfo();
257  return TRI.isCallerPreservedPhysReg(Reg, MF) ||
258  (MRI.reservedRegsFrozen() && MRI.isConstantPhysReg(Reg));
259 }
260 
261 /// hasLivePhysRegDefUses - Return true if the specified instruction read/write
262 /// physical registers (except for dead defs of physical registers). It also
263 /// returns the physical register def by reference if it's the only one and the
264 /// instruction does not uses a physical register.
265 bool MachineCSE::hasLivePhysRegDefUses(const MachineInstr *MI,
266  const MachineBasicBlock *MBB,
267  SmallSet<unsigned, 8> &PhysRefs,
268  PhysDefVector &PhysDefs,
269  bool &PhysUseDef) const {
270  // First, add all uses to PhysRefs.
271  for (const MachineOperand &MO : MI->operands()) {
272  if (!MO.isReg() || MO.isDef())
273  continue;
274  unsigned Reg = MO.getReg();
275  if (!Reg)
276  continue;
278  continue;
279  // Reading either caller preserved or constant physregs is ok.
280  if (!isCallerPreservedOrConstPhysReg(Reg, *MI->getMF(), *TRI))
281  for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
282  PhysRefs.insert(*AI);
283  }
284 
285  // Next, collect all defs into PhysDefs. If any is already in PhysRefs
286  // (which currently contains only uses), set the PhysUseDef flag.
287  PhysUseDef = false;
288  MachineBasicBlock::const_iterator I = MI; I = std::next(I);
289  for (const auto &MOP : llvm::enumerate(MI->operands())) {
290  const MachineOperand &MO = MOP.value();
291  if (!MO.isReg() || !MO.isDef())
292  continue;
293  unsigned Reg = MO.getReg();
294  if (!Reg)
295  continue;
297  continue;
298  // Check against PhysRefs even if the def is "dead".
299  if (PhysRefs.count(Reg))
300  PhysUseDef = true;
301  // If the def is dead, it's ok. But the def may not marked "dead". That's
302  // common since this pass is run before livevariables. We can scan
303  // forward a few instructions and check if it is obviously dead.
304  if (!MO.isDead() && !isPhysDefTriviallyDead(Reg, I, MBB->end()))
305  PhysDefs.push_back(std::make_pair(MOP.index(), Reg));
306  }
307 
308  // Finally, add all defs to PhysRefs as well.
309  for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i)
310  for (MCRegAliasIterator AI(PhysDefs[i].second, TRI, true); AI.isValid();
311  ++AI)
312  PhysRefs.insert(*AI);
313 
314  return !PhysRefs.empty();
315 }
316 
317 bool MachineCSE::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
318  SmallSet<unsigned, 8> &PhysRefs,
319  PhysDefVector &PhysDefs,
320  bool &NonLocal) const {
321  // For now conservatively returns false if the common subexpression is
322  // not in the same basic block as the given instruction. The only exception
323  // is if the common subexpression is in the sole predecessor block.
324  const MachineBasicBlock *MBB = MI->getParent();
325  const MachineBasicBlock *CSMBB = CSMI->getParent();
326 
327  bool CrossMBB = false;
328  if (CSMBB != MBB) {
329  if (MBB->pred_size() != 1 || *MBB->pred_begin() != CSMBB)
330  return false;
331 
332  for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) {
333  if (MRI->isAllocatable(PhysDefs[i].second) ||
334  MRI->isReserved(PhysDefs[i].second))
335  // Avoid extending live range of physical registers if they are
336  //allocatable or reserved.
337  return false;
338  }
339  CrossMBB = true;
340  }
341  MachineBasicBlock::const_iterator I = CSMI; I = std::next(I);
344  unsigned LookAheadLeft = LookAheadLimit;
345  while (LookAheadLeft) {
346  // Skip over dbg_value's.
347  while (I != E && I != EE && I->isDebugInstr())
348  ++I;
349 
350  if (I == EE) {
351  assert(CrossMBB && "Reaching end-of-MBB without finding MI?");
352  (void)CrossMBB;
353  CrossMBB = false;
354  NonLocal = true;
355  I = MBB->begin();
356  EE = MBB->end();
357  continue;
358  }
359 
360  if (I == E)
361  return true;
362 
363  for (const MachineOperand &MO : I->operands()) {
364  // RegMasks go on instructions like calls that clobber lots of physregs.
365  // Don't attempt to CSE across such an instruction.
366  if (MO.isRegMask())
367  return false;
368  if (!MO.isReg() || !MO.isDef())
369  continue;
370  unsigned MOReg = MO.getReg();
372  continue;
373  if (PhysRefs.count(MOReg))
374  return false;
375  }
376 
377  --LookAheadLeft;
378  ++I;
379  }
380 
381  return false;
382 }
383 
384 bool MachineCSE::isCSECandidate(MachineInstr *MI) {
385  if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() || MI->isKill() ||
386  MI->isInlineAsm() || MI->isDebugInstr())
387  return false;
388 
389  // Ignore copies.
390  if (MI->isCopyLike())
391  return false;
392 
393  // Ignore stuff that we obviously can't move.
394  if (MI->mayStore() || MI->isCall() || MI->isTerminator() ||
396  return false;
397 
398  if (MI->mayLoad()) {
399  // Okay, this instruction does a load. As a refinement, we allow the target
400  // to decide whether the loaded value is actually a constant. If so, we can
401  // actually use it as a load.
402  if (!MI->isDereferenceableInvariantLoad(AA))
403  // FIXME: we should be able to hoist loads with no other side effects if
404  // there are no other instructions which can change memory in this loop.
405  // This is a trivial form of alias analysis.
406  return false;
407  }
408 
409  // Ignore stack guard loads, otherwise the register that holds CSEed value may
410  // be spilled and get loaded back with corrupted data.
411  if (MI->getOpcode() == TargetOpcode::LOAD_STACK_GUARD)
412  return false;
413 
414  return true;
415 }
416 
417 /// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
418 /// common expression that defines Reg. CSBB is basic block where CSReg is
419 /// defined.
420 bool MachineCSE::isProfitableToCSE(unsigned CSReg, unsigned Reg,
421  MachineBasicBlock *CSBB, MachineInstr *MI) {
422  // FIXME: Heuristics that works around the lack the live range splitting.
423 
424  // If CSReg is used at all uses of Reg, CSE should not increase register
425  // pressure of CSReg.
426  bool MayIncreasePressure = true;
429  MayIncreasePressure = false;
431  for (MachineInstr &MI : MRI->use_nodbg_instructions(CSReg)) {
432  CSUses.insert(&MI);
433  }
434  for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
435  if (!CSUses.count(&MI)) {
436  MayIncreasePressure = true;
437  break;
438  }
439  }
440  }
441  if (!MayIncreasePressure) return true;
442 
443  // Heuristics #1: Don't CSE "cheap" computation if the def is not local or in
444  // an immediate predecessor. We don't want to increase register pressure and
445  // end up causing other computation to be spilled.
446  if (TII->isAsCheapAsAMove(*MI)) {
447  MachineBasicBlock *BB = MI->getParent();
448  if (CSBB != BB && !CSBB->isSuccessor(BB))
449  return false;
450  }
451 
452  // Heuristics #2: If the expression doesn't not use a vr and the only use
453  // of the redundant computation are copies, do not cse.
454  bool HasVRegUse = false;
455  for (const MachineOperand &MO : MI->operands()) {
456  if (MO.isReg() && MO.isUse() &&
458  HasVRegUse = true;
459  break;
460  }
461  }
462  if (!HasVRegUse) {
463  bool HasNonCopyUse = false;
464  for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
465  // Ignore copies.
466  if (!MI.isCopyLike()) {
467  HasNonCopyUse = true;
468  break;
469  }
470  }
471  if (!HasNonCopyUse)
472  return false;
473  }
474 
475  // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
476  // it unless the defined value is already used in the BB of the new use.
477  bool HasPHI = false;
478  for (MachineInstr &UseMI : MRI->use_nodbg_instructions(CSReg)) {
479  HasPHI |= UseMI.isPHI();
480  if (UseMI.getParent() == MI->getParent())
481  return true;
482  }
483 
484  return !HasPHI;
485 }
486 
487 void MachineCSE::EnterScope(MachineBasicBlock *MBB) {
488  LLVM_DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
489  ScopeType *Scope = new ScopeType(VNT);
490  ScopeMap[MBB] = Scope;
491 }
492 
493 void MachineCSE::ExitScope(MachineBasicBlock *MBB) {
494  LLVM_DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
496  assert(SI != ScopeMap.end());
497  delete SI->second;
498  ScopeMap.erase(SI);
499 }
500 
501 bool MachineCSE::ProcessBlockCSE(MachineBasicBlock *MBB) {
502  bool Changed = false;
503 
505  SmallVector<unsigned, 2> ImplicitDefsToUpdate;
506  SmallVector<unsigned, 2> ImplicitDefs;
507  for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E; ) {
508  MachineInstr *MI = &*I;
509  ++I;
510 
511  if (!isCSECandidate(MI))
512  continue;
513 
514  bool FoundCSE = VNT.count(MI);
515  if (!FoundCSE) {
516  // Using trivial copy propagation to find more CSE opportunities.
517  if (PerformTrivialCopyPropagation(MI, MBB)) {
518  Changed = true;
519 
520  // After coalescing MI itself may become a copy.
521  if (MI->isCopyLike())
522  continue;
523 
524  // Try again to see if CSE is possible.
525  FoundCSE = VNT.count(MI);
526  }
527  }
528 
529  // Commute commutable instructions.
530  bool Commuted = false;
531  if (!FoundCSE && MI->isCommutable()) {
532  if (MachineInstr *NewMI = TII->commuteInstruction(*MI)) {
533  Commuted = true;
534  FoundCSE = VNT.count(NewMI);
535  if (NewMI != MI) {
536  // New instruction. It doesn't need to be kept.
537  NewMI->eraseFromParent();
538  Changed = true;
539  } else if (!FoundCSE)
540  // MI was changed but it didn't help, commute it back!
541  (void)TII->commuteInstruction(*MI);
542  }
543  }
544 
545  // If the instruction defines physical registers and the values *may* be
546  // used, then it's not safe to replace it with a common subexpression.
547  // It's also not safe if the instruction uses physical registers.
548  bool CrossMBBPhysDef = false;
549  SmallSet<unsigned, 8> PhysRefs;
550  PhysDefVector PhysDefs;
551  bool PhysUseDef = false;
552  if (FoundCSE && hasLivePhysRegDefUses(MI, MBB, PhysRefs,
553  PhysDefs, PhysUseDef)) {
554  FoundCSE = false;
555 
556  // ... Unless the CS is local or is in the sole predecessor block
557  // and it also defines the physical register which is not clobbered
558  // in between and the physical register uses were not clobbered.
559  // This can never be the case if the instruction both uses and
560  // defines the same physical register, which was detected above.
561  if (!PhysUseDef) {
562  unsigned CSVN = VNT.lookup(MI);
563  MachineInstr *CSMI = Exps[CSVN];
564  if (PhysRegDefsReach(CSMI, MI, PhysRefs, PhysDefs, CrossMBBPhysDef))
565  FoundCSE = true;
566  }
567  }
568 
569  if (!FoundCSE) {
570  VNT.insert(MI, CurrVN++);
571  Exps.push_back(MI);
572  continue;
573  }
574 
575  // Found a common subexpression, eliminate it.
576  unsigned CSVN = VNT.lookup(MI);
577  MachineInstr *CSMI = Exps[CSVN];
578  LLVM_DEBUG(dbgs() << "Examining: " << *MI);
579  LLVM_DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
580 
581  // Check if it's profitable to perform this CSE.
582  bool DoCSE = true;
583  unsigned NumDefs = MI->getNumDefs();
584 
585  for (unsigned i = 0, e = MI->getNumOperands(); NumDefs && i != e; ++i) {
586  MachineOperand &MO = MI->getOperand(i);
587  if (!MO.isReg() || !MO.isDef())
588  continue;
589  unsigned OldReg = MO.getReg();
590  unsigned NewReg = CSMI->getOperand(i).getReg();
591 
592  // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
593  // we should make sure it is not dead at CSMI.
594  if (MO.isImplicit() && !MO.isDead() && CSMI->getOperand(i).isDead())
595  ImplicitDefsToUpdate.push_back(i);
596 
597  // Keep track of implicit defs of CSMI and MI, to clear possibly
598  // made-redundant kill flags.
599  if (MO.isImplicit() && !MO.isDead() && OldReg == NewReg)
600  ImplicitDefs.push_back(OldReg);
601 
602  if (OldReg == NewReg) {
603  --NumDefs;
604  continue;
605  }
606 
609  "Do not CSE physical register defs!");
610 
611  if (!isProfitableToCSE(NewReg, OldReg, CSMI->getParent(), MI)) {
612  LLVM_DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
613  DoCSE = false;
614  break;
615  }
616 
617  // Don't perform CSE if the result of the new instruction cannot exist
618  // within the constraints (register class, bank, or low-level type) of
619  // the old instruction.
620  if (!MRI->constrainRegAttrs(NewReg, OldReg)) {
621  LLVM_DEBUG(
622  dbgs() << "*** Not the same register constraints, avoid CSE!\n");
623  DoCSE = false;
624  break;
625  }
626 
627  CSEPairs.push_back(std::make_pair(OldReg, NewReg));
628  --NumDefs;
629  }
630 
631  // Actually perform the elimination.
632  if (DoCSE) {
633  for (std::pair<unsigned, unsigned> &CSEPair : CSEPairs) {
634  unsigned OldReg = CSEPair.first;
635  unsigned NewReg = CSEPair.second;
636  // OldReg may have been unused but is used now, clear the Dead flag
637  MachineInstr *Def = MRI->getUniqueVRegDef(NewReg);
638  assert(Def != nullptr && "CSEd register has no unique definition?");
639  Def->clearRegisterDeads(NewReg);
640  // Replace with NewReg and clear kill flags which may be wrong now.
641  MRI->replaceRegWith(OldReg, NewReg);
642  MRI->clearKillFlags(NewReg);
643  }
644 
645  // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
646  // we should make sure it is not dead at CSMI.
647  for (unsigned ImplicitDefToUpdate : ImplicitDefsToUpdate)
648  CSMI->getOperand(ImplicitDefToUpdate).setIsDead(false);
649  for (auto PhysDef : PhysDefs)
650  if (!MI->getOperand(PhysDef.first).isDead())
651  CSMI->getOperand(PhysDef.first).setIsDead(false);
652 
653  // Go through implicit defs of CSMI and MI, and clear the kill flags on
654  // their uses in all the instructions between CSMI and MI.
655  // We might have made some of the kill flags redundant, consider:
656  // subs ... implicit-def %nzcv <- CSMI
657  // csinc ... implicit killed %nzcv <- this kill flag isn't valid anymore
658  // subs ... implicit-def %nzcv <- MI, to be eliminated
659  // csinc ... implicit killed %nzcv
660  // Since we eliminated MI, and reused a register imp-def'd by CSMI
661  // (here %nzcv), that register, if it was killed before MI, should have
662  // that kill flag removed, because it's lifetime was extended.
663  if (CSMI->getParent() == MI->getParent()) {
664  for (MachineBasicBlock::iterator II = CSMI, IE = MI; II != IE; ++II)
665  for (auto ImplicitDef : ImplicitDefs)
666  if (MachineOperand *MO = II->findRegisterUseOperand(
667  ImplicitDef, /*isKill=*/true, TRI))
668  MO->setIsKill(false);
669  } else {
670  // If the instructions aren't in the same BB, bail out and clear the
671  // kill flag on all uses of the imp-def'd register.
672  for (auto ImplicitDef : ImplicitDefs)
673  MRI->clearKillFlags(ImplicitDef);
674  }
675 
676  if (CrossMBBPhysDef) {
677  // Add physical register defs now coming in from a predecessor to MBB
678  // livein list.
679  while (!PhysDefs.empty()) {
680  auto LiveIn = PhysDefs.pop_back_val();
681  if (!MBB->isLiveIn(LiveIn.second))
682  MBB->addLiveIn(LiveIn.second);
683  }
684  ++NumCrossBBCSEs;
685  }
686 
687  MI->eraseFromParent();
688  ++NumCSEs;
689  if (!PhysRefs.empty())
690  ++NumPhysCSEs;
691  if (Commuted)
692  ++NumCommutes;
693  Changed = true;
694  } else {
695  VNT.insert(MI, CurrVN++);
696  Exps.push_back(MI);
697  }
698  CSEPairs.clear();
699  ImplicitDefsToUpdate.clear();
700  ImplicitDefs.clear();
701  }
702 
703  return Changed;
704 }
705 
706 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
707 /// dominator tree node if its a leaf or all of its children are done. Walk
708 /// up the dominator tree to destroy ancestors which are now done.
709 void
710 MachineCSE::ExitScopeIfDone(MachineDomTreeNode *Node,
712  if (OpenChildren[Node])
713  return;
714 
715  // Pop scope.
716  ExitScope(Node->getBlock());
717 
718  // Now traverse upwards to pop ancestors whose offsprings are all done.
719  while (MachineDomTreeNode *Parent = Node->getIDom()) {
720  unsigned Left = --OpenChildren[Parent];
721  if (Left != 0)
722  break;
723  ExitScope(Parent->getBlock());
724  Node = Parent;
725  }
726 }
727 
728 bool MachineCSE::PerformCSE(MachineDomTreeNode *Node) {
732 
733  CurrVN = 0;
734 
735  // Perform a DFS walk to determine the order of visit.
736  WorkList.push_back(Node);
737  do {
738  Node = WorkList.pop_back_val();
739  Scopes.push_back(Node);
740  const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
741  OpenChildren[Node] = Children.size();
742  for (MachineDomTreeNode *Child : Children)
743  WorkList.push_back(Child);
744  } while (!WorkList.empty());
745 
746  // Now perform CSE.
747  bool Changed = false;
748  for (MachineDomTreeNode *Node : Scopes) {
749  MachineBasicBlock *MBB = Node->getBlock();
750  EnterScope(MBB);
751  Changed |= ProcessBlockCSE(MBB);
752  // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
753  ExitScopeIfDone(Node, OpenChildren);
754  }
755 
756  return Changed;
757 }
758 
759 // We use stronger checks for PRE candidate rather than for CSE ones to embrace
760 // checks inside ProcessBlockCSE(), not only inside isCSECandidate(). This helps
761 // to exclude instrs created by PRE that won't be CSEed later.
762 bool MachineCSE::isPRECandidate(MachineInstr *MI) {
763  if (!isCSECandidate(MI) ||
764  MI->isNotDuplicable() ||
765  MI->mayLoad() ||
766  MI->isAsCheapAsAMove() ||
767  MI->getNumDefs() != 1 ||
768  MI->getNumExplicitDefs() != 1)
769  return false;
770 
771  for (auto def : MI->defs())
772  if (!TRI->isVirtualRegister(def.getReg()))
773  return false;
774 
775  for (auto use : MI->uses())
776  if (use.isReg() && !TRI->isVirtualRegister(use.getReg()))
777  return false;
778 
779  return true;
780 }
781 
782 bool MachineCSE::ProcessBlockPRE(MachineDominatorTree *DT,
783  MachineBasicBlock *MBB) {
784  bool Changed = false;
785  for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;) {
786  MachineInstr *MI = &*I;
787  ++I;
788 
789  if (!isPRECandidate(MI))
790  continue;
791 
792  if (!PREMap.count(MI)) {
793  PREMap[MI] = MBB;
794  continue;
795  }
796 
797  auto MBB1 = PREMap[MI];
798  assert(
799  !DT->properlyDominates(MBB, MBB1) &&
800  "MBB cannot properly dominate MBB1 while DFS through dominators tree!");
801  auto CMBB = DT->findNearestCommonDominator(MBB, MBB1);
802  if (!CMBB->isLegalToHoistInto())
803  continue;
804 
805  // Two instrs are partial redundant if their basic blocks are reachable
806  // from one to another but one doesn't dominate another.
807  if (CMBB != MBB1) {
808  auto BB = MBB->getBasicBlock(), BB1 = MBB1->getBasicBlock();
809  if (BB != nullptr && BB1 != nullptr &&
810  (isPotentiallyReachable(BB1, BB) ||
811  isPotentiallyReachable(BB, BB1))) {
812 
813  assert(MI->getOperand(0).isDef() &&
814  "First operand of instr with one explicit def must be this def");
815  unsigned VReg = MI->getOperand(0).getReg();
816  unsigned NewReg = MRI->cloneVirtualRegister(VReg);
817  if (!isProfitableToCSE(NewReg, VReg, CMBB, MI))
818  continue;
819  MachineInstr &NewMI =
820  TII->duplicate(*CMBB, CMBB->getFirstTerminator(), *MI);
821  NewMI.getOperand(0).setReg(NewReg);
822 
823  PREMap[MI] = CMBB;
824  ++NumPREs;
825  Changed = true;
826  }
827  }
828  }
829  return Changed;
830 }
831 
832 // This simple PRE (partial redundancy elimination) pass doesn't actually
833 // eliminate partial redundancy but transforms it to full redundancy,
834 // anticipating that the next CSE step will eliminate this created redundancy.
835 // If CSE doesn't eliminate this, than created instruction will remain dead
836 // and eliminated later by Remove Dead Machine Instructions pass.
837 bool MachineCSE::PerformSimplePRE(MachineDominatorTree *DT) {
839 
840  PREMap.clear();
841  bool Changed = false;
842  BBs.push_back(DT->getRootNode());
843  do {
844  auto Node = BBs.pop_back_val();
845  const std::vector<MachineDomTreeNode *> &Children = Node->getChildren();
846  for (MachineDomTreeNode *Child : Children)
847  BBs.push_back(Child);
848 
849  MachineBasicBlock *MBB = Node->getBlock();
850  Changed |= ProcessBlockPRE(DT, MBB);
851 
852  } while (!BBs.empty());
853 
854  return Changed;
855 }
856 
857 bool MachineCSE::runOnMachineFunction(MachineFunction &MF) {
858  if (skipFunction(MF.getFunction()))
859  return false;
860 
861  TII = MF.getSubtarget().getInstrInfo();
862  TRI = MF.getSubtarget().getRegisterInfo();
863  MRI = &MF.getRegInfo();
864  AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
865  DT = &getAnalysis<MachineDominatorTree>();
866  LookAheadLimit = TII->getMachineCSELookAheadLimit();
867  bool ChangedPRE, ChangedCSE;
868  ChangedPRE = PerformSimplePRE(DT);
869  ChangedCSE = PerformCSE(DT->getRootNode());
870  return ChangedPRE || ChangedCSE;
871 }
Machine Common Subexpression Elimination
Definition: MachineCSE.cpp:148
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:634
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:493
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:460
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:413
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:650
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:410
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:142
bool mayRaiseFPException() const
Return true if this instruction could possibly raise a floating-point exception.
Definition: MachineInstr.h:841
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:821
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:482
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
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:837
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:255
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:425
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:246
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
Definition: MachineInstr.h:808
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isPosition() const
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:415
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:918
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:860
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:1578
bool isNotDuplicable(QueryType Type=AnyInBundle) const
Return true if this instruction cannot be safely duplicated.
Definition: MachineInstr.h:724
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