1 //===- StackSlotColoring.cpp - Stack slot coloring 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 file implements the stack slot coloring pass. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/ADT/BitVector.h" 14 #include "llvm/ADT/SmallVector.h" 15 #include "llvm/ADT/Statistic.h" 16 #include "llvm/CodeGen/LiveInterval.h" 17 #include "llvm/CodeGen/LiveIntervals.h" 18 #include "llvm/CodeGen/LiveStacks.h" 19 #include "llvm/CodeGen/MachineBasicBlock.h" 20 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 21 #include "llvm/CodeGen/MachineFrameInfo.h" 22 #include "llvm/CodeGen/MachineFunction.h" 23 #include "llvm/CodeGen/MachineFunctionPass.h" 24 #include "llvm/CodeGen/MachineInstr.h" 25 #include "llvm/CodeGen/MachineMemOperand.h" 26 #include "llvm/CodeGen/MachineOperand.h" 27 #include "llvm/CodeGen/Passes.h" 28 #include "llvm/CodeGen/PseudoSourceValue.h" 29 #include "llvm/CodeGen/SlotIndexes.h" 30 #include "llvm/CodeGen/TargetInstrInfo.h" 31 #include "llvm/CodeGen/TargetRegisterInfo.h" 32 #include "llvm/CodeGen/TargetSubtargetInfo.h" 33 #include "llvm/InitializePasses.h" 34 #include "llvm/Pass.h" 35 #include "llvm/Support/Casting.h" 36 #include "llvm/Support/CommandLine.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include <algorithm> 40 #include <cassert> 41 #include <cstdint> 42 #include <iterator> 43 #include <vector> 44 45 using namespace llvm; 46 47 #define DEBUG_TYPE "stack-slot-coloring" 48 49 static cl::opt<bool> 50 DisableSharing("no-stack-slot-sharing", 51 cl::init(false), cl::Hidden, 52 cl::desc("Suppress slot sharing during stack coloring")); 53 54 static cl::opt<int> DCELimit("ssc-dce-limit", cl::init(-1), cl::Hidden); 55 56 STATISTIC(NumEliminated, "Number of stack slots eliminated due to coloring"); 57 STATISTIC(NumDead, "Number of trivially dead stack accesses eliminated"); 58 59 namespace { 60 61 class StackSlotColoring : public MachineFunctionPass { 62 LiveStacks* LS; 63 MachineFrameInfo *MFI; 64 const TargetInstrInfo *TII; 65 const MachineBlockFrequencyInfo *MBFI; 66 67 // SSIntervals - Spill slot intervals. 68 std::vector<LiveInterval*> SSIntervals; 69 70 // SSRefs - Keep a list of MachineMemOperands for each spill slot. 71 // MachineMemOperands can be shared between instructions, so we need 72 // to be careful that renames like [FI0, FI1] -> [FI1, FI2] do not 73 // become FI0 -> FI1 -> FI2. 74 SmallVector<SmallVector<MachineMemOperand *, 8>, 16> SSRefs; 75 76 // OrigAlignments - Alignments of stack objects before coloring. 77 SmallVector<Align, 16> OrigAlignments; 78 79 // OrigSizes - Sizess of stack objects before coloring. 80 SmallVector<unsigned, 16> OrigSizes; 81 82 // AllColors - If index is set, it's a spill slot, i.e. color. 83 // FIXME: This assumes PEI locate spill slot with smaller indices 84 // closest to stack pointer / frame pointer. Therefore, smaller 85 // index == better color. This is per stack ID. 86 SmallVector<BitVector, 2> AllColors; 87 88 // NextColor - Next "color" that's not yet used. This is per stack ID. 89 SmallVector<int, 2> NextColors = { -1 }; 90 91 // UsedColors - "Colors" that have been assigned. This is per stack ID 92 SmallVector<BitVector, 2> UsedColors; 93 94 // Assignments - Color to intervals mapping. 95 SmallVector<SmallVector<LiveInterval*,4>, 16> Assignments; 96 97 public: 98 static char ID; // Pass identification 99 100 StackSlotColoring() : MachineFunctionPass(ID) { 101 initializeStackSlotColoringPass(*PassRegistry::getPassRegistry()); 102 } 103 104 void getAnalysisUsage(AnalysisUsage &AU) const override { 105 AU.setPreservesCFG(); 106 AU.addRequired<SlotIndexes>(); 107 AU.addPreserved<SlotIndexes>(); 108 AU.addRequired<LiveStacks>(); 109 AU.addRequired<MachineBlockFrequencyInfo>(); 110 AU.addPreserved<MachineBlockFrequencyInfo>(); 111 AU.addPreservedID(MachineDominatorsID); 112 MachineFunctionPass::getAnalysisUsage(AU); 113 } 114 115 bool runOnMachineFunction(MachineFunction &MF) override; 116 117 private: 118 void InitializeSlots(); 119 void ScanForSpillSlotRefs(MachineFunction &MF); 120 bool OverlapWithAssignments(LiveInterval *li, int Color) const; 121 int ColorSlot(LiveInterval *li); 122 bool ColorSlots(MachineFunction &MF); 123 void RewriteInstruction(MachineInstr &MI, SmallVectorImpl<int> &SlotMapping, 124 MachineFunction &MF); 125 bool RemoveDeadStores(MachineBasicBlock* MBB); 126 }; 127 128 } // end anonymous namespace 129 130 char StackSlotColoring::ID = 0; 131 132 char &llvm::StackSlotColoringID = StackSlotColoring::ID; 133 134 INITIALIZE_PASS_BEGIN(StackSlotColoring, DEBUG_TYPE, 135 "Stack Slot Coloring", false, false) 136 INITIALIZE_PASS_DEPENDENCY(SlotIndexes) 137 INITIALIZE_PASS_DEPENDENCY(LiveStacks) 138 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 139 INITIALIZE_PASS_END(StackSlotColoring, DEBUG_TYPE, 140 "Stack Slot Coloring", false, false) 141 142 namespace { 143 144 // IntervalSorter - Comparison predicate that sort live intervals by 145 // their weight. 146 struct IntervalSorter { 147 bool operator()(LiveInterval* LHS, LiveInterval* RHS) const { 148 return LHS->weight() > RHS->weight(); 149 } 150 }; 151 152 } // end anonymous namespace 153 154 /// ScanForSpillSlotRefs - Scan all the machine instructions for spill slot 155 /// references and update spill slot weights. 156 void StackSlotColoring::ScanForSpillSlotRefs(MachineFunction &MF) { 157 SSRefs.resize(MFI->getObjectIndexEnd()); 158 159 // FIXME: Need the equivalent of MachineRegisterInfo for frameindex operands. 160 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end(); 161 MBBI != E; ++MBBI) { 162 MachineBasicBlock *MBB = &*MBBI; 163 for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end(); 164 MII != EE; ++MII) { 165 MachineInstr &MI = *MII; 166 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 167 MachineOperand &MO = MI.getOperand(i); 168 if (!MO.isFI()) 169 continue; 170 int FI = MO.getIndex(); 171 if (FI < 0) 172 continue; 173 if (!LS->hasInterval(FI)) 174 continue; 175 LiveInterval &li = LS->getInterval(FI); 176 if (!MI.isDebugValue()) 177 li.incrementWeight( 178 LiveIntervals::getSpillWeight(false, true, MBFI, MI)); 179 } 180 for (MachineInstr::mmo_iterator MMOI = MI.memoperands_begin(), 181 EE = MI.memoperands_end(); 182 MMOI != EE; ++MMOI) { 183 MachineMemOperand *MMO = *MMOI; 184 if (const FixedStackPseudoSourceValue *FSV = 185 dyn_cast_or_null<FixedStackPseudoSourceValue>( 186 MMO->getPseudoValue())) { 187 int FI = FSV->getFrameIndex(); 188 if (FI >= 0) 189 SSRefs[FI].push_back(MMO); 190 } 191 } 192 } 193 } 194 } 195 196 /// InitializeSlots - Process all spill stack slot liveintervals and add them 197 /// to a sorted (by weight) list. 198 void StackSlotColoring::InitializeSlots() { 199 int LastFI = MFI->getObjectIndexEnd(); 200 201 // There is always at least one stack ID. 202 AllColors.resize(1); 203 UsedColors.resize(1); 204 205 OrigAlignments.resize(LastFI); 206 OrigSizes.resize(LastFI); 207 AllColors[0].resize(LastFI); 208 UsedColors[0].resize(LastFI); 209 Assignments.resize(LastFI); 210 211 using Pair = std::iterator_traits<LiveStacks::iterator>::value_type; 212 213 SmallVector<Pair *, 16> Intervals; 214 215 Intervals.reserve(LS->getNumIntervals()); 216 for (auto &I : *LS) 217 Intervals.push_back(&I); 218 llvm::sort(Intervals, 219 [](Pair *LHS, Pair *RHS) { return LHS->first < RHS->first; }); 220 221 // Gather all spill slots into a list. 222 LLVM_DEBUG(dbgs() << "Spill slot intervals:\n"); 223 for (auto *I : Intervals) { 224 LiveInterval &li = I->second; 225 LLVM_DEBUG(li.dump()); 226 int FI = Register::stackSlot2Index(li.reg()); 227 if (MFI->isDeadObjectIndex(FI)) 228 continue; 229 230 SSIntervals.push_back(&li); 231 OrigAlignments[FI] = MFI->getObjectAlign(FI); 232 OrigSizes[FI] = MFI->getObjectSize(FI); 233 234 auto StackID = MFI->getStackID(FI); 235 if (StackID != 0) { 236 AllColors.resize(StackID + 1); 237 UsedColors.resize(StackID + 1); 238 AllColors[StackID].resize(LastFI); 239 UsedColors[StackID].resize(LastFI); 240 } 241 242 AllColors[StackID].set(FI); 243 } 244 LLVM_DEBUG(dbgs() << '\n'); 245 246 // Sort them by weight. 247 llvm::stable_sort(SSIntervals, IntervalSorter()); 248 249 NextColors.resize(AllColors.size()); 250 251 // Get first "color". 252 for (unsigned I = 0, E = AllColors.size(); I != E; ++I) 253 NextColors[I] = AllColors[I].find_first(); 254 } 255 256 /// OverlapWithAssignments - Return true if LiveInterval overlaps with any 257 /// LiveIntervals that have already been assigned to the specified color. 258 bool 259 StackSlotColoring::OverlapWithAssignments(LiveInterval *li, int Color) const { 260 const SmallVectorImpl<LiveInterval *> &OtherLIs = Assignments[Color]; 261 for (unsigned i = 0, e = OtherLIs.size(); i != e; ++i) { 262 LiveInterval *OtherLI = OtherLIs[i]; 263 if (OtherLI->overlaps(*li)) 264 return true; 265 } 266 return false; 267 } 268 269 /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot. 270 int StackSlotColoring::ColorSlot(LiveInterval *li) { 271 int Color = -1; 272 bool Share = false; 273 int FI = Register::stackSlot2Index(li->reg()); 274 uint8_t StackID = MFI->getStackID(FI); 275 276 if (!DisableSharing) { 277 278 // Check if it's possible to reuse any of the used colors. 279 Color = UsedColors[StackID].find_first(); 280 while (Color != -1) { 281 if (!OverlapWithAssignments(li, Color)) { 282 Share = true; 283 ++NumEliminated; 284 break; 285 } 286 Color = UsedColors[StackID].find_next(Color); 287 } 288 } 289 290 if (Color != -1 && MFI->getStackID(Color) != MFI->getStackID(FI)) { 291 LLVM_DEBUG(dbgs() << "cannot share FIs with different stack IDs\n"); 292 Share = false; 293 } 294 295 // Assign it to the first available color (assumed to be the best) if it's 296 // not possible to share a used color with other objects. 297 if (!Share) { 298 assert(NextColors[StackID] != -1 && "No more spill slots?"); 299 Color = NextColors[StackID]; 300 UsedColors[StackID].set(Color); 301 NextColors[StackID] = AllColors[StackID].find_next(NextColors[StackID]); 302 } 303 304 assert(MFI->getStackID(Color) == MFI->getStackID(FI)); 305 306 // Record the assignment. 307 Assignments[Color].push_back(li); 308 LLVM_DEBUG(dbgs() << "Assigning fi#" << FI << " to fi#" << Color << "\n"); 309 310 // Change size and alignment of the allocated slot. If there are multiple 311 // objects sharing the same slot, then make sure the size and alignment 312 // are large enough for all. 313 Align Alignment = OrigAlignments[FI]; 314 if (!Share || Alignment > MFI->getObjectAlign(Color)) 315 MFI->setObjectAlignment(Color, Alignment); 316 int64_t Size = OrigSizes[FI]; 317 if (!Share || Size > MFI->getObjectSize(Color)) 318 MFI->setObjectSize(Color, Size); 319 return Color; 320 } 321 322 /// Colorslots - Color all spill stack slots and rewrite all frameindex machine 323 /// operands in the function. 324 bool StackSlotColoring::ColorSlots(MachineFunction &MF) { 325 unsigned NumObjs = MFI->getObjectIndexEnd(); 326 SmallVector<int, 16> SlotMapping(NumObjs, -1); 327 SmallVector<float, 16> SlotWeights(NumObjs, 0.0); 328 SmallVector<SmallVector<int, 4>, 16> RevMap(NumObjs); 329 BitVector UsedColors(NumObjs); 330 331 LLVM_DEBUG(dbgs() << "Color spill slot intervals:\n"); 332 bool Changed = false; 333 for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) { 334 LiveInterval *li = SSIntervals[i]; 335 int SS = Register::stackSlot2Index(li->reg()); 336 int NewSS = ColorSlot(li); 337 assert(NewSS >= 0 && "Stack coloring failed?"); 338 SlotMapping[SS] = NewSS; 339 RevMap[NewSS].push_back(SS); 340 SlotWeights[NewSS] += li->weight(); 341 UsedColors.set(NewSS); 342 Changed |= (SS != NewSS); 343 } 344 345 LLVM_DEBUG(dbgs() << "\nSpill slots after coloring:\n"); 346 for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) { 347 LiveInterval *li = SSIntervals[i]; 348 int SS = Register::stackSlot2Index(li->reg()); 349 li->setWeight(SlotWeights[SS]); 350 } 351 // Sort them by new weight. 352 llvm::stable_sort(SSIntervals, IntervalSorter()); 353 354 #ifndef NDEBUG 355 for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) 356 LLVM_DEBUG(SSIntervals[i]->dump()); 357 LLVM_DEBUG(dbgs() << '\n'); 358 #endif 359 360 if (!Changed) 361 return false; 362 363 // Rewrite all MachineMemOperands. 364 for (unsigned SS = 0, SE = SSRefs.size(); SS != SE; ++SS) { 365 int NewFI = SlotMapping[SS]; 366 if (NewFI == -1 || (NewFI == (int)SS)) 367 continue; 368 369 const PseudoSourceValue *NewSV = MF.getPSVManager().getFixedStack(NewFI); 370 SmallVectorImpl<MachineMemOperand *> &RefMMOs = SSRefs[SS]; 371 for (unsigned i = 0, e = RefMMOs.size(); i != e; ++i) 372 RefMMOs[i]->setValue(NewSV); 373 } 374 375 // Rewrite all MO_FrameIndex operands. Look for dead stores. 376 for (MachineBasicBlock &MBB : MF) { 377 for (MachineInstr &MI : MBB) 378 RewriteInstruction(MI, SlotMapping, MF); 379 RemoveDeadStores(&MBB); 380 } 381 382 // Delete unused stack slots. 383 for (int StackID = 0, E = AllColors.size(); StackID != E; ++StackID) { 384 int NextColor = NextColors[StackID]; 385 while (NextColor != -1) { 386 LLVM_DEBUG(dbgs() << "Removing unused stack object fi#" << NextColor << "\n"); 387 MFI->RemoveStackObject(NextColor); 388 NextColor = AllColors[StackID].find_next(NextColor); 389 } 390 } 391 392 return true; 393 } 394 395 /// RewriteInstruction - Rewrite specified instruction by replacing references 396 /// to old frame index with new one. 397 void StackSlotColoring::RewriteInstruction(MachineInstr &MI, 398 SmallVectorImpl<int> &SlotMapping, 399 MachineFunction &MF) { 400 // Update the operands. 401 for (unsigned i = 0, ee = MI.getNumOperands(); i != ee; ++i) { 402 MachineOperand &MO = MI.getOperand(i); 403 if (!MO.isFI()) 404 continue; 405 int OldFI = MO.getIndex(); 406 if (OldFI < 0) 407 continue; 408 int NewFI = SlotMapping[OldFI]; 409 if (NewFI == -1 || NewFI == OldFI) 410 continue; 411 412 assert(MFI->getStackID(OldFI) == MFI->getStackID(NewFI)); 413 MO.setIndex(NewFI); 414 } 415 416 // The MachineMemOperands have already been updated. 417 } 418 419 /// RemoveDeadStores - Scan through a basic block and look for loads followed 420 /// by stores. If they're both using the same stack slot, then the store is 421 /// definitely dead. This could obviously be much more aggressive (consider 422 /// pairs with instructions between them), but such extensions might have a 423 /// considerable compile time impact. 424 bool StackSlotColoring::RemoveDeadStores(MachineBasicBlock* MBB) { 425 // FIXME: This could be much more aggressive, but we need to investigate 426 // the compile time impact of doing so. 427 bool changed = false; 428 429 SmallVector<MachineInstr*, 4> toErase; 430 431 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); 432 I != E; ++I) { 433 if (DCELimit != -1 && (int)NumDead >= DCELimit) 434 break; 435 int FirstSS, SecondSS; 436 if (TII->isStackSlotCopy(*I, FirstSS, SecondSS) && FirstSS == SecondSS && 437 FirstSS != -1) { 438 ++NumDead; 439 changed = true; 440 toErase.push_back(&*I); 441 continue; 442 } 443 444 MachineBasicBlock::iterator NextMI = std::next(I); 445 MachineBasicBlock::iterator ProbableLoadMI = I; 446 447 unsigned LoadReg = 0; 448 unsigned StoreReg = 0; 449 unsigned LoadSize = 0; 450 unsigned StoreSize = 0; 451 if (!(LoadReg = TII->isLoadFromStackSlot(*I, FirstSS, LoadSize))) 452 continue; 453 // Skip the ...pseudo debugging... instructions between a load and store. 454 while ((NextMI != E) && NextMI->isDebugInstr()) { 455 ++NextMI; 456 ++I; 457 } 458 if (NextMI == E) continue; 459 if (!(StoreReg = TII->isStoreToStackSlot(*NextMI, SecondSS, StoreSize))) 460 continue; 461 if (FirstSS != SecondSS || LoadReg != StoreReg || FirstSS == -1 || 462 LoadSize != StoreSize) 463 continue; 464 465 ++NumDead; 466 changed = true; 467 468 if (NextMI->findRegisterUseOperandIdx(LoadReg, true, nullptr) != -1) { 469 ++NumDead; 470 toErase.push_back(&*ProbableLoadMI); 471 } 472 473 toErase.push_back(&*NextMI); 474 ++I; 475 } 476 477 for (SmallVectorImpl<MachineInstr *>::iterator I = toErase.begin(), 478 E = toErase.end(); I != E; ++I) 479 (*I)->eraseFromParent(); 480 481 return changed; 482 } 483 484 bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) { 485 LLVM_DEBUG({ 486 dbgs() << "********** Stack Slot Coloring **********\n" 487 << "********** Function: " << MF.getName() << '\n'; 488 }); 489 490 if (skipFunction(MF.getFunction())) 491 return false; 492 493 MFI = &MF.getFrameInfo(); 494 TII = MF.getSubtarget().getInstrInfo(); 495 LS = &getAnalysis<LiveStacks>(); 496 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 497 498 bool Changed = false; 499 500 unsigned NumSlots = LS->getNumIntervals(); 501 if (NumSlots == 0) 502 // Nothing to do! 503 return false; 504 505 // If there are calls to setjmp or sigsetjmp, don't perform stack slot 506 // coloring. The stack could be modified before the longjmp is executed, 507 // resulting in the wrong value being used afterwards. (See 508 // <rdar://problem/8007500>.) 509 if (MF.exposesReturnsTwice()) 510 return false; 511 512 // Gather spill slot references 513 ScanForSpillSlotRefs(MF); 514 InitializeSlots(); 515 Changed = ColorSlots(MF); 516 517 for (int &Next : NextColors) 518 Next = -1; 519 520 SSIntervals.clear(); 521 for (unsigned i = 0, e = SSRefs.size(); i != e; ++i) 522 SSRefs[i].clear(); 523 SSRefs.clear(); 524 OrigAlignments.clear(); 525 OrigSizes.clear(); 526 AllColors.clear(); 527 UsedColors.clear(); 528 for (unsigned i = 0, e = Assignments.size(); i != e; ++i) 529 Assignments[i].clear(); 530 Assignments.clear(); 531 532 return Changed; 533 } 534