1 //===-- LiveVariables.cpp - Live Variable Analysis for Machine Code -------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the LiveVariable analysis pass. For each machine 11 // instruction in the function, this pass calculates the set of registers that 12 // are immediately dead after the instruction (i.e., the instruction calculates 13 // the value, but it is never used) and the set of registers that are used by 14 // the instruction, but are never used after the instruction (i.e., they are 15 // killed). 16 // 17 // This class computes live variables using are sparse implementation based on 18 // the machine code SSA form. This class computes live variable information for 19 // each virtual and _register allocatable_ physical register in a function. It 20 // uses the dominance properties of SSA form to efficiently compute live 21 // variables for virtual registers, and assumes that physical registers are only 22 // live within a single basic block (allowing it to do a single local analysis 23 // to resolve physical register lifetimes in each basic block). If a physical 24 // register is not register allocatable, it is not tracked. This is useful for 25 // things like the stack pointer and condition codes. 26 // 27 //===----------------------------------------------------------------------===// 28 29 #include "llvm/CodeGen/LiveVariables.h" 30 #include "llvm/CodeGen/MachineInstr.h" 31 #include "llvm/CodeGen/MachineRegisterInfo.h" 32 #include "llvm/CodeGen/Passes.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Target/TargetInstrInfo.h" 35 #include "llvm/Target/TargetMachine.h" 36 #include "llvm/ADT/DepthFirstIterator.h" 37 #include "llvm/ADT/SmallPtrSet.h" 38 #include "llvm/ADT/SmallSet.h" 39 #include "llvm/ADT/STLExtras.h" 40 #include <algorithm> 41 using namespace llvm; 42 43 char LiveVariables::ID = 0; 44 INITIALIZE_PASS_BEGIN(LiveVariables, "livevars", 45 "Live Variable Analysis", false, false) 46 INITIALIZE_PASS_DEPENDENCY(UnreachableMachineBlockElim) 47 INITIALIZE_PASS_END(LiveVariables, "livevars", 48 "Live Variable Analysis", false, false) 49 50 51 void LiveVariables::getAnalysisUsage(AnalysisUsage &AU) const { 52 AU.addRequiredID(UnreachableMachineBlockElimID); 53 AU.setPreservesAll(); 54 MachineFunctionPass::getAnalysisUsage(AU); 55 } 56 57 MachineInstr * 58 LiveVariables::VarInfo::findKill(const MachineBasicBlock *MBB) const { 59 for (unsigned i = 0, e = Kills.size(); i != e; ++i) 60 if (Kills[i]->getParent() == MBB) 61 return Kills[i]; 62 return NULL; 63 } 64 65 void LiveVariables::VarInfo::dump() const { 66 dbgs() << " Alive in blocks: "; 67 for (SparseBitVector<>::iterator I = AliveBlocks.begin(), 68 E = AliveBlocks.end(); I != E; ++I) 69 dbgs() << *I << ", "; 70 dbgs() << "\n Killed by:"; 71 if (Kills.empty()) 72 dbgs() << " No instructions.\n"; 73 else { 74 for (unsigned i = 0, e = Kills.size(); i != e; ++i) 75 dbgs() << "\n #" << i << ": " << *Kills[i]; 76 dbgs() << "\n"; 77 } 78 } 79 80 /// getVarInfo - Get (possibly creating) a VarInfo object for the given vreg. 81 LiveVariables::VarInfo &LiveVariables::getVarInfo(unsigned RegIdx) { 82 assert(TargetRegisterInfo::isVirtualRegister(RegIdx) && 83 "getVarInfo: not a virtual register!"); 84 VirtRegInfo.grow(RegIdx); 85 return VirtRegInfo[RegIdx]; 86 } 87 88 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo& VRInfo, 89 MachineBasicBlock *DefBlock, 90 MachineBasicBlock *MBB, 91 std::vector<MachineBasicBlock*> &WorkList) { 92 unsigned BBNum = MBB->getNumber(); 93 94 // Check to see if this basic block is one of the killing blocks. If so, 95 // remove it. 96 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i) 97 if (VRInfo.Kills[i]->getParent() == MBB) { 98 VRInfo.Kills.erase(VRInfo.Kills.begin()+i); // Erase entry 99 break; 100 } 101 102 if (MBB == DefBlock) return; // Terminate recursion 103 104 if (VRInfo.AliveBlocks.test(BBNum)) 105 return; // We already know the block is live 106 107 // Mark the variable known alive in this bb 108 VRInfo.AliveBlocks.set(BBNum); 109 110 WorkList.insert(WorkList.end(), MBB->pred_rbegin(), MBB->pred_rend()); 111 } 112 113 void LiveVariables::MarkVirtRegAliveInBlock(VarInfo &VRInfo, 114 MachineBasicBlock *DefBlock, 115 MachineBasicBlock *MBB) { 116 std::vector<MachineBasicBlock*> WorkList; 117 MarkVirtRegAliveInBlock(VRInfo, DefBlock, MBB, WorkList); 118 119 while (!WorkList.empty()) { 120 MachineBasicBlock *Pred = WorkList.back(); 121 WorkList.pop_back(); 122 MarkVirtRegAliveInBlock(VRInfo, DefBlock, Pred, WorkList); 123 } 124 } 125 126 void LiveVariables::HandleVirtRegUse(unsigned reg, MachineBasicBlock *MBB, 127 MachineInstr *MI) { 128 assert(MRI->getVRegDef(reg) && "Register use before def!"); 129 130 unsigned BBNum = MBB->getNumber(); 131 132 VarInfo& VRInfo = getVarInfo(reg); 133 VRInfo.NumUses++; 134 135 // Check to see if this basic block is already a kill block. 136 if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() == MBB) { 137 // Yes, this register is killed in this basic block already. Increase the 138 // live range by updating the kill instruction. 139 VRInfo.Kills.back() = MI; 140 return; 141 } 142 143 #ifndef NDEBUG 144 for (unsigned i = 0, e = VRInfo.Kills.size(); i != e; ++i) 145 assert(VRInfo.Kills[i]->getParent() != MBB && "entry should be at end!"); 146 #endif 147 148 // This situation can occur: 149 // 150 // ,------. 151 // | | 152 // | v 153 // | t2 = phi ... t1 ... 154 // | | 155 // | v 156 // | t1 = ... 157 // | ... = ... t1 ... 158 // | | 159 // `------' 160 // 161 // where there is a use in a PHI node that's a predecessor to the defining 162 // block. We don't want to mark all predecessors as having the value "alive" 163 // in this case. 164 if (MBB == MRI->getVRegDef(reg)->getParent()) return; 165 166 // Add a new kill entry for this basic block. If this virtual register is 167 // already marked as alive in this basic block, that means it is alive in at 168 // least one of the successor blocks, it's not a kill. 169 if (!VRInfo.AliveBlocks.test(BBNum)) 170 VRInfo.Kills.push_back(MI); 171 172 // Update all dominating blocks to mark them as "known live". 173 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), 174 E = MBB->pred_end(); PI != E; ++PI) 175 MarkVirtRegAliveInBlock(VRInfo, MRI->getVRegDef(reg)->getParent(), *PI); 176 } 177 178 void LiveVariables::HandleVirtRegDef(unsigned Reg, MachineInstr *MI) { 179 VarInfo &VRInfo = getVarInfo(Reg); 180 181 if (VRInfo.AliveBlocks.empty()) 182 // If vr is not alive in any block, then defaults to dead. 183 VRInfo.Kills.push_back(MI); 184 } 185 186 /// FindLastPartialDef - Return the last partial def of the specified register. 187 /// Also returns the sub-registers that're defined by the instruction. 188 MachineInstr *LiveVariables::FindLastPartialDef(unsigned Reg, 189 SmallSet<unsigned,4> &PartDefRegs) { 190 unsigned LastDefReg = 0; 191 unsigned LastDefDist = 0; 192 MachineInstr *LastDef = NULL; 193 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg); 194 unsigned SubReg = *SubRegs; ++SubRegs) { 195 MachineInstr *Def = PhysRegDef[SubReg]; 196 if (!Def) 197 continue; 198 unsigned Dist = DistanceMap[Def]; 199 if (Dist > LastDefDist) { 200 LastDefReg = SubReg; 201 LastDef = Def; 202 LastDefDist = Dist; 203 } 204 } 205 206 if (!LastDef) 207 return 0; 208 209 PartDefRegs.insert(LastDefReg); 210 for (unsigned i = 0, e = LastDef->getNumOperands(); i != e; ++i) { 211 MachineOperand &MO = LastDef->getOperand(i); 212 if (!MO.isReg() || !MO.isDef() || MO.getReg() == 0) 213 continue; 214 unsigned DefReg = MO.getReg(); 215 if (TRI->isSubRegister(Reg, DefReg)) { 216 PartDefRegs.insert(DefReg); 217 for (const unsigned *SubRegs = TRI->getSubRegisters(DefReg); 218 unsigned SubReg = *SubRegs; ++SubRegs) 219 PartDefRegs.insert(SubReg); 220 } 221 } 222 return LastDef; 223 } 224 225 /// HandlePhysRegUse - Turn previous partial def's into read/mod/writes. Add 226 /// implicit defs to a machine instruction if there was an earlier def of its 227 /// super-register. 228 void LiveVariables::HandlePhysRegUse(unsigned Reg, MachineInstr *MI) { 229 MachineInstr *LastDef = PhysRegDef[Reg]; 230 // If there was a previous use or a "full" def all is well. 231 if (!LastDef && !PhysRegUse[Reg]) { 232 // Otherwise, the last sub-register def implicitly defines this register. 233 // e.g. 234 // AH = 235 // AL = ... <imp-def EAX>, <imp-kill AH> 236 // = AH 237 // ... 238 // = EAX 239 // All of the sub-registers must have been defined before the use of Reg! 240 SmallSet<unsigned, 4> PartDefRegs; 241 MachineInstr *LastPartialDef = FindLastPartialDef(Reg, PartDefRegs); 242 // If LastPartialDef is NULL, it must be using a livein register. 243 if (LastPartialDef) { 244 LastPartialDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/, 245 true/*IsImp*/)); 246 PhysRegDef[Reg] = LastPartialDef; 247 SmallSet<unsigned, 8> Processed; 248 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg); 249 unsigned SubReg = *SubRegs; ++SubRegs) { 250 if (Processed.count(SubReg)) 251 continue; 252 if (PartDefRegs.count(SubReg)) 253 continue; 254 // This part of Reg was defined before the last partial def. It's killed 255 // here. 256 LastPartialDef->addOperand(MachineOperand::CreateReg(SubReg, 257 false/*IsDef*/, 258 true/*IsImp*/)); 259 PhysRegDef[SubReg] = LastPartialDef; 260 for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS) 261 Processed.insert(*SS); 262 } 263 } 264 } else if (LastDef && !PhysRegUse[Reg] && 265 !LastDef->findRegisterDefOperand(Reg)) 266 // Last def defines the super register, add an implicit def of reg. 267 LastDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/, 268 true/*IsImp*/)); 269 270 // Remember this use. 271 PhysRegUse[Reg] = MI; 272 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg); 273 unsigned SubReg = *SubRegs; ++SubRegs) 274 PhysRegUse[SubReg] = MI; 275 } 276 277 /// FindLastRefOrPartRef - Return the last reference or partial reference of 278 /// the specified register. 279 MachineInstr *LiveVariables::FindLastRefOrPartRef(unsigned Reg) { 280 MachineInstr *LastDef = PhysRegDef[Reg]; 281 MachineInstr *LastUse = PhysRegUse[Reg]; 282 if (!LastDef && !LastUse) 283 return 0; 284 285 MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef; 286 unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef]; 287 unsigned LastPartDefDist = 0; 288 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg); 289 unsigned SubReg = *SubRegs; ++SubRegs) { 290 MachineInstr *Def = PhysRegDef[SubReg]; 291 if (Def && Def != LastDef) { 292 // There was a def of this sub-register in between. This is a partial 293 // def, keep track of the last one. 294 unsigned Dist = DistanceMap[Def]; 295 if (Dist > LastPartDefDist) 296 LastPartDefDist = Dist; 297 } else if (MachineInstr *Use = PhysRegUse[SubReg]) { 298 unsigned Dist = DistanceMap[Use]; 299 if (Dist > LastRefOrPartRefDist) { 300 LastRefOrPartRefDist = Dist; 301 LastRefOrPartRef = Use; 302 } 303 } 304 } 305 306 return LastRefOrPartRef; 307 } 308 309 bool LiveVariables::HandlePhysRegKill(unsigned Reg, MachineInstr *MI) { 310 MachineInstr *LastDef = PhysRegDef[Reg]; 311 MachineInstr *LastUse = PhysRegUse[Reg]; 312 if (!LastDef && !LastUse) 313 return false; 314 315 MachineInstr *LastRefOrPartRef = LastUse ? LastUse : LastDef; 316 unsigned LastRefOrPartRefDist = DistanceMap[LastRefOrPartRef]; 317 // The whole register is used. 318 // AL = 319 // AH = 320 // 321 // = AX 322 // = AL, AX<imp-use, kill> 323 // AX = 324 // 325 // Or whole register is defined, but not used at all. 326 // AX<dead> = 327 // ... 328 // AX = 329 // 330 // Or whole register is defined, but only partly used. 331 // AX<dead> = AL<imp-def> 332 // = AL<kill> 333 // AX = 334 MachineInstr *LastPartDef = 0; 335 unsigned LastPartDefDist = 0; 336 SmallSet<unsigned, 8> PartUses; 337 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg); 338 unsigned SubReg = *SubRegs; ++SubRegs) { 339 MachineInstr *Def = PhysRegDef[SubReg]; 340 if (Def && Def != LastDef) { 341 // There was a def of this sub-register in between. This is a partial 342 // def, keep track of the last one. 343 unsigned Dist = DistanceMap[Def]; 344 if (Dist > LastPartDefDist) { 345 LastPartDefDist = Dist; 346 LastPartDef = Def; 347 } 348 continue; 349 } 350 if (MachineInstr *Use = PhysRegUse[SubReg]) { 351 PartUses.insert(SubReg); 352 for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS) 353 PartUses.insert(*SS); 354 unsigned Dist = DistanceMap[Use]; 355 if (Dist > LastRefOrPartRefDist) { 356 LastRefOrPartRefDist = Dist; 357 LastRefOrPartRef = Use; 358 } 359 } 360 } 361 362 if (!PhysRegUse[Reg]) { 363 // Partial uses. Mark register def dead and add implicit def of 364 // sub-registers which are used. 365 // EAX<dead> = op AL<imp-def> 366 // That is, EAX def is dead but AL def extends pass it. 367 PhysRegDef[Reg]->addRegisterDead(Reg, TRI, true); 368 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg); 369 unsigned SubReg = *SubRegs; ++SubRegs) { 370 if (!PartUses.count(SubReg)) 371 continue; 372 bool NeedDef = true; 373 if (PhysRegDef[Reg] == PhysRegDef[SubReg]) { 374 MachineOperand *MO = PhysRegDef[Reg]->findRegisterDefOperand(SubReg); 375 if (MO) { 376 NeedDef = false; 377 assert(!MO->isDead()); 378 } 379 } 380 if (NeedDef) 381 PhysRegDef[Reg]->addOperand(MachineOperand::CreateReg(SubReg, 382 true/*IsDef*/, true/*IsImp*/)); 383 MachineInstr *LastSubRef = FindLastRefOrPartRef(SubReg); 384 if (LastSubRef) 385 LastSubRef->addRegisterKilled(SubReg, TRI, true); 386 else { 387 LastRefOrPartRef->addRegisterKilled(SubReg, TRI, true); 388 PhysRegUse[SubReg] = LastRefOrPartRef; 389 for (const unsigned *SSRegs = TRI->getSubRegisters(SubReg); 390 unsigned SSReg = *SSRegs; ++SSRegs) 391 PhysRegUse[SSReg] = LastRefOrPartRef; 392 } 393 for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS) 394 PartUses.erase(*SS); 395 } 396 } else if (LastRefOrPartRef == PhysRegDef[Reg] && LastRefOrPartRef != MI) { 397 if (LastPartDef) 398 // The last partial def kills the register. 399 LastPartDef->addOperand(MachineOperand::CreateReg(Reg, false/*IsDef*/, 400 true/*IsImp*/, true/*IsKill*/)); 401 else { 402 MachineOperand *MO = 403 LastRefOrPartRef->findRegisterDefOperand(Reg, false, TRI); 404 bool NeedEC = MO->isEarlyClobber() && MO->getReg() != Reg; 405 // If the last reference is the last def, then it's not used at all. 406 // That is, unless we are currently processing the last reference itself. 407 LastRefOrPartRef->addRegisterDead(Reg, TRI, true); 408 if (NeedEC) { 409 // If we are adding a subreg def and the superreg def is marked early 410 // clobber, add an early clobber marker to the subreg def. 411 MO = LastRefOrPartRef->findRegisterDefOperand(Reg); 412 if (MO) 413 MO->setIsEarlyClobber(); 414 } 415 } 416 } else 417 LastRefOrPartRef->addRegisterKilled(Reg, TRI, true); 418 return true; 419 } 420 421 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI, 422 SmallVector<unsigned, 4> &Defs) { 423 // What parts of the register are previously defined? 424 SmallSet<unsigned, 32> Live; 425 if (PhysRegDef[Reg] || PhysRegUse[Reg]) { 426 Live.insert(Reg); 427 for (const unsigned *SS = TRI->getSubRegisters(Reg); *SS; ++SS) 428 Live.insert(*SS); 429 } else { 430 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg); 431 unsigned SubReg = *SubRegs; ++SubRegs) { 432 // If a register isn't itself defined, but all parts that make up of it 433 // are defined, then consider it also defined. 434 // e.g. 435 // AL = 436 // AH = 437 // = AX 438 if (Live.count(SubReg)) 439 continue; 440 if (PhysRegDef[SubReg] || PhysRegUse[SubReg]) { 441 Live.insert(SubReg); 442 for (const unsigned *SS = TRI->getSubRegisters(SubReg); *SS; ++SS) 443 Live.insert(*SS); 444 } 445 } 446 } 447 448 // Start from the largest piece, find the last time any part of the register 449 // is referenced. 450 HandlePhysRegKill(Reg, MI); 451 // Only some of the sub-registers are used. 452 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg); 453 unsigned SubReg = *SubRegs; ++SubRegs) { 454 if (!Live.count(SubReg)) 455 // Skip if this sub-register isn't defined. 456 continue; 457 HandlePhysRegKill(SubReg, MI); 458 } 459 460 if (MI) 461 Defs.push_back(Reg); // Remember this def. 462 } 463 464 void LiveVariables::UpdatePhysRegDefs(MachineInstr *MI, 465 SmallVector<unsigned, 4> &Defs) { 466 while (!Defs.empty()) { 467 unsigned Reg = Defs.back(); 468 Defs.pop_back(); 469 PhysRegDef[Reg] = MI; 470 PhysRegUse[Reg] = NULL; 471 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg); 472 unsigned SubReg = *SubRegs; ++SubRegs) { 473 PhysRegDef[SubReg] = MI; 474 PhysRegUse[SubReg] = NULL; 475 } 476 } 477 } 478 479 bool LiveVariables::runOnMachineFunction(MachineFunction &mf) { 480 MF = &mf; 481 MRI = &mf.getRegInfo(); 482 TRI = MF->getTarget().getRegisterInfo(); 483 484 ReservedRegisters = TRI->getReservedRegs(mf); 485 486 unsigned NumRegs = TRI->getNumRegs(); 487 PhysRegDef = new MachineInstr*[NumRegs]; 488 PhysRegUse = new MachineInstr*[NumRegs]; 489 PHIVarInfo = new SmallVector<unsigned, 4>[MF->getNumBlockIDs()]; 490 std::fill(PhysRegDef, PhysRegDef + NumRegs, (MachineInstr*)0); 491 std::fill(PhysRegUse, PhysRegUse + NumRegs, (MachineInstr*)0); 492 PHIJoins.clear(); 493 494 analyzePHINodes(mf); 495 496 // Calculate live variable information in depth first order on the CFG of the 497 // function. This guarantees that we will see the definition of a virtual 498 // register before its uses due to dominance properties of SSA (except for PHI 499 // nodes, which are treated as a special case). 500 MachineBasicBlock *Entry = MF->begin(); 501 SmallPtrSet<MachineBasicBlock*,16> Visited; 502 503 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> > 504 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited); 505 DFI != E; ++DFI) { 506 MachineBasicBlock *MBB = *DFI; 507 508 // Mark live-in registers as live-in. 509 SmallVector<unsigned, 4> Defs; 510 for (MachineBasicBlock::livein_iterator II = MBB->livein_begin(), 511 EE = MBB->livein_end(); II != EE; ++II) { 512 assert(TargetRegisterInfo::isPhysicalRegister(*II) && 513 "Cannot have a live-in virtual register!"); 514 HandlePhysRegDef(*II, 0, Defs); 515 } 516 517 // Loop over all of the instructions, processing them. 518 DistanceMap.clear(); 519 unsigned Dist = 0; 520 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); 521 I != E; ++I) { 522 MachineInstr *MI = I; 523 if (MI->isDebugValue()) 524 continue; 525 DistanceMap.insert(std::make_pair(MI, Dist++)); 526 527 // Process all of the operands of the instruction... 528 unsigned NumOperandsToProcess = MI->getNumOperands(); 529 530 // Unless it is a PHI node. In this case, ONLY process the DEF, not any 531 // of the uses. They will be handled in other basic blocks. 532 if (MI->isPHI()) 533 NumOperandsToProcess = 1; 534 535 // Clear kill and dead markers. LV will recompute them. 536 SmallVector<unsigned, 4> UseRegs; 537 SmallVector<unsigned, 4> DefRegs; 538 for (unsigned i = 0; i != NumOperandsToProcess; ++i) { 539 MachineOperand &MO = MI->getOperand(i); 540 if (!MO.isReg() || MO.getReg() == 0) 541 continue; 542 unsigned MOReg = MO.getReg(); 543 if (MO.isUse()) { 544 MO.setIsKill(false); 545 UseRegs.push_back(MOReg); 546 } else /*MO.isDef()*/ { 547 MO.setIsDead(false); 548 DefRegs.push_back(MOReg); 549 } 550 } 551 552 // Process all uses. 553 for (unsigned i = 0, e = UseRegs.size(); i != e; ++i) { 554 unsigned MOReg = UseRegs[i]; 555 if (TargetRegisterInfo::isVirtualRegister(MOReg)) 556 HandleVirtRegUse(MOReg, MBB, MI); 557 else if (!ReservedRegisters[MOReg]) 558 HandlePhysRegUse(MOReg, MI); 559 } 560 561 // Process all defs. 562 for (unsigned i = 0, e = DefRegs.size(); i != e; ++i) { 563 unsigned MOReg = DefRegs[i]; 564 if (TargetRegisterInfo::isVirtualRegister(MOReg)) 565 HandleVirtRegDef(MOReg, MI); 566 else if (!ReservedRegisters[MOReg]) 567 HandlePhysRegDef(MOReg, MI, Defs); 568 } 569 UpdatePhysRegDefs(MI, Defs); 570 } 571 572 // Handle any virtual assignments from PHI nodes which might be at the 573 // bottom of this basic block. We check all of our successor blocks to see 574 // if they have PHI nodes, and if so, we simulate an assignment at the end 575 // of the current block. 576 if (!PHIVarInfo[MBB->getNumber()].empty()) { 577 SmallVector<unsigned, 4>& VarInfoVec = PHIVarInfo[MBB->getNumber()]; 578 579 for (SmallVector<unsigned, 4>::iterator I = VarInfoVec.begin(), 580 E = VarInfoVec.end(); I != E; ++I) 581 // Mark it alive only in the block we are representing. 582 MarkVirtRegAliveInBlock(getVarInfo(*I),MRI->getVRegDef(*I)->getParent(), 583 MBB); 584 } 585 586 // Finally, if the last instruction in the block is a return, make sure to 587 // mark it as using all of the live-out values in the function. 588 // Things marked both call and return are tail calls; do not do this for 589 // them. The tail callee need not take the same registers as input 590 // that it produces as output, and there are dependencies for its input 591 // registers elsewhere. 592 if (!MBB->empty() && MBB->back().isReturn() 593 && !MBB->back().isCall()) { 594 MachineInstr *Ret = &MBB->back(); 595 596 for (MachineRegisterInfo::liveout_iterator 597 I = MF->getRegInfo().liveout_begin(), 598 E = MF->getRegInfo().liveout_end(); I != E; ++I) { 599 assert(TargetRegisterInfo::isPhysicalRegister(*I) && 600 "Cannot have a live-out virtual register!"); 601 HandlePhysRegUse(*I, Ret); 602 603 // Add live-out registers as implicit uses. 604 if (!Ret->readsRegister(*I)) 605 Ret->addOperand(MachineOperand::CreateReg(*I, false, true)); 606 } 607 } 608 609 // MachineCSE may CSE instructions which write to non-allocatable physical 610 // registers across MBBs. Remember if any reserved register is liveout. 611 SmallSet<unsigned, 4> LiveOuts; 612 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(), 613 SE = MBB->succ_end(); SI != SE; ++SI) { 614 MachineBasicBlock *SuccMBB = *SI; 615 if (SuccMBB->isLandingPad()) 616 continue; 617 for (MachineBasicBlock::livein_iterator LI = SuccMBB->livein_begin(), 618 LE = SuccMBB->livein_end(); LI != LE; ++LI) { 619 unsigned LReg = *LI; 620 if (!TRI->isInAllocatableClass(LReg)) 621 // Ignore other live-ins, e.g. those that are live into landing pads. 622 LiveOuts.insert(LReg); 623 } 624 } 625 626 // Loop over PhysRegDef / PhysRegUse, killing any registers that are 627 // available at the end of the basic block. 628 for (unsigned i = 0; i != NumRegs; ++i) 629 if ((PhysRegDef[i] || PhysRegUse[i]) && !LiveOuts.count(i)) 630 HandlePhysRegDef(i, 0, Defs); 631 632 std::fill(PhysRegDef, PhysRegDef + NumRegs, (MachineInstr*)0); 633 std::fill(PhysRegUse, PhysRegUse + NumRegs, (MachineInstr*)0); 634 } 635 636 // Convert and transfer the dead / killed information we have gathered into 637 // VirtRegInfo onto MI's. 638 for (unsigned i = 0, e1 = VirtRegInfo.size(); i != e1; ++i) { 639 const unsigned Reg = TargetRegisterInfo::index2VirtReg(i); 640 for (unsigned j = 0, e2 = VirtRegInfo[Reg].Kills.size(); j != e2; ++j) 641 if (VirtRegInfo[Reg].Kills[j] == MRI->getVRegDef(Reg)) 642 VirtRegInfo[Reg].Kills[j]->addRegisterDead(Reg, TRI); 643 else 644 VirtRegInfo[Reg].Kills[j]->addRegisterKilled(Reg, TRI); 645 } 646 647 // Check to make sure there are no unreachable blocks in the MC CFG for the 648 // function. If so, it is due to a bug in the instruction selector or some 649 // other part of the code generator if this happens. 650 #ifndef NDEBUG 651 for(MachineFunction::iterator i = MF->begin(), e = MF->end(); i != e; ++i) 652 assert(Visited.count(&*i) != 0 && "unreachable basic block found"); 653 #endif 654 655 delete[] PhysRegDef; 656 delete[] PhysRegUse; 657 delete[] PHIVarInfo; 658 659 return false; 660 } 661 662 /// replaceKillInstruction - Update register kill info by replacing a kill 663 /// instruction with a new one. 664 void LiveVariables::replaceKillInstruction(unsigned Reg, MachineInstr *OldMI, 665 MachineInstr *NewMI) { 666 VarInfo &VI = getVarInfo(Reg); 667 std::replace(VI.Kills.begin(), VI.Kills.end(), OldMI, NewMI); 668 } 669 670 /// removeVirtualRegistersKilled - Remove all killed info for the specified 671 /// instruction. 672 void LiveVariables::removeVirtualRegistersKilled(MachineInstr *MI) { 673 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 674 MachineOperand &MO = MI->getOperand(i); 675 if (MO.isReg() && MO.isKill()) { 676 MO.setIsKill(false); 677 unsigned Reg = MO.getReg(); 678 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 679 bool removed = getVarInfo(Reg).removeKill(MI); 680 assert(removed && "kill not in register's VarInfo?"); 681 (void)removed; 682 } 683 } 684 } 685 } 686 687 /// analyzePHINodes - Gather information about the PHI nodes in here. In 688 /// particular, we want to map the variable information of a virtual register 689 /// which is used in a PHI node. We map that to the BB the vreg is coming from. 690 /// 691 void LiveVariables::analyzePHINodes(const MachineFunction& Fn) { 692 for (MachineFunction::const_iterator I = Fn.begin(), E = Fn.end(); 693 I != E; ++I) 694 for (MachineBasicBlock::const_iterator BBI = I->begin(), BBE = I->end(); 695 BBI != BBE && BBI->isPHI(); ++BBI) 696 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) 697 PHIVarInfo[BBI->getOperand(i + 1).getMBB()->getNumber()] 698 .push_back(BBI->getOperand(i).getReg()); 699 } 700 701 bool LiveVariables::VarInfo::isLiveIn(const MachineBasicBlock &MBB, 702 unsigned Reg, 703 MachineRegisterInfo &MRI) { 704 unsigned Num = MBB.getNumber(); 705 706 // Reg is live-through. 707 if (AliveBlocks.test(Num)) 708 return true; 709 710 // Registers defined in MBB cannot be live in. 711 const MachineInstr *Def = MRI.getVRegDef(Reg); 712 if (Def && Def->getParent() == &MBB) 713 return false; 714 715 // Reg was not defined in MBB, was it killed here? 716 return findKill(&MBB); 717 } 718 719 bool LiveVariables::isLiveOut(unsigned Reg, const MachineBasicBlock &MBB) { 720 LiveVariables::VarInfo &VI = getVarInfo(Reg); 721 722 // Loop over all of the successors of the basic block, checking to see if 723 // the value is either live in the block, or if it is killed in the block. 724 SmallVector<MachineBasicBlock*, 8> OpSuccBlocks; 725 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(), 726 E = MBB.succ_end(); SI != E; ++SI) { 727 MachineBasicBlock *SuccMBB = *SI; 728 729 // Is it alive in this successor? 730 unsigned SuccIdx = SuccMBB->getNumber(); 731 if (VI.AliveBlocks.test(SuccIdx)) 732 return true; 733 OpSuccBlocks.push_back(SuccMBB); 734 } 735 736 // Check to see if this value is live because there is a use in a successor 737 // that kills it. 738 switch (OpSuccBlocks.size()) { 739 case 1: { 740 MachineBasicBlock *SuccMBB = OpSuccBlocks[0]; 741 for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i) 742 if (VI.Kills[i]->getParent() == SuccMBB) 743 return true; 744 break; 745 } 746 case 2: { 747 MachineBasicBlock *SuccMBB1 = OpSuccBlocks[0], *SuccMBB2 = OpSuccBlocks[1]; 748 for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i) 749 if (VI.Kills[i]->getParent() == SuccMBB1 || 750 VI.Kills[i]->getParent() == SuccMBB2) 751 return true; 752 break; 753 } 754 default: 755 std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end()); 756 for (unsigned i = 0, e = VI.Kills.size(); i != e; ++i) 757 if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(), 758 VI.Kills[i]->getParent())) 759 return true; 760 } 761 return false; 762 } 763 764 /// addNewBlock - Add a new basic block BB as an empty succcessor to DomBB. All 765 /// variables that are live out of DomBB will be marked as passing live through 766 /// BB. 767 void LiveVariables::addNewBlock(MachineBasicBlock *BB, 768 MachineBasicBlock *DomBB, 769 MachineBasicBlock *SuccBB) { 770 const unsigned NumNew = BB->getNumber(); 771 772 // All registers used by PHI nodes in SuccBB must be live through BB. 773 for (MachineBasicBlock::iterator BBI = SuccBB->begin(), 774 BBE = SuccBB->end(); BBI != BBE && BBI->isPHI(); ++BBI) 775 for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2) 776 if (BBI->getOperand(i+1).getMBB() == BB) 777 getVarInfo(BBI->getOperand(i).getReg()).AliveBlocks.set(NumNew); 778 779 // Update info for all live variables 780 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 781 unsigned Reg = TargetRegisterInfo::index2VirtReg(i); 782 VarInfo &VI = getVarInfo(Reg); 783 if (!VI.AliveBlocks.test(NumNew) && VI.isLiveIn(*SuccBB, Reg, *MRI)) 784 VI.AliveBlocks.set(NumNew); 785 } 786 } 787