LLVM 23.0.0git
LiveVariables.cpp
Go to the documentation of this file.
1//===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===//
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 file implements the LiveVariable analysis pass. For each machine
10// instruction in the function, this pass calculates the set of registers that
11// are immediately dead after the instruction (i.e., the instruction calculates
12// the value, but it is never used) and the set of registers that are used by
13// the instruction, but are never used after the instruction (i.e., they are
14// killed).
15//
16// This class computes live variables using a sparse implementation based on
17// the machine code SSA form. This class computes live variable information for
18// each virtual and _register allocatable_ physical register in a function. It
19// uses the dominance properties of SSA form to efficiently compute live
20// variables for virtual registers, and assumes that physical registers are only
21// live within a single basic block (allowing it to do a single local analysis
22// to resolve physical register lifetimes in each basic block). If a physical
23// register is not register allocatable, it is not tracked. This is useful for
24// things like the stack pointer and condition codes.
25//
26//===----------------------------------------------------------------------===//
27
29#include "llvm/ADT/DenseSet.h"
31#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SmallSet.h"
36#include "llvm/CodeGen/Passes.h"
37#include "llvm/Config/llvm-config.h"
39#include "llvm/Support/Debug.h"
42using namespace llvm;
43
44AnalysisKey LiveVariablesAnalysis::Key;
45
51
55 OS << "Live variables in machine function: " << MF.getName() << '\n';
58}
59
63 "Live Variable Analysis", false, false)
64INITIALIZE_PASS_DEPENDENCY(UnreachableMachineBlockElimLegacy)
66 "Live Variable Analysis", false, false)
67
69 AU.addRequiredID(UnreachableMachineBlockElimID);
70 AU.setPreservesAll();
72}
73
74LiveVariables::LiveVariables(MachineFunction &MF)
75 : MF(&MF), MRI(&MF.getRegInfo()), TRI(MF.getSubtarget().getRegisterInfo()) {
76 analyze(MF);
77}
78
80 for (size_t I = 0, E = VirtRegInfo.size(); I != E; ++I) {
82 OS << "Virtual register '%" << I << "':\n";
83 VirtRegInfo[Reg].print(OS);
84 }
85}
86
89 for (MachineInstr *MI : Kills)
90 if (MI->getParent() == MBB)
91 return MI;
92 return nullptr;
93}
94
96 OS << " Alive in blocks: ";
97 for (unsigned AB : AliveBlocks)
98 OS << AB << ", ";
99 OS << "\n Killed by:";
100 if (Kills.empty())
101 OS << " No instructions.\n\n";
102 else {
103 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
104 OS << "\n #" << i << ": " << *Kills[i];
105 OS << "\n";
106 }
107}
108
109#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
111#endif
112
113/// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg.
115 assert(Reg.isVirtual() && "getVarInfo: not a virtual register!");
116 VirtRegInfo.grow(Reg);
117 return VirtRegInfo[Reg];
118}
119
121 VarInfo &VRInfo, MachineBasicBlock *DefBlock, MachineBasicBlock *MBB,
123 unsigned BBNum = MBB->getNumber();
124
125 // Check to see if this basic block is one of the killing blocks. If so,
126 // remove it.
127 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i)
128 if (VRInfo.Kills[i]->getParent() == MBB) {
129 VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry
130 break;
131 }
132
133 if (MBB == DefBlock) return; // Terminate recursion
134
135 if (VRInfo.AliveBlocks.test(BBNum))
136 return; // We already know the block is live
137
138 // Mark the variable known alive in this bb
139 VRInfo.AliveBlocks.set(BBNum);
140
141 assert(MBB != &MF->front() && "Can't find reaching def for virtreg");
142 WorkList.insert(WorkList.end(), MBB->pred_rbegin(), MBB->pred_rend());
143}
144
146 MachineBasicBlock *DefBlock,
149 MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList);
150
151 while (!WorkList.empty()) {
152 MachineBasicBlock *Pred = WorkList.pop_back_val();
153 MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList);
154 }
155}
156
158 MachineInstr &MI) {
159 assert(MRI->getVRegDef(Reg) && "Register use before def!");
160
161 unsigned BBNum = MBB->getNumber();
162
163 VarInfo &VRInfo = getVarInfo(Reg);
164
165 // Check to see if this basic block is already a kill block.
166 if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) {
167 // Yes, this register is killed in this basic block already. Increase the
168 // live range by updating the kill instruction.
169 VRInfo.Kills.back() = &MI;
170 return;
171 }
172
173#ifndef NDEBUG
174 for (MachineInstr *Kill : VRInfo.Kills)
175 assert(Kill->getParent() != MBB && "entry should be at end!");
176#endif
177
178 // This situation can occur:
179 //
180 // ,------.
181 // | |
182 // | v
183 // | t2 = phi ... t1 ...
184 // | |
185 // | v
186 // | t1 = ...
187 // | ... = ... t1 ...
188 // | |
189 // `------'
190 //
191 // where there is a use in a PHI node that's a predecessor to the defining
192 // block. We don't want to mark all predecessors as having the value "alive"
193 // in this case.
194 if (MBB == MRI->getVRegDef(Reg)->getParent())
195 return;
196
197 // Add a new kill entry for this basic block. If this virtual register is
198 // already marked as alive in this basic block, that means it is alive in at
199 // least one of the successor blocks, it's not a kill.
200 if (!VRInfo.AliveBlocks.test(BBNum))
201 VRInfo.Kills.push_back(&MI);
202
203 // Update all dominating blocks to mark them as "known live".
204 for (MachineBasicBlock *Pred : MBB->predecessors())
205 MarkVirtRegAliveInBlock(VRInfo, MRI->getVRegDef(Reg)->getParent(), Pred);
206}
207
209 VarInfo &VRInfo = getVarInfo(Reg);
210
211 if (VRInfo.AliveBlocks.empty())
212 // If vr is not alive in any block, then defaults to dead.
213 VRInfo.Kills.push_back(&MI);
214}
215
216/// FindLastPartialDef - Return the last partial def of the specified register.
217MachineInstr *LiveVariables::FindLastPartialDef(Register Reg) {
218 unsigned LastDefDist = 0;
219 MachineInstr *LastDef = nullptr;
220 for (MCPhysReg SubReg : TRI->subregs(Reg)) {
221 MachineInstr *Def = PhysRegDef[SubReg];
222 if (!Def)
223 continue;
224 unsigned Dist = DistanceMap[Def];
225 if (Dist > LastDefDist) {
226 LastDef = Def;
227 LastDefDist = Dist;
228 }
229 }
230
231 if (!LastDef)
232 return nullptr;
233
234 return LastDef;
235}
236
237/// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add
238/// implicit defs to a machine instruction if there was an earlier def of its
239/// super-register.
240void LiveVariables::HandlePhysRegUse(Register Reg, MachineInstr &MI) {
241 MachineInstr *LastDef = PhysRegDef[Reg.id()];
242 // If there was a previous use or a "full" def all is well.
243 if (!LastDef && !PhysRegUse[Reg.id()]) {
244 // Otherwise, the last sub-register def implicitly defines this register.
245 // e.g.
246 // AH =
247 // AL = ... implicit-def EAX, implicit killed AH
248 // = AH
249 // ...
250 // = EAX
251 // All of the sub-registers must have been defined before the use of Reg!
252 MachineInstr *LastPartialDef = FindLastPartialDef(Reg);
253 // If LastPartialDef is NULL, it must be using a livein register.
254 if (LastPartialDef) {
255 LastPartialDef->addOperand(
256 MachineOperand::CreateReg(Reg, /*IsDef=*/true, /*IsImp=*/true));
257 }
258 } else if (LastDef && !PhysRegUse[Reg.id()] &&
259 !LastDef->findRegisterDefOperand(Reg, /*TRI=*/nullptr))
260 // Last def defines the super register, add an implicit def of reg.
261 LastDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
262 true/*IsImp*/));
263
264 // Remember this use.
265 for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg))
266 PhysRegUse[SubReg] = &MI;
267}
268
269/// FindLastRefOrPartRef - Return the last reference or partial reference of
270/// the specified register.
271MachineInstr *LiveVariables::FindLastRefOrPartRef(Register Reg) {
272 MachineInstr *LastDef = PhysRegDef[Reg.id()];
273 MachineInstr *LastUse = PhysRegUse[Reg.id()];
274 if (!LastDef && !LastUse)
275 return nullptr;
276
277 MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
278 unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
279 unsigned LastPartDefDist = 0;
280 for (MCPhysReg SubReg : TRI->subregs(Reg)) {
281 MachineInstr *Def = PhysRegDef[SubReg];
282 if (Def && Def != LastDef) {
283 // There was a def of this sub-register in between. This is a partial
284 // def, keep track of the last one.
285 unsigned Dist = DistanceMap[Def];
286 if (Dist > LastPartDefDist)
287 LastPartDefDist = Dist;
288 } else if (MachineInstr *Use = PhysRegUse[SubReg]) {
289 unsigned Dist = DistanceMap[Use];
290 if (Dist > LastRefOrPartRefDist) {
291 LastRefOrPartRefDist = Dist;
292 LastRefOrPartRef = Use;
293 }
294 }
295 }
296
297 return LastRefOrPartRef;
298}
299
300bool LiveVariables::HandlePhysRegKill(Register Reg, MachineInstr *MI) {
301 MachineInstr *LastDef = PhysRegDef[Reg.id()];
302 MachineInstr *LastUse = PhysRegUse[Reg.id()];
303 if (!LastDef && !LastUse)
304 return false;
305
306 MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef;
307 unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef];
308 // The whole register is used.
309 // AL =
310 // AH =
311 //
312 // = AX
313 // = AL, implicit killed AX
314 // AX =
315 //
316 // Or whole register is defined, but not used at all.
317 // dead AX =
318 // ...
319 // AX =
320 //
321 // Or whole register is defined, but only partly used.
322 // dead AX = implicit-def AL
323 // = killed AL
324 // AX =
325 MachineInstr *LastPartDef = nullptr;
326 unsigned LastPartDefDist = 0;
327 SmallSet<unsigned, 8> PartUses;
328 for (MCPhysReg SubReg : TRI->subregs(Reg)) {
329 MachineInstr *Def = PhysRegDef[SubReg];
330 if (Def && Def != LastDef) {
331 // There was a def of this sub-register in between. This is a partial
332 // def, keep track of the last one.
333 unsigned Dist = DistanceMap[Def];
334 if (Dist > LastPartDefDist) {
335 LastPartDefDist = Dist;
336 LastPartDef = Def;
337 }
338 continue;
339 }
340 if (MachineInstr *Use = PhysRegUse[SubReg]) {
341 PartUses.insert_range(TRI->subregs_inclusive(SubReg));
342 unsigned Dist = DistanceMap[Use];
343 if (Dist > LastRefOrPartRefDist) {
344 LastRefOrPartRefDist = Dist;
345 LastRefOrPartRef = Use;
346 }
347 }
348 }
349
350 if (!PhysRegUse[Reg.id()]) {
351 // Partial uses. Mark register def dead and add implicit def of
352 // sub-registers which are used.
353 // dead EAX = op implicit-def AL
354 // That is, EAX def is dead but AL def extends pass it.
355 PhysRegDef[Reg.id()]->addRegisterDead(Reg, TRI, true);
356 for (MCPhysReg SubReg : TRI->subregs(Reg)) {
357 if (!PartUses.count(SubReg))
358 continue;
359 bool NeedDef = true;
360 if (PhysRegDef[Reg.id()] == PhysRegDef[SubReg]) {
361 MachineOperand *MO = PhysRegDef[Reg.id()]->findRegisterDefOperand(
362 SubReg, /*TRI=*/nullptr);
363 if (MO) {
364 NeedDef = false;
365 assert(!MO->isDead());
366 }
367 }
368 if (NeedDef)
369 PhysRegDef[Reg.id()]->addOperand(
370 MachineOperand::CreateReg(SubReg, true /*IsDef*/, true /*IsImp*/));
371 MachineInstr *LastSubRef = FindLastRefOrPartRef(SubReg);
372 if (LastSubRef)
373 LastSubRef->addRegisterKilled(SubReg, TRI, true);
374 else {
375 LastRefOrPartRef->addRegisterKilled(SubReg, TRI, true);
376 for (MCPhysReg SS : TRI->subregs_inclusive(SubReg))
377 PhysRegUse[SS] = LastRefOrPartRef;
378 }
379 for (MCPhysReg SS : TRI->subregs(SubReg))
380 PartUses.erase(SS);
381 }
382 } else if (LastRefOrPartRef == PhysRegDef[Reg.id()] &&
383 LastRefOrPartRef != MI) {
384 if (LastPartDef)
385 // The last partial def kills the register.
386 LastPartDef->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/,
387 true/*IsImp*/, true/*IsKill*/));
388 else {
389 MachineOperand *MO =
390 LastRefOrPartRef->findRegisterDefOperand(Reg, TRI, false, false);
391 bool NeedEC = MO->isEarlyClobber() && MO->getReg() != Reg;
392 // If the last reference is the last def, then it's not used at all.
393 // That is, unless we are currently processing the last reference itself.
394 LastRefOrPartRef->addRegisterDead(Reg, TRI, true);
395 if (NeedEC) {
396 // If we are adding a subreg def and the superreg def is marked early
397 // clobber, add an early clobber marker to the subreg def.
398 MO = LastRefOrPartRef->findRegisterDefOperand(Reg, /*TRI=*/nullptr);
399 if (MO)
400 MO->setIsEarlyClobber();
401 }
402 }
403 } else
404 LastRefOrPartRef->addRegisterKilled(Reg, TRI, true);
405 return true;
406}
407
408void LiveVariables::HandleRegMask(const MachineOperand &MO, unsigned NumRegs) {
409 // Call HandlePhysRegKill() for all live registers clobbered by Mask.
410 // Clobbered registers are always dead, sp there is no need to use
411 // HandlePhysRegDef().
412 for (unsigned Reg = 1; Reg != NumRegs; ++Reg) {
413 // Skip dead regs.
414 if (!PhysRegDef[Reg] && !PhysRegUse[Reg])
415 continue;
416 // Skip mask-preserved regs.
417 if (!MO.clobbersPhysReg(Reg))
418 continue;
419 // Kill the largest clobbered super-register.
420 // This avoids needless implicit operands.
421 unsigned Super = Reg;
422 for (MCPhysReg SR : TRI->superregs(Reg))
423 if (SR < NumRegs && (PhysRegDef[SR] || PhysRegUse[SR]) &&
424 MO.clobbersPhysReg(SR))
425 Super = SR;
426 HandlePhysRegKill(Super, nullptr);
427 }
428}
429
430void LiveVariables::HandlePhysRegDef(Register Reg, MachineInstr *MI,
431 SmallVectorImpl<Register> &Defs) {
432 // What parts of the register are previously defined?
433 SmallSet<unsigned, 32> Live;
434 if (PhysRegDef[Reg.id()] || PhysRegUse[Reg.id()]) {
435 Live.insert_range(TRI->subregs_inclusive(Reg));
436 } else {
437 for (MCPhysReg SubReg : TRI->subregs(Reg)) {
438 // If a register isn't itself defined, but all parts that make up of it
439 // are defined, then consider it also defined.
440 // e.g.
441 // AL =
442 // AH =
443 // = AX
444 if (Live.count(SubReg))
445 continue;
446 if (PhysRegDef[SubReg] || PhysRegUse[SubReg])
447 Live.insert_range(TRI->subregs_inclusive(SubReg));
448 }
449 }
450
451 // Start from the largest piece, find the last time any part of the register
452 // is referenced.
453 HandlePhysRegKill(Reg, MI);
454 // Only some of the sub-registers are used.
455 for (MCPhysReg SubReg : TRI->subregs(Reg)) {
456 if (!Live.count(SubReg))
457 // Skip if this sub-register isn't defined.
458 continue;
459 HandlePhysRegKill(SubReg, MI);
460 }
461
462 if (MI)
463 Defs.push_back(Reg); // Remember this def.
464}
465
466void LiveVariables::UpdatePhysRegDefs(MachineInstr &MI,
467 SmallVectorImpl<Register> &Defs) {
468 while (!Defs.empty()) {
469 Register Reg = Defs.pop_back_val();
470 for (MCPhysReg SubReg : TRI->subregs_inclusive(Reg)) {
471 PhysRegDef[SubReg] = &MI;
472 PhysRegUse[SubReg] = nullptr;
473 }
474 }
475}
476
477void LiveVariables::runOnInstr(MachineInstr &MI,
478 SmallVectorImpl<Register> &Defs,
479 unsigned NumRegs) {
480 assert(!MI.isDebugOrPseudoInstr());
481 // Process all of the operands of the instruction...
482 unsigned NumOperandsToProcess = MI.getNumOperands();
483
484 // Unless it is a PHI node. In this case, ONLY process the DEF, not any
485 // of the uses. They will be handled in other basic blocks.
486 if (MI.isPHI())
487 NumOperandsToProcess = 1;
488
489 // Clear kill and dead markers. LV will recompute them.
493 for (unsigned i = 0; i != NumOperandsToProcess; ++i) {
494 MachineOperand &MO = MI.getOperand(i);
495 if (MO.isRegMask()) {
496 RegMasks.push_back(i);
497 continue;
498 }
499 if (!MO.isReg() || !MO.getReg())
500 continue;
501 Register MOReg = MO.getReg();
502 if (MO.isUse()) {
503 if (!(MOReg.isPhysical() && MRI->isReserved(MOReg)))
504 MO.setIsKill(false);
505 if (MO.readsReg())
506 UseRegs.push_back(MOReg);
507 } else {
508 assert(MO.isDef());
509 // FIXME: We should not remove any dead flags. However the MIPS RDDSP
510 // instruction needs it at the moment: http://llvm.org/PR27116.
511 if (MOReg.isPhysical() && !MRI->isReserved(MOReg))
512 MO.setIsDead(false);
513 DefRegs.push_back(MOReg);
514 }
515 }
516
517 MachineBasicBlock *MBB = MI.getParent();
518 // Process all uses.
519 for (Register MOReg : UseRegs) {
520 if (MOReg.isVirtual())
521 HandleVirtRegUse(MOReg, MBB, MI);
522 else if (!MRI->isReserved(MOReg))
523 HandlePhysRegUse(MOReg, MI);
524 }
525
526 // Process all masked registers. (Call clobbers).
527 for (unsigned Mask : RegMasks)
528 HandleRegMask(MI.getOperand(Mask), NumRegs);
529
530 // Process all defs.
531 for (Register MOReg : DefRegs) {
532 if (MOReg.isVirtual())
533 HandleVirtRegDef(MOReg, MI);
534 else if (!MRI->isReserved(MOReg))
535 HandlePhysRegDef(MOReg, &MI, Defs);
536 }
537 UpdatePhysRegDefs(MI, Defs);
538}
539
540void LiveVariables::runOnBlock(MachineBasicBlock *MBB, unsigned NumRegs) {
541 // Mark live-in registers as live-in.
543 for (const auto &LI : MBB->liveins()) {
544 assert(LI.PhysReg.isPhysical() &&
545 "Cannot have a live-in virtual register!");
546 HandlePhysRegDef(LI.PhysReg, nullptr, Defs);
547 }
548
549 // Loop over all of the instructions, processing them.
550 DistanceMap.clear();
551 unsigned Dist = 0;
552 for (MachineInstr &MI : *MBB) {
553 if (MI.isDebugOrPseudoInstr())
554 continue;
555 DistanceMap.insert(std::make_pair(&MI, Dist++));
556
557 runOnInstr(MI, Defs, NumRegs);
558 }
559
560 // Handle any virtual assignments from PHI nodes which might be at the
561 // bottom of this basic block. We check all of our successor blocks to see
562 // if they have PHI nodes, and if so, we simulate an assignment at the end
563 // of the current block.
564 if (!PHIVarInfo[MBB->getNumber()].empty()) {
565 SmallVectorImpl<Register> &VarInfoVec = PHIVarInfo[MBB->getNumber()];
566
567 for (Register I : VarInfoVec)
568 // Mark it alive only in the block we are representing.
569 MarkVirtRegAliveInBlock(getVarInfo(I), MRI->getVRegDef(I)->getParent(),
570 MBB);
571 }
572
573 // MachineCSE may CSE instructions which write to non-allocatable physical
574 // registers across MBBs. Remember if any reserved register is liveout.
575 SmallSet<unsigned, 4> LiveOuts;
576 for (const MachineBasicBlock *SuccMBB : MBB->successors()) {
577 if (SuccMBB->isEHPad())
578 continue;
579 for (const auto &LI : SuccMBB->liveins()) {
580 if (!TRI->isInAllocatableClass(LI.PhysReg))
581 // Ignore other live-ins, e.g. those that are live into landing pads.
582 LiveOuts.insert(LI.PhysReg);
583 }
584 }
585
586 // Loop over PhysRegDef / PhysRegUse, killing any registers that are
587 // available at the end of the basic block.
588 for (unsigned i = 0; i != NumRegs; ++i)
589 if ((PhysRegDef[i] || PhysRegUse[i]) && !LiveOuts.count(i))
590 HandlePhysRegDef(i, nullptr, Defs);
591}
592
593void LiveVariables::analyze(MachineFunction &mf) {
594 MF = &mf;
595 MRI = &mf.getRegInfo();
596 TRI = MF->getSubtarget().getRegisterInfo();
597
598 const unsigned NumRegs = TRI->getNumSupportedRegs(mf);
599 PhysRegDef.assign(NumRegs, nullptr);
600 PhysRegUse.assign(NumRegs, nullptr);
601 PHIVarInfo.resize(MF->getNumBlockIDs());
602
603 // FIXME: LiveIntervals will be updated to remove its dependence on
604 // LiveVariables to improve compilation time and eliminate bizarre pass
605 // dependencies. Until then, we can't change much in -O0.
606 if (!MRI->isSSA())
607 reportFatalUsageError("regalloc=... not currently supported with -O0");
608
609 analyzePHINodes(mf);
610
611 // Calculate live variable information in depth first order on the CFG of the
612 // function. This guarantees that we will see the definition of a virtual
613 // register before its uses due to dominance properties of SSA (except for PHI
614 // nodes, which are treated as a special case).
615 MachineBasicBlock *Entry = &MF->front();
616 df_iterator_default_set<MachineBasicBlock*,16> Visited;
617
618 for (MachineBasicBlock *MBB : depth_first_ext(Entry, Visited)) {
619 runOnBlock(MBB, NumRegs);
620
621 PhysRegDef.assign(NumRegs, nullptr);
622 PhysRegUse.assign(NumRegs, nullptr);
623 }
624
625 // Convert and transfer the dead / killed information we have gathered into
626 // VirtRegInfo onto MI's.
627 for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i) {
629 for (unsigned j = 0, e2 = VirtRegInfo[Reg].Kills.size(); j != e2; ++j)
630 if (VirtRegInfo[Reg].Kills[j] == MRI->getVRegDef(Reg))
631 VirtRegInfo[Reg].Kills[j]->addRegisterDead(Reg, TRI);
632 else
633 VirtRegInfo[Reg].Kills[j]->addRegisterKilled(Reg, TRI);
634 }
635
636 // Check to make sure there are no unreachable blocks in the MC CFG for the
637 // function. If so, it is due to a bug in the instruction selector or some
638 // other part of the code generator if this happens.
639#ifndef NDEBUG
640 for (const MachineBasicBlock &MBB : *MF)
641 assert(Visited.contains(&MBB) && "unreachable basic block found");
642#endif
643
644 PhysRegDef.clear();
645 PhysRegUse.clear();
646 PHIVarInfo.clear();
647}
648
650 assert(Reg.isVirtual());
651
652 VarInfo &VI = getVarInfo(Reg);
653 VI.AliveBlocks.clear();
654 VI.Kills.clear();
655
656 MachineInstr &DefMI = *MRI->getUniqueVRegDef(Reg);
657 MachineBasicBlock &DefBB = *DefMI.getParent();
658
659 // Initialize a worklist of BBs that Reg is live-to-end of. (Here
660 // "live-to-end" means Reg is live at the end of a block even if it is only
661 // live because of phi uses in a successor. This is different from isLiveOut()
662 // which does not consider phi uses.)
663 SmallVector<MachineBasicBlock *> LiveToEndBlocks;
664 SparseBitVector<> UseBlocks;
665 unsigned NumRealUses = 0;
666 for (auto &UseMO : MRI->use_nodbg_operands(Reg)) {
667 UseMO.setIsKill(false);
668 if (!UseMO.readsReg())
669 continue;
670 ++NumRealUses;
671 MachineInstr &UseMI = *UseMO.getParent();
672 MachineBasicBlock &UseBB = *UseMI.getParent();
673 UseBlocks.set(UseBB.getNumber());
674 if (UseMI.isPHI()) {
675 // If Reg is used in a phi then it is live-to-end of the corresponding
676 // predecessor.
677 unsigned Idx = UseMO.getOperandNo();
678 LiveToEndBlocks.push_back(UseMI.getOperand(Idx + 1).getMBB());
679 } else if (&UseBB == &DefBB) {
680 // A non-phi use in the same BB as the single def must come after the def.
681 } else {
682 // Otherwise Reg must be live-to-end of all predecessors.
683 LiveToEndBlocks.append(UseBB.pred_begin(), UseBB.pred_end());
684 }
685 }
686
687 // Handle the case where all uses have been removed.
688 if (NumRealUses == 0) {
689 VI.Kills.push_back(&DefMI);
690 DefMI.addRegisterDead(Reg, nullptr);
691 return;
692 }
693 DefMI.clearRegisterDeads(Reg);
694
695 // Iterate over the worklist adding blocks to AliveBlocks.
696 bool LiveToEndOfDefBB = false;
697 while (!LiveToEndBlocks.empty()) {
698 MachineBasicBlock &BB = *LiveToEndBlocks.pop_back_val();
699 if (&BB == &DefBB) {
700 LiveToEndOfDefBB = true;
701 continue;
702 }
703 if (VI.AliveBlocks.test(BB.getNumber()))
704 continue;
705 VI.AliveBlocks.set(BB.getNumber());
706 LiveToEndBlocks.append(BB.pred_begin(), BB.pred_end());
707 }
708
709 // Recompute kill flags. For each block in which Reg is used but is not
710 // live-through, find the last instruction that uses Reg. Ignore phi nodes
711 // because they should not be included in Kills.
712 for (unsigned UseBBNum : UseBlocks) {
713 if (VI.AliveBlocks.test(UseBBNum))
714 continue;
715 MachineBasicBlock &UseBB = *MF->getBlockNumbered(UseBBNum);
716 if (&UseBB == &DefBB && LiveToEndOfDefBB)
717 continue;
718 for (auto &MI : reverse(UseBB)) {
719 if (MI.isDebugOrPseudoInstr())
720 continue;
721 if (MI.isPHI())
722 break;
723 if (MI.readsVirtualRegister(Reg)) {
724 assert(!MI.killsRegister(Reg, /*TRI=*/nullptr));
725 MI.addRegisterKilled(Reg, nullptr);
726 VI.Kills.push_back(&MI);
727 break;
728 }
729 }
730 }
731}
732
733/// replaceKillInstruction - Update register kill info by replacing a kill
734/// instruction with a new one.
736 MachineInstr &NewMI) {
737 VarInfo &VI = getVarInfo(Reg);
738 llvm::replace(VI.Kills, &OldMI, &NewMI);
739}
740
741/// removeVirtualRegistersKilled - Remove all killed info for the specified
742/// instruction.
744 for (MachineOperand &MO : MI.operands()) {
745 if (MO.isReg() && MO.isKill()) {
746 MO.setIsKill(false);
747 Register Reg = MO.getReg();
748 if (Reg.isVirtual()) {
749 bool removed = getVarInfo(Reg).removeKill(MI);
750 assert(removed && "kill not in register's VarInfo?");
751 (void)removed;
752 }
753 }
754 }
755}
756
757/// analyzePHINodes - Gather information about the PHI nodes in here. In
758/// particular, we want to map the variable information of a virtual register
759/// which is used in a PHI node. We map that to the BB the vreg is coming from.
760///
761void LiveVariables::analyzePHINodes(const MachineFunction& Fn) {
762 for (const auto &MBB : Fn)
763 for (const auto &BBI : MBB) {
764 if (!BBI.isPHI())
765 break;
766 for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2)
767 if (BBI.getOperand(i).readsReg())
768 PHIVarInfo[BBI.getOperand(i + 1).getMBB()->getNumber()]
769 .push_back(BBI.getOperand(i).getReg());
770 }
771}
772
774 Register Reg, MachineRegisterInfo &MRI) {
775 unsigned Num = MBB.getNumber();
776
777 // Reg is live-through.
778 if (AliveBlocks.test(Num))
779 return true;
780
781 // Registers defined in MBB cannot be live in.
782 const MachineInstr *Def = MRI.getVRegDef(Reg);
783 if (Def && Def->getParent() == &MBB)
784 return false;
785
786 // Reg was not defined in MBB, was it killed here?
787 return findKill(&MBB);
788}
789
792
794 for (MachineInstr *MI : VI.Kills)
795 Kills.insert(MI->getParent());
796
797 // Loop over all of the successors of the basic block, checking to see if
798 // the value is either live in the block, or if it is killed in the block.
799 for (const MachineBasicBlock *SuccMBB : MBB.successors()) {
800 // Is it alive in this successor?
801 unsigned SuccIdx = SuccMBB->getNumber();
802 if (VI.AliveBlocks.test(SuccIdx))
803 return true;
804 // Or is it live because there is a use in a successor that kills it?
805 if (Kills.count(SuccMBB))
806 return true;
807 }
808
809 return false;
810}
811
812/// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
813/// variables that are live out of DomBB will be marked as passing live through
814/// BB.
816 MachineBasicBlock *DomBB,
817 MachineBasicBlock *SuccBB) {
818 const unsigned NumNew = BB->getNumber();
819
820 DenseSet<Register> Defs, Kills;
821
822 MachineBasicBlock::iterator BBI = SuccBB->begin(), BBE = SuccBB->end();
823 for (; BBI != BBE && BBI->isPHI(); ++BBI) {
824 // Record the def of the PHI node.
825 Defs.insert(BBI->getOperand(0).getReg());
826
827 // All registers used by PHI nodes in SuccBB must be live through BB.
828 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
829 if (BBI->getOperand(i+1).getMBB() == BB)
830 getVarInfo(BBI->getOperand(i).getReg()).AliveBlocks.set(NumNew);
831 }
832
833 // Record all vreg defs and kills of all instructions in SuccBB.
834 for (; BBI != BBE; ++BBI) {
835 for (const MachineOperand &Op : BBI->operands()) {
836 if (Op.isReg() && Op.getReg().isVirtual()) {
837 if (Op.isDef())
838 Defs.insert(Op.getReg());
839 else if (Op.isKill())
840 Kills.insert(Op.getReg());
841 }
842 }
843 }
844
845 // Update info for all live variables
846 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
848
849 // If the Defs is defined in the successor it can't be live in BB.
850 if (Defs.count(Reg))
851 continue;
852
853 // If the register is either killed in or live through SuccBB it's also live
854 // through BB.
855 VarInfo &VI = getVarInfo(Reg);
856 if (Kills.count(Reg) || VI.AliveBlocks.test(SuccBB->getNumber()))
857 VI.AliveBlocks.set(NumNew);
858 }
859}
860
861/// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All
862/// variables that are live out of DomBB will be marked as passing live through
863/// BB. LiveInSets[BB] is *not* updated (because it is not needed during
864/// PHIElimination).
866 MachineBasicBlock *DomBB,
867 MachineBasicBlock *SuccBB,
868 std::vector<SparseBitVector<>> &LiveInSets) {
869 const unsigned NumNew = BB->getNumber();
870
871 SparseBitVector<> &BV = LiveInSets[SuccBB->getNumber()];
872 for (unsigned R : BV) {
874 LiveVariables::VarInfo &VI = getVarInfo(VirtReg);
875 VI.AliveBlocks.set(NumNew);
876 }
877 // All registers used by PHI nodes in SuccBB must be live through BB.
878 for (MachineBasicBlock::iterator BBI = SuccBB->begin(),
879 BBE = SuccBB->end();
880 BBI != BBE && BBI->isPHI(); ++BBI) {
881 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)
882 if (BBI->getOperand(i + 1).getMBB() == BB &&
883 BBI->getOperand(i).readsReg())
884 getVarInfo(BBI->getOperand(i).getReg())
885 .AliveBlocks.set(NumNew);
886 }
887}
unsigned SubReg
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:661
This file defines the DenseSet and SmallDenseSet classes.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#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
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &)
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
LLVM_ABI void replaceKillInstruction(Register Reg, MachineInstr &OldMI, MachineInstr &NewMI)
replaceKillInstruction - Update register kill info by replacing a kill instruction with a new one.
LLVM_ABI void MarkVirtRegAliveInBlock(VarInfo &VRInfo, MachineBasicBlock *DefBlock, MachineBasicBlock *BB)
LLVM_ABI void removeVirtualRegistersKilled(MachineInstr &MI)
removeVirtualRegistersKilled - Remove all killed info for the specified instruction.
LLVM_ABI bool isLiveOut(Register Reg, const MachineBasicBlock &MBB)
isLiveOut - Determine if Reg is live out from MBB, when not considering PHI nodes.
LLVM_ABI void HandleVirtRegDef(Register reg, MachineInstr &MI)
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI void recomputeForSingleDefVirtReg(Register Reg)
Recompute liveness from scratch for a virtual register Reg that is known to have a single def that do...
LLVM_ABI void HandleVirtRegUse(Register reg, MachineBasicBlock *MBB, MachineInstr &MI)
LLVM_ABI VarInfo & getVarInfo(Register Reg)
getVarInfo - Return the VarInfo structure for the specified VIRTUAL register.
LLVM_ABI void addNewBlock(MachineBasicBlock *BB, MachineBasicBlock *DomBB, MachineBasicBlock *SuccBB)
addNewBlock - Add a new basic block BB between DomBB and SuccBB.
iterator_range< livein_iterator > liveins() const
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
iterator_range< succ_iterator > successors()
MachineInstrBundleIterator< MachineInstr > iterator
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Representation of each machine instruction.
LLVM_ABI void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
LLVM_ABI bool addRegisterKilled(Register IncomingReg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI kills a register.
MachineOperand * findRegisterDefOperand(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false)
Wrapper for findRegisterDefOperandIdx, it returns a pointer to the MachineOperand rather than an inde...
LLVM_ABI bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI defined a register without a use.
MachineOperand class - Representation of each machine instruction operand.
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
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)
void setIsKill(bool Val=true)
void setIsEarlyClobber(bool Val=true)
bool isEarlyClobber() const
Register getReg() const
getReg - Returns the register number.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
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
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition Register.h:72
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr unsigned id() const
Definition Register.h:100
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
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.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:175
void insert_range(Range &&R)
Definition SmallSet.h:195
bool erase(const T &V)
Definition SmallSet.h:199
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:183
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
void set(unsigned Idx)
bool test(unsigned Idx) const
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:180
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
@ Entry
Definition COFF.h:862
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
iterator_range< df_ext_iterator< T, SetTy > > depth_first_ext(const T &G, SetTy &S)
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
@ Kill
The last use of a register.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
auto reverse(ContainerTy &&C)
Definition STLExtras.h:406
LLVM_ABI char & UnreachableMachineBlockElimID
UnreachableMachineBlockElimination - This pass removes unreachable machine basic blocks.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1908
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
LLVM_ABI char & LiveVariablesID
LiveVariables pass - This pass computes the set of blocks in which each variable is life and sets mac...
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
VarInfo - This represents the regions where a virtual register is live in the program.
bool removeKill(MachineInstr &MI)
removeKill - Delete a kill corresponding to the specified machine instruction.
LLVM_ABI void dump() const
std::vector< MachineInstr * > Kills
Kills - List of MachineInstruction's which are the last use of this virtual register (kill it) in the...
SparseBitVector AliveBlocks
AliveBlocks - Set of blocks in which this value is alive completely through.
LLVM_ABI MachineInstr * findKill(const MachineBasicBlock *MBB) const
findKill - Find a kill instruction in MBB. Return NULL if none is found.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI bool isLiveIn(const MachineBasicBlock &MBB, Register Reg, MachineRegisterInfo &MRI)
isLiveIn - Is Reg live in to MBB?