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