LLVM 24.0.0git
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
16#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/CFG.h"
32#include "llvm/CodeGen/Passes.h"
38#include "llvm/MC/MCRegister.h"
40#include "llvm/Pass.h"
42#include "llvm/Support/Debug.h"
45#include <cassert>
46#include <iterator>
47#include <utility>
48
49using namespace llvm;
50
51#define DEBUG_TYPE "machine-cse"
52
53STATISTIC(NumCoalesces, "Number of copies coalesced");
54STATISTIC(NumCSEs, "Number of common subexpression eliminated");
55STATISTIC(NumPREs, "Number of partial redundant expression"
56 " transformed to fully redundant");
57STATISTIC(NumPhysCSEs,
58 "Number of physreg referencing common subexpr eliminated");
59STATISTIC(NumCrossBBCSEs,
60 "Number of cross-MBB physreg referencing CS eliminated");
61STATISTIC(NumCommutes, "Number of copies coalesced after commuting");
62
63// Threshold to avoid excessive cost to compute isProfitableToCSE.
64static cl::opt<int>
65 CSUsesThreshold("csuses-threshold", cl::Hidden, cl::init(1024),
66 cl::desc("Threshold for the size of CSUses"));
67
69 "aggressive-machine-cse", cl::Hidden, cl::init(false),
70 cl::desc("Override the profitability heuristics for Machine CSE"));
71
72namespace {
73
74class MachineCSEImpl {
75 const TargetInstrInfo *TII = nullptr;
76 const TargetRegisterInfo *TRI = nullptr;
77 MachineDominatorTree *DT = nullptr;
78 MachineRegisterInfo *MRI = nullptr;
79 MachineBlockFrequencyInfo *MBFI = nullptr;
80
81public:
82 MachineCSEImpl(MachineDominatorTree *DT, MachineBlockFrequencyInfo *MBFI)
83 : DT(DT), MBFI(MBFI) {}
84 bool run(MachineFunction &MF);
85
86private:
87 using AllocatorTy =
88 RecyclingAllocator<BumpPtrAllocator,
89 ScopedHashTableVal<MachineInstr *, unsigned>>;
90 using ScopedHTType =
91 ScopedHashTable<MachineInstr *, unsigned, MachineInstrExpressionTrait,
92 AllocatorTy>;
93 using ScopeType = ScopedHTType::ScopeTy;
94 using PhysDefVector = SmallVector<std::pair<unsigned, Register>, 2>;
95
96 unsigned LookAheadLimit = 0;
97 DenseMap<MachineBasicBlock *, ScopeType *> ScopeMap;
98 DenseMap<MachineInstr *, MachineBasicBlock *, MachineInstrExpressionTrait>
99 PREMap;
100 ScopedHTType VNT;
102 unsigned CurrVN = 0;
103
104 bool PerformTrivialCopyPropagation(MachineInstr *MI, MachineBasicBlock *MBB);
105 bool isPhysDefTriviallyDead(MCRegister Reg,
108 bool hasLivePhysRegDefUses(const MachineInstr *MI,
109 const MachineBasicBlock *MBB,
110 SmallSet<MCRegister, 8> &PhysRefs,
111 PhysDefVector &PhysDefs, bool &PhysUseDef) const;
112 bool PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
113 const SmallSet<MCRegister, 8> &PhysRefs,
114 const PhysDefVector &PhysDefs, bool &NonLocal) const;
115 bool isCSECandidate(MachineInstr *MI);
116 bool isProfitableToCSE(Register CSReg, Register Reg, MachineBasicBlock *CSBB,
117 MachineInstr *MI);
118 void EnterScope(MachineBasicBlock *MBB);
119 void ExitScope(MachineBasicBlock *MBB);
120 bool ProcessBlockCSE(MachineBasicBlock *MBB);
121 void ExitScopeIfDone(MachineDomTreeNode *Node,
122 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren);
123 bool PerformCSE(MachineDomTreeNode *Node);
124
125 bool isPRECandidate(MachineInstr *MI, SmallSet<MCRegister, 8> &PhysRefs);
126 bool ProcessBlockPRE(MachineDominatorTree *MDT, MachineBasicBlock *MBB);
127 bool PerformSimplePRE(MachineDominatorTree *DT);
128 /// Heuristics to see if it's profitable to move common computations of MBB
129 /// and MBB1 to CandidateBB.
130 bool isProfitableToHoistInto(MachineBasicBlock *CandidateBB,
131 MachineBasicBlock *MBB, MachineBasicBlock *MBB1);
132 void releaseMemory();
133};
134
135class MachineCSELegacy : public MachineFunctionPass {
136public:
137 static char ID; // Pass identification
138
139 MachineCSELegacy() : MachineFunctionPass(ID) {}
140
141 bool runOnMachineFunction(MachineFunction &MF) override;
142
143 void getAnalysisUsage(AnalysisUsage &AU) const override {
144 AU.setPreservesCFG();
146 AU.addRequired<MachineDominatorTreeWrapperPass>();
147 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
148 }
149
150 MachineFunctionProperties getRequiredProperties() const override {
151 return MachineFunctionProperties().setIsSSA();
152 }
153};
154} // end anonymous namespace
155
156char MachineCSELegacy::ID = 0;
157
158char &llvm::MachineCSELegacyID = MachineCSELegacy::ID;
159
161 "Machine Common Subexpression Elimination", false, false)
164 "Machine Common Subexpression Elimination", false, false)
165
166/// The source register of a COPY machine instruction can be propagated to all
167/// its users, and this propagation could increase the probability of finding
168/// common subexpressions. If the COPY has only one user, the COPY itself can
169/// be removed.
170bool MachineCSEImpl::PerformTrivialCopyPropagation(MachineInstr *MI,
172 bool Changed = false;
173 for (MachineOperand &MO : MI->all_uses()) {
174 Register Reg = MO.getReg();
175 if (!Reg.isVirtual())
176 continue;
177 bool OnlyOneUse = MRI->hasOneNonDBGUse(Reg);
178 MachineInstr *DefMI = MRI->getVRegDef(Reg);
179 if (!DefMI || !DefMI->isCopy())
180 continue;
181 Register SrcReg = DefMI->getOperand(1).getReg();
182 if (!SrcReg.isVirtual())
183 continue;
184 // FIXME: We should trivially coalesce subregister copies to expose CSE
185 // opportunities on instructions with truncated operands (see
186 // cse-add-with-overflow.ll). This can be done here as follows:
187 // if (SrcSubReg)
188 // RC = TRI->getMatchingSuperRegClass(MRI->getRegClass(SrcReg), RC,
189 // SrcSubReg);
190 // MO.substVirtReg(SrcReg, SrcSubReg, *TRI);
191 //
192 // The 2-addr pass has been updated to handle coalesced subregs. However,
193 // some machine-specific code still can't handle it.
194 // To handle it properly we also need a way find a constrained subregister
195 // class given a super-reg class and subreg index.
196 if (DefMI->getOperand(1).getSubReg())
197 continue;
198 if (!MRI->constrainRegAttrs(SrcReg, Reg))
199 continue;
200 LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI);
201 LLVM_DEBUG(dbgs() << "*** to: " << *MI);
202
203 // Propagate SrcReg of copies to MI.
204 MO.setReg(SrcReg);
205 // Coalesce single use copies.
206 if (OnlyOneUse) {
207 // If (and only if) we've eliminated all uses of the copy, also
208 // copy-propagate to any debug-users of MI, or they'll be left using
209 // an undefined value.
210 DefMI->changeDebugValuesDefReg(SrcReg);
211
212 DefMI->eraseFromParent();
213 ++NumCoalesces;
214 }
215 Changed = true;
216 }
217
218 return Changed;
219}
220
221bool MachineCSEImpl::isPhysDefTriviallyDead(
224 unsigned LookAheadLeft = LookAheadLimit;
225 while (LookAheadLeft) {
226 // Skip over dbg_value's.
228
229 if (I == E)
230 // Reached end of block, we don't know if register is dead or not.
231 return false;
232
233 bool SeenDef = false;
234 for (const MachineOperand &MO : I->operands()) {
235 if (MO.isRegMask() && MO.clobbersPhysReg(Reg))
236 SeenDef = true;
237 if (!MO.isReg() || !MO.getReg())
238 continue;
239 if (!TRI->regsOverlap(MO.getReg(), Reg))
240 continue;
241 if (MO.isUse())
242 // Found a use!
243 return false;
244 SeenDef = true;
245 }
246 if (SeenDef)
247 // See a def of Reg (or an alias) before encountering any use, it's
248 // trivially dead.
249 return true;
250
251 --LookAheadLeft;
252 ++I;
253 }
254 return false;
255}
256
258 const MachineInstr &MI,
259 unsigned OpIdx,
260 const MachineFunction &MF,
261 const TargetRegisterInfo &TRI,
262 const TargetInstrInfo &TII) {
263 // MachineRegisterInfo::isConstantPhysReg directly called by
264 // MachineRegisterInfo::isCallerPreservedOrConstPhysReg expects the
265 // reserved registers to be frozen. That doesn't cause a problem post-ISel as
266 // most (if not all) targets freeze reserved registers right after ISel.
267 //
268 // It does cause issues mid-GlobalISel, however, hence the additional
269 // reservedRegsFrozen check.
270 const MachineRegisterInfo &MRI = MF.getRegInfo();
271 return TRI.isCallerPreservedPhysReg(Reg, MF) ||
272 TII.isIgnorableUse(MI, OpIdx) ||
273 (MRI.reservedRegsFrozen() && MRI.isConstantPhysReg(Reg));
274}
275
276/// hasLivePhysRegDefUses - Return true if the specified instruction read/write
277/// physical registers (except for dead defs of physical registers). It also
278/// returns the physical register def by reference if it's the only one and the
279/// instruction does not uses a physical register.
280bool MachineCSEImpl::hasLivePhysRegDefUses(const MachineInstr *MI,
281 const MachineBasicBlock *MBB,
282 SmallSet<MCRegister, 8> &PhysRefs,
283 PhysDefVector &PhysDefs,
284 bool &PhysUseDef) const {
285 // First, add all uses to PhysRefs.
286 for (const MachineOperand &MO : MI->all_uses()) {
287 Register Reg = MO.getReg();
288 if (!Reg)
289 continue;
290 if (Reg.isVirtual())
291 continue;
292 // Reading either caller preserved or constant physregs is ok.
294 MI->getOperandNo(&MO), *MI->getMF(),
295 *TRI, *TII))
296 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
297 PhysRefs.insert(*AI);
298 }
299
300 // Next, collect all defs into PhysDefs. If any is already in PhysRefs
301 // (which currently contains only uses), set the PhysUseDef flag.
302 PhysUseDef = false;
303 MachineBasicBlock::const_iterator I = MI; I = std::next(I);
304 for (const auto &MOP : llvm::enumerate(MI->operands())) {
305 const MachineOperand &MO = MOP.value();
306 if (!MO.isReg() || !MO.isDef())
307 continue;
308 Register Reg = MO.getReg();
309 if (!Reg)
310 continue;
311 if (Reg.isVirtual())
312 continue;
313 // Check against PhysRefs even if the def is "dead".
314 if (PhysRefs.count(Reg.asMCReg()))
315 PhysUseDef = true;
316 // If the def is dead, it's ok. But the def may not marked "dead". That's
317 // common since this pass is run before livevariables. We can scan
318 // forward a few instructions and check if it is obviously dead.
319 if (!MO.isDead() && !isPhysDefTriviallyDead(Reg.asMCReg(), I, MBB->end()))
320 PhysDefs.emplace_back(MOP.index(), Reg);
321 }
322
323 // Finally, add all defs to PhysRefs as well.
324 for (const auto &Def : PhysDefs)
325 for (MCRegAliasIterator AI(Def.second, TRI, true); AI.isValid(); ++AI)
326 PhysRefs.insert(*AI);
327
328 return !PhysRefs.empty();
329}
330
331bool MachineCSEImpl::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
332 const SmallSet<MCRegister, 8> &PhysRefs,
333 const PhysDefVector &PhysDefs,
334 bool &NonLocal) const {
335 // For now conservatively returns false if the common subexpression is
336 // not in the same basic block as the given instruction. The only exception
337 // is if the common subexpression is in the sole predecessor block.
338 const MachineBasicBlock *MBB = MI->getParent();
339 const MachineBasicBlock *CSMBB = CSMI->getParent();
340
341 bool CrossMBB = false;
342 if (CSMBB != MBB) {
343 if (MBB->pred_size() != 1 || *MBB->pred_begin() != CSMBB)
344 return false;
345
346 for (const auto &PhysDef : PhysDefs) {
347 if (MRI->isAllocatable(PhysDef.second) || MRI->isReserved(PhysDef.second))
348 // Avoid extending live range of physical registers if they are
349 //allocatable or reserved.
350 return false;
351 }
352 CrossMBB = true;
353 }
354 MachineBasicBlock::const_iterator I = CSMI; I = std::next(I);
357 unsigned LookAheadLeft = LookAheadLimit;
358 while (LookAheadLeft) {
359 // Skip over dbg_value's.
360 while (I != E && I != EE && I->isDebugInstr())
361 ++I;
362
363 if (I == EE) {
364 assert(CrossMBB && "Reaching end-of-MBB without finding MI?");
365 (void)CrossMBB;
366 CrossMBB = false;
367 NonLocal = true;
368 I = MBB->begin();
369 EE = MBB->end();
370 continue;
371 }
372
373 if (I == E)
374 return true;
375
376 for (const MachineOperand &MO : I->operands()) {
377 // RegMasks go on instructions like calls that clobber lots of physregs.
378 // Don't attempt to CSE across such an instruction.
379 if (MO.isRegMask())
380 return false;
381 if (!MO.isReg() || !MO.isDef())
382 continue;
383 Register MOReg = MO.getReg();
384 if (MOReg.isVirtual())
385 continue;
386 if (PhysRefs.count(MOReg.asMCReg()))
387 return false;
388 }
389
390 --LookAheadLeft;
391 ++I;
392 }
393
394 return false;
395}
396
397bool MachineCSEImpl::isCSECandidate(MachineInstr *MI) {
398 if (MI->isPosition() || MI->isPHI() || MI->isImplicitDef() || MI->isKill() ||
399 MI->isInlineAsm() || MI->isDebugInstr() || MI->isJumpTableDebugInfo() ||
400 MI->isFakeUse())
401 return false;
402
403 // Ignore copies.
404 if (MI->isCopyLike())
405 return false;
406
407 // Ignore stuff that we obviously can't move.
408 if (MI->mayStore() || MI->isCall() || MI->isTerminator() ||
409 MI->mayRaiseFPException() || MI->hasUnmodeledSideEffects())
410 return false;
411
412 if (MI->mayLoad()) {
413 // Okay, this instruction does a load. As a refinement, we allow the target
414 // to decide whether the loaded value is actually a constant. If so, we can
415 // actually use it as a load.
416 if (!MI->isDereferenceableInvariantLoad())
417 // FIXME: we should be able to hoist loads with no other side effects if
418 // there are no other instructions which can change memory in this loop.
419 // This is a trivial form of alias analysis.
420 return false;
421 }
422
423 // Ignore stack guard loads, otherwise the register that holds CSEed value may
424 // be spilled and get loaded back with corrupted data.
425 if (MI->getOpcode() == TargetOpcode::LOAD_STACK_GUARD)
426 return false;
427
428 return true;
429}
430
431/// isProfitableToCSE - Return true if it's profitable to eliminate MI with a
432/// common expression that defines Reg. CSBB is basic block where CSReg is
433/// defined.
434bool MachineCSEImpl::isProfitableToCSE(Register CSReg, Register Reg,
435 MachineBasicBlock *CSBB,
436 MachineInstr *MI) {
438 return true;
439
440 // FIXME: Heuristics that works around the lack the live range splitting.
441
442 // If CSReg is used at all uses of Reg, CSE should not increase register
443 // pressure of CSReg.
444 bool MayIncreasePressure = true;
445 if (CSReg.isVirtual() && Reg.isVirtual()) {
446 MayIncreasePressure = false;
447 SmallPtrSet<MachineInstr*, 8> CSUses;
448 int NumOfUses = 0;
449 for (MachineInstr &MI : MRI->use_nodbg_instructions(CSReg)) {
450 CSUses.insert(&MI);
451 // Too costly to compute if NumOfUses is very large. Conservatively assume
452 // MayIncreasePressure to avoid spending too much time here.
453 if (++NumOfUses > CSUsesThreshold) {
454 MayIncreasePressure = true;
455 break;
456 }
457 }
458 if (!MayIncreasePressure)
459 for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
460 if (!CSUses.count(&MI)) {
461 MayIncreasePressure = true;
462 break;
463 }
464 }
465 }
466 if (!MayIncreasePressure) return true;
467
468 // Heuristics #1: Don't CSE "cheap" computation if the def is not local or in
469 // an immediate predecessor. We don't want to increase register pressure and
470 // end up causing other computation to be spilled.
471 if (TII->isAsCheapAsAMove(*MI)) {
472 MachineBasicBlock *BB = MI->getParent();
473 if (CSBB != BB && !CSBB->isSuccessor(BB))
474 return false;
475 }
476
477 // Heuristics #2: If the expression doesn't not use a vr and the only use
478 // of the redundant computation are copies, do not cse.
479 bool HasVRegUse = false;
480 for (const MachineOperand &MO : MI->all_uses()) {
481 if (MO.getReg().isVirtual()) {
482 HasVRegUse = true;
483 break;
484 }
485 }
486 if (!HasVRegUse) {
487 bool HasNonCopyUse = false;
488 for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) {
489 // Ignore copies.
490 if (!MI.isCopyLike()) {
491 HasNonCopyUse = true;
492 break;
493 }
494 }
495 if (!HasNonCopyUse)
496 return false;
497 }
498
499 // Heuristics #3: If the common subexpression is used by PHIs, do not reuse
500 // it unless the defined value is already used in the BB of the new use.
501 bool HasPHI = false;
502 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(CSReg)) {
503 HasPHI |= UseMI.isPHI();
504 if (UseMI.getParent() == MI->getParent())
505 return true;
506 }
507
508 return !HasPHI;
509}
510
511void MachineCSEImpl::EnterScope(MachineBasicBlock *MBB) {
512 LLVM_DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
513 ScopeType *Scope = new ScopeType(VNT);
514 ScopeMap[MBB] = Scope;
515}
516
517void MachineCSEImpl::ExitScope(MachineBasicBlock *MBB) {
518 LLVM_DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
519 auto SI = ScopeMap.find(MBB);
520 assert(SI != ScopeMap.end());
521 delete SI->second;
522 ScopeMap.erase(SI);
523}
524
525bool MachineCSEImpl::ProcessBlockCSE(MachineBasicBlock *MBB) {
526 bool Changed = false;
527
529 SmallVector<unsigned, 2> ImplicitDefsToUpdate;
530 SmallVector<Register, 2> ImplicitDefs;
531 for (MachineInstr &MI : llvm::make_early_inc_range(*MBB)) {
532 if (!isCSECandidate(&MI))
533 continue;
534
535 bool FoundCSE = VNT.count(&MI);
536 if (!FoundCSE) {
537 // Using trivial copy propagation to find more CSE opportunities.
538 if (PerformTrivialCopyPropagation(&MI, MBB)) {
539 Changed = true;
540
541 // After coalescing MI itself may become a copy.
542 if (MI.isCopyLike())
543 continue;
544
545 // Try again to see if CSE is possible.
546 FoundCSE = VNT.count(&MI);
547 }
548 }
549
550 // Commute commutable instructions.
551 bool Commuted = false;
552 if (!FoundCSE && MI.isCommutable()) {
553 if (MachineInstr *NewMI = TII->commuteInstruction(MI)) {
554 Commuted = true;
555 FoundCSE = VNT.count(NewMI);
556 if (NewMI != &MI) {
557 // New instruction. It doesn't need to be kept.
558 NewMI->eraseFromParent();
559 Changed = true;
560 } else if (!FoundCSE)
561 // MI was changed but it didn't help, commute it back!
562 (void)TII->commuteInstruction(MI);
563 }
564 }
565
566 // If the instruction defines physical registers and the values *may* be
567 // used, then it's not safe to replace it with a common subexpression.
568 // It's also not safe if the instruction uses physical registers.
569 bool CrossMBBPhysDef = false;
570 SmallSet<MCRegister, 8> PhysRefs;
571 PhysDefVector PhysDefs;
572 bool PhysUseDef = false;
573 if (FoundCSE &&
574 hasLivePhysRegDefUses(&MI, MBB, PhysRefs, PhysDefs, PhysUseDef)) {
575 FoundCSE = false;
576
577 // ... Unless the CS is local or is in the sole predecessor block
578 // and it also defines the physical register which is not clobbered
579 // in between and the physical register uses were not clobbered.
580 // This can never be the case if the instruction both uses and
581 // defines the same physical register, which was detected above.
582 if (!PhysUseDef) {
583 unsigned CSVN = VNT.lookup(&MI);
584 MachineInstr *CSMI = Exps[CSVN];
585 if (PhysRegDefsReach(CSMI, &MI, PhysRefs, PhysDefs, CrossMBBPhysDef))
586 FoundCSE = true;
587 }
588 }
589
590 if (!FoundCSE) {
591 VNT.insert(&MI, CurrVN++);
592 Exps.push_back(&MI);
593 continue;
594 }
595
596 // Found a common subexpression, eliminate it.
597 unsigned CSVN = VNT.lookup(&MI);
598 MachineInstr *CSMI = Exps[CSVN];
599 LLVM_DEBUG(dbgs() << "Examining: " << MI);
600 LLVM_DEBUG(dbgs() << "*** Found a common subexpression: " << *CSMI);
601
602 // Prevent CSE-ing non-local convergent instructions.
603 // LLVM's current definition of `isConvergent` does not necessarily prove
604 // that non-local CSE is illegal. The following check extends the definition
605 // of `isConvergent` to assume a convergent instruction is dependent not
606 // only on additional conditions, but also on fewer conditions. LLVM does
607 // not have a MachineInstr attribute which expresses this extended
608 // definition, so it's necessary to use `isConvergent` to prevent illegally
609 // CSE-ing the subset of `isConvergent` instructions which do fall into this
610 // extended definition.
611 if (MI.isConvergent() && MI.getParent() != CSMI->getParent()) {
612 LLVM_DEBUG(dbgs() << "*** Convergent MI and subexpression exist in "
613 "different BBs, avoid CSE!\n");
614 VNT.insert(&MI, CurrVN++);
615 Exps.push_back(&MI);
616 continue;
617 }
618
619 // Check if it's profitable to perform this CSE.
620 bool DoCSE = true;
621 unsigned NumDefs = MI.getNumDefs();
622
623 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
624 MachineOperand &MO = MI.getOperand(i);
625 if (!MO.isReg() || !MO.isDef())
626 continue;
627 Register OldReg = MO.getReg();
628 Register NewReg = CSMI->getOperand(i).getReg();
629
630 // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
631 // we should make sure it is not dead at CSMI.
632 if (MO.isImplicit() && !MO.isDead() && CSMI->getOperand(i).isDead())
633 ImplicitDefsToUpdate.push_back(i);
634
635 // Keep track of implicit defs of CSMI and MI, to clear possibly
636 // made-redundant kill flags.
637 if (MO.isImplicit() && !MO.isDead() && OldReg == NewReg)
638 ImplicitDefs.push_back(OldReg);
639
640 if (OldReg == NewReg) {
641 --NumDefs;
642 continue;
643 }
644
645 assert(OldReg.isVirtual() && NewReg.isVirtual() &&
646 "Do not CSE physical register defs!");
647
648 if (!isProfitableToCSE(NewReg, OldReg, CSMI->getParent(), &MI)) {
649 LLVM_DEBUG(dbgs() << "*** Not profitable, avoid CSE!\n");
650 DoCSE = false;
651 break;
652 }
653
654 // Don't perform CSE if the result of the new instruction cannot exist
655 // within the constraints (register class, bank, or low-level type) of
656 // the old instruction.
657 if (!MRI->constrainRegAttrs(NewReg, OldReg)) {
659 dbgs() << "*** Not the same register constraints, avoid CSE!\n");
660 DoCSE = false;
661 break;
662 }
663
664 CSEPairs.emplace_back(OldReg, NewReg);
665 --NumDefs;
666 }
667
668 // Actually perform the elimination.
669 if (DoCSE) {
670 for (const std::pair<Register, Register> &CSEPair : CSEPairs) {
671 Register OldReg = CSEPair.first;
672 Register NewReg = CSEPair.second;
673 // OldReg may have been unused but is used now, clear the Dead flag
674 MachineInstr *Def = MRI->getUniqueVRegDef(NewReg);
675 assert(Def != nullptr && "CSEd register has no unique definition?");
676 Def->clearRegisterDeads(NewReg);
677 MRI->replaceRegWith(OldReg, NewReg);
678 }
679
680 // Go through implicit defs of CSMI and MI, if a def is not dead at MI,
681 // we should make sure it is not dead at CSMI.
682 for (unsigned ImplicitDefToUpdate : ImplicitDefsToUpdate)
683 CSMI->getOperand(ImplicitDefToUpdate).setIsDead(false);
684 for (const auto &PhysDef : PhysDefs)
685 if (!MI.getOperand(PhysDef.first).isDead())
686 CSMI->getOperand(PhysDef.first).setIsDead(false);
687
688 // Go through implicit defs of CSMI and MI, and clear the kill flags on
689 // their uses in all the instructions between CSMI and MI.
690 // We might have made some of the kill flags redundant, consider:
691 // subs ... implicit-def %nzcv <- CSMI
692 // csinc ... implicit killed %nzcv <- this kill flag isn't valid anymore
693 // subs ... implicit-def %nzcv <- MI, to be eliminated
694 // csinc ... implicit killed %nzcv
695 // Since we eliminated MI, and reused a register imp-def'd by CSMI
696 // (here %nzcv), that register, if it was killed before MI, should have
697 // that kill flag removed, because it's lifetime was extended.
698 if (CSMI->getParent() == MI.getParent()) {
699 for (MachineBasicBlock::iterator II = CSMI, IE = &MI; II != IE; ++II)
700 for (auto ImplicitDef : ImplicitDefs)
701 if (MachineOperand *MO = II->findRegisterUseOperand(
702 ImplicitDef, TRI, /*isKill=*/true))
703 MO->setIsKill(false);
704 } else {
705 // If the instructions aren't in the same BB, bail out and clear the
706 // kill flag on all uses of the imp-def'd register.
707 for (auto ImplicitDef : ImplicitDefs)
708 MRI->clearKillFlags(ImplicitDef);
709 }
710
711 if (CrossMBBPhysDef) {
712 // Add physical register defs now coming in from a predecessor to MBB
713 // livein list.
714 while (!PhysDefs.empty()) {
715 auto LiveIn = PhysDefs.pop_back_val();
716 if (!MBB->isLiveIn(LiveIn.second))
717 MBB->addLiveIn(LiveIn.second);
718 }
719 ++NumCrossBBCSEs;
720 }
721
722 MI.eraseFromParent();
723 ++NumCSEs;
724 if (!PhysRefs.empty())
725 ++NumPhysCSEs;
726 if (Commuted)
727 ++NumCommutes;
728 Changed = true;
729 } else {
730 VNT.insert(&MI, CurrVN++);
731 Exps.push_back(&MI);
732 }
733 CSEPairs.clear();
734 ImplicitDefsToUpdate.clear();
735 ImplicitDefs.clear();
736 }
737
738 return Changed;
739}
740
741/// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
742/// dominator tree node if its a leaf or all of its children are done. Walk
743/// up the dominator tree to destroy ancestors which are now done.
744void MachineCSEImpl::ExitScopeIfDone(
745 MachineDomTreeNode *Node,
746 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren) {
747 if (OpenChildren[Node])
748 return;
749
750 // Pop scope.
751 ExitScope(Node->getBlock());
752
753 // Now traverse upwards to pop ancestors whose offsprings are all done.
754 while (MachineDomTreeNode *Parent = Node->getIDom()) {
755 unsigned Left = --OpenChildren[Parent];
756 if (Left != 0)
757 break;
758 ExitScope(Parent->getBlock());
759 Node = Parent;
760 }
761}
762
763bool MachineCSEImpl::PerformCSE(MachineDomTreeNode *Node) {
766 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
767
768 CurrVN = 0;
769
770 // Perform a DFS walk to determine the order of visit.
771 WorkList.push_back(Node);
772 do {
773 Node = WorkList.pop_back_val();
774 Scopes.push_back(Node);
775 size_t WorkListSize = WorkList.size();
776 append_range(WorkList, Node->children());
777 OpenChildren[Node] = WorkList.size() - WorkListSize; // Number of children.
778 } while (!WorkList.empty());
779
780 // Now perform CSE.
781 bool Changed = false;
782 for (MachineDomTreeNode *Node : Scopes) {
783 MachineBasicBlock *MBB = Node->getBlock();
784 EnterScope(MBB);
785 Changed |= ProcessBlockCSE(MBB);
786 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
787 ExitScopeIfDone(Node, OpenChildren);
788 }
789
790 return Changed;
791}
792
793// We use stronger checks for PRE candidate rather than for CSE ones to embrace
794// checks inside ProcessBlockCSE(), not only inside isCSECandidate(). This helps
795// to exclude instrs created by PRE that won't be CSEed later.
796bool MachineCSEImpl::isPRECandidate(MachineInstr *MI,
797 SmallSet<MCRegister, 8> &PhysRefs) {
798 if (!isCSECandidate(MI) ||
799 MI->isNotDuplicable() ||
800 MI->mayLoad() ||
802 MI->getNumDefs() != 1 ||
803 MI->getNumExplicitDefs() != 1)
804 return false;
805
806 for (const MachineOperand &MO : MI->operands()) {
807 if (MO.isReg() && !MO.getReg().isVirtual()) {
808 if (MO.isDef())
809 return false;
810 else
811 PhysRefs.insert(MO.getReg());
812 }
813 }
814
815 return true;
816}
817
818bool MachineCSEImpl::ProcessBlockPRE(MachineDominatorTree *DT,
819 MachineBasicBlock *MBB) {
820 bool Changed = false;
821 for (MachineInstr &MI : llvm::make_early_inc_range(*MBB)) {
822 SmallSet<MCRegister, 8> PhysRefs;
823 if (!isPRECandidate(&MI, PhysRefs))
824 continue;
825
826 auto [It, Inserted] = PREMap.try_emplace(&MI, MBB);
827 if (Inserted)
828 continue;
829
830 auto *MBB1 = It->second;
831 assert(
832 !DT->properlyDominates(MBB, MBB1) &&
833 "MBB cannot properly dominate MBB1 while DFS through dominators tree!");
834 auto CMBB = DT->findNearestCommonDominator(MBB, MBB1);
835 if (!CMBB->isLegalToHoistInto())
836 continue;
837
838 if (!isProfitableToHoistInto(CMBB, MBB, MBB1))
839 continue;
840
841 // Two instrs are partial redundant if their basic blocks are reachable
842 // from one to another but one doesn't dominate another.
843 if (CMBB != MBB1) {
844 auto BB = MBB->getBasicBlock(), BB1 = MBB1->getBasicBlock();
845 if (BB != nullptr && BB1 != nullptr &&
846 (isPotentiallyReachable(BB1, BB) ||
847 isPotentiallyReachable(BB, BB1))) {
848 // The following check extends the definition of `isConvergent` to
849 // assume a convergent instruction is dependent not only on additional
850 // conditions, but also on fewer conditions. LLVM does not have a
851 // MachineInstr attribute which expresses this extended definition, so
852 // it's necessary to use `isConvergent` to prevent illegally PRE-ing the
853 // subset of `isConvergent` instructions which do fall into this
854 // extended definition.
855 if (MI.isConvergent() && CMBB != MBB)
856 continue;
857
858 // If this instruction uses physical registers then we can only do PRE
859 // if it's using the value that is live at the place we're hoisting to.
860 bool NonLocal;
861 PhysDefVector PhysDefs;
862 if (!PhysRefs.empty() &&
863 !PhysRegDefsReach(&*(CMBB->getFirstTerminator()), &MI, PhysRefs,
864 PhysDefs, NonLocal))
865 continue;
866
867 assert(MI.getOperand(0).isDef() &&
868 "First operand of instr with one explicit def must be this def");
869 Register VReg = MI.getOperand(0).getReg();
870 Register NewReg = MRI->cloneVirtualRegister(VReg);
871 if (!isProfitableToCSE(NewReg, VReg, CMBB, &MI))
872 continue;
873 MachineInstr &NewMI =
874 TII->duplicate(*CMBB, CMBB->getFirstTerminator(), MI);
875
876 // When hoisting, make sure we don't carry the debug location of
877 // the original instruction, as that's not correct and can cause
878 // unexpected jumps when debugging optimized code.
879 auto EmptyDL = DebugLoc();
880 NewMI.setDebugLoc(EmptyDL);
881
882 NewMI.getOperand(0).setReg(NewReg);
883
884 PREMap[&MI] = CMBB;
885 ++NumPREs;
886 Changed = true;
887 }
888 }
889 }
890 return Changed;
891}
892
893// This simple PRE (partial redundancy elimination) pass doesn't actually
894// eliminate partial redundancy but transforms it to full redundancy,
895// anticipating that the next CSE step will eliminate this created redundancy.
896// If CSE doesn't eliminate this, than created instruction will remain dead
897// and eliminated later by Remove Dead Machine Instructions pass.
898bool MachineCSEImpl::PerformSimplePRE(MachineDominatorTree *DT) {
900
901 PREMap.clear();
902 bool Changed = false;
903 BBs.push_back(DT->getRootNode());
904 do {
905 auto Node = BBs.pop_back_val();
906 append_range(BBs, Node->children());
907
908 MachineBasicBlock *MBB = Node->getBlock();
909 Changed |= ProcessBlockPRE(DT, MBB);
910
911 } while (!BBs.empty());
912
913 return Changed;
914}
915
916bool MachineCSEImpl::isProfitableToHoistInto(MachineBasicBlock *CandidateBB,
917 MachineBasicBlock *MBB,
918 MachineBasicBlock *MBB1) {
919 if (CandidateBB->getParent()->getFunction().hasMinSize())
920 return true;
921 assert(DT->dominates(CandidateBB, MBB) && "CandidateBB should dominate MBB");
922 assert(DT->dominates(CandidateBB, MBB1) &&
923 "CandidateBB should dominate MBB1");
924 return MBFI->getBlockFreq(CandidateBB) <=
925 MBFI->getBlockFreq(MBB) + MBFI->getBlockFreq(MBB1);
926}
927
928void MachineCSEImpl::releaseMemory() {
929 ScopeMap.clear();
930 PREMap.clear();
931 Exps.clear();
932}
933
934bool MachineCSEImpl::run(MachineFunction &MF) {
937 MRI = &MF.getRegInfo();
938 LookAheadLimit = TII->getMachineCSELookAheadLimit();
939 bool ChangedPRE, ChangedCSE;
940 ChangedPRE = PerformSimplePRE(DT);
941 ChangedCSE = PerformCSE(DT->getRootNode());
942 releaseMemory();
943 return ChangedPRE || ChangedCSE;
944}
945
948 MFPropsModifier _(*this, MF);
949
953 MachineCSEImpl Impl(&MDT, &MBFI);
954 bool Changed = Impl.run(MF);
955 if (!Changed)
956 return PreservedAnalyses::all();
957
959 PA.preserveSet<CFGAnalyses>();
960 return PA;
961}
962
963bool MachineCSELegacy::runOnMachineFunction(MachineFunction &MF) {
964 if (skipFunction(MF.getFunction()))
965 return false;
966
968 getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
970 getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
971 MachineCSEImpl Impl(&MDT, &MBFI);
972 return Impl.run(MF);
973}
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
static cl::opt< int > CSUsesThreshold("csuses-threshold", cl::Hidden, cl::init(1024), cl::desc("Threshold for the size of CSUses"))
static cl::opt< bool > AggressiveMachineCSE("aggressive-machine-cse", cl::Hidden, cl::init(false), cl::desc("Override the profitability heuristics for Machine CSE"))
static bool isCallerPreservedOrConstPhysReg(MCRegister Reg, const MachineInstr &MI, unsigned OpIdx, const MachineFunction &MF, const TargetRegisterInfo &TRI, const TargetInstrInfo &TII)
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
MachineRegisterInfo & MRI
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
Find nearest common dominator basic block for basic block A and B.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:696
bool isAsCheapAsAMove(const MachineInstr &MI) const override
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
An RAII based helper class to modify MachineFunctionProperties when running pass.
MachineInstrBundleIterator< const MachineInstr > const_iterator
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
const MachineOperand & getOperand(unsigned i) const
void setDebugLoc(DebugLoc DL)
Replace current source information with new such.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
void setIsDead(bool Val=true)
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI void clearKillFlags(Register Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
bool isAllocatable(MCRegister PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn't been...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
LLVM_ABI Register cloneVirtualRegister(Register VReg, StringRef Name="")
Create and return a new virtual register in the function with the same attributes as the given regist...
LLVM_ABI bool constrainRegAttrs(Register Reg, Register ConstrainingReg, unsigned MinNumRegs=0)
Constrain the register class or the register bank of the virtual register Reg (and low-level type) to...
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
size_type count(const K &Key) const
Return 1 if the specified key is in the table, 0 otherwise.
void insert(const K &Key, const V &Val)
V lookup(const K &Key) const
ScopedHashTableScope< MachineInstr *, unsigned, MachineInstrExpressionTrait, AllocatorTy > ScopeTy
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
bool empty() const
Definition SmallSet.h:169
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
LLVM_ABI bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet=nullptr, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr, const CycleInfo *CI=nullptr)
Determine whether instruction 'To' is reachable from 'From', without passing through any blocks in Ex...
Definition CFG.cpp:335
LLVM_ABI char & MachineCSELegacyID
MachineCSE - This pass performs global CSE on machine instructions.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391