1 //===-- StackColoring.cpp -------------------------------------------------===// 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 pass implements the stack-coloring optimization that looks for 11 // lifetime markers machine instructions (LIFESTART_BEGIN and LIFESTART_END), 12 // which represent the possible lifetime of stack slots. It attempts to 13 // merge disjoint stack slots and reduce the used stack space. 14 // NOTE: This pass is not StackSlotColoring, which optimizes spill slots. 15 // 16 // TODO: In the future we plan to improve stack coloring in the following ways: 17 // 1. Allow merging multiple small slots into a single larger slot at different 18 // offsets. 19 // 2. Merge this pass with StackSlotColoring and allow merging of allocas with 20 // spill slots. 21 // 22 //===----------------------------------------------------------------------===// 23 24 #define DEBUG_TYPE "stackcoloring" 25 #include "llvm/CodeGen/Passes.h" 26 #include "llvm/ADT/BitVector.h" 27 #include "llvm/ADT/DepthFirstIterator.h" 28 #include "llvm/ADT/PostOrderIterator.h" 29 #include "llvm/ADT/SetVector.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/SparseSet.h" 32 #include "llvm/ADT/Statistic.h" 33 #include "llvm/Analysis/ValueTracking.h" 34 #include "llvm/CodeGen/LiveInterval.h" 35 #include "llvm/CodeGen/MachineBasicBlock.h" 36 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 37 #include "llvm/CodeGen/MachineDominators.h" 38 #include "llvm/CodeGen/MachineFrameInfo.h" 39 #include "llvm/CodeGen/MachineFunctionPass.h" 40 #include "llvm/CodeGen/MachineLoopInfo.h" 41 #include "llvm/CodeGen/MachineMemOperand.h" 42 #include "llvm/CodeGen/MachineModuleInfo.h" 43 #include "llvm/CodeGen/MachineRegisterInfo.h" 44 #include "llvm/CodeGen/PseudoSourceValue.h" 45 #include "llvm/CodeGen/SlotIndexes.h" 46 #include "llvm/CodeGen/StackProtector.h" 47 #include "llvm/IR/DebugInfo.h" 48 #include "llvm/IR/Dominators.h" 49 #include "llvm/IR/Function.h" 50 #include "llvm/IR/Instructions.h" 51 #include "llvm/IR/Module.h" 52 #include "llvm/MC/MCInstrItineraries.h" 53 #include "llvm/Support/CommandLine.h" 54 #include "llvm/Support/Debug.h" 55 #include "llvm/Support/raw_ostream.h" 56 #include "llvm/Target/TargetInstrInfo.h" 57 #include "llvm/Target/TargetRegisterInfo.h" 58 59 using namespace llvm; 60 61 static cl::opt<bool> 62 DisableColoring("no-stack-coloring", 63 cl::init(false), cl::Hidden, 64 cl::desc("Disable stack coloring")); 65 66 /// The user may write code that uses allocas outside of the declared lifetime 67 /// zone. This can happen when the user returns a reference to a local 68 /// data-structure. We can detect these cases and decide not to optimize the 69 /// code. If this flag is enabled, we try to save the user. 70 static cl::opt<bool> 71 ProtectFromEscapedAllocas("protect-from-escaped-allocas", 72 cl::init(false), cl::Hidden, 73 cl::desc("Do not optimize lifetime zones that " 74 "are broken")); 75 76 STATISTIC(NumMarkerSeen, "Number of lifetime markers found."); 77 STATISTIC(StackSpaceSaved, "Number of bytes saved due to merging slots."); 78 STATISTIC(StackSlotMerged, "Number of stack slot merged."); 79 STATISTIC(EscapedAllocas, "Number of allocas that escaped the lifetime region"); 80 81 //===----------------------------------------------------------------------===// 82 // StackColoring Pass 83 //===----------------------------------------------------------------------===// 84 85 namespace { 86 /// StackColoring - A machine pass for merging disjoint stack allocations, 87 /// marked by the LIFETIME_START and LIFETIME_END pseudo instructions. 88 class StackColoring : public MachineFunctionPass { 89 MachineFrameInfo *MFI; 90 MachineFunction *MF; 91 92 /// A class representing liveness information for a single basic block. 93 /// Each bit in the BitVector represents the liveness property 94 /// for a different stack slot. 95 struct BlockLifetimeInfo { 96 /// Which slots BEGINs in each basic block. 97 BitVector Begin; 98 /// Which slots ENDs in each basic block. 99 BitVector End; 100 /// Which slots are marked as LIVE_IN, coming into each basic block. 101 BitVector LiveIn; 102 /// Which slots are marked as LIVE_OUT, coming out of each basic block. 103 BitVector LiveOut; 104 }; 105 106 /// Maps active slots (per bit) for each basic block. 107 typedef DenseMap<const MachineBasicBlock*, BlockLifetimeInfo> LivenessMap; 108 LivenessMap BlockLiveness; 109 110 /// Maps serial numbers to basic blocks. 111 DenseMap<const MachineBasicBlock*, int> BasicBlocks; 112 /// Maps basic blocks to a serial number. 113 SmallVector<const MachineBasicBlock*, 8> BasicBlockNumbering; 114 115 /// Maps liveness intervals for each slot. 116 SmallVector<std::unique_ptr<LiveInterval>, 16> Intervals; 117 /// VNInfo is used for the construction of LiveIntervals. 118 VNInfo::Allocator VNInfoAllocator; 119 /// SlotIndex analysis object. 120 SlotIndexes *Indexes; 121 /// The stack protector object. 122 StackProtector *SP; 123 124 /// The list of lifetime markers found. These markers are to be removed 125 /// once the coloring is done. 126 SmallVector<MachineInstr*, 8> Markers; 127 128 public: 129 static char ID; 130 StackColoring() : MachineFunctionPass(ID) { 131 initializeStackColoringPass(*PassRegistry::getPassRegistry()); 132 } 133 void getAnalysisUsage(AnalysisUsage &AU) const override; 134 bool runOnMachineFunction(MachineFunction &MF) override; 135 136 private: 137 /// Debug. 138 void dump() const; 139 140 /// Removes all of the lifetime marker instructions from the function. 141 /// \returns true if any markers were removed. 142 bool removeAllMarkers(); 143 144 /// Scan the machine function and find all of the lifetime markers. 145 /// Record the findings in the BEGIN and END vectors. 146 /// \returns the number of markers found. 147 unsigned collectMarkers(unsigned NumSlot); 148 149 /// Perform the dataflow calculation and calculate the lifetime for each of 150 /// the slots, based on the BEGIN/END vectors. Set the LifetimeLIVE_IN and 151 /// LifetimeLIVE_OUT maps that represent which stack slots are live coming 152 /// in and out blocks. 153 void calculateLocalLiveness(); 154 155 /// Construct the LiveIntervals for the slots. 156 void calculateLiveIntervals(unsigned NumSlots); 157 158 /// Go over the machine function and change instructions which use stack 159 /// slots to use the joint slots. 160 void remapInstructions(DenseMap<int, int> &SlotRemap); 161 162 /// The input program may contain instructions which are not inside lifetime 163 /// markers. This can happen due to a bug in the compiler or due to a bug in 164 /// user code (for example, returning a reference to a local variable). 165 /// This procedure checks all of the instructions in the function and 166 /// invalidates lifetime ranges which do not contain all of the instructions 167 /// which access that frame slot. 168 void removeInvalidSlotRanges(); 169 170 /// Map entries which point to other entries to their destination. 171 /// A->B->C becomes A->C. 172 void expungeSlotMap(DenseMap<int, int> &SlotRemap, unsigned NumSlots); 173 }; 174 } // end anonymous namespace 175 176 char StackColoring::ID = 0; 177 char &llvm::StackColoringID = StackColoring::ID; 178 179 INITIALIZE_PASS_BEGIN(StackColoring, 180 "stack-coloring", "Merge disjoint stack slots", false, false) 181 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 182 INITIALIZE_PASS_DEPENDENCY(SlotIndexes) 183 INITIALIZE_PASS_DEPENDENCY(StackProtector) 184 INITIALIZE_PASS_END(StackColoring, 185 "stack-coloring", "Merge disjoint stack slots", false, false) 186 187 void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const { 188 AU.addRequired<MachineDominatorTree>(); 189 AU.addPreserved<MachineDominatorTree>(); 190 AU.addRequired<SlotIndexes>(); 191 AU.addRequired<StackProtector>(); 192 MachineFunctionPass::getAnalysisUsage(AU); 193 } 194 195 void StackColoring::dump() const { 196 for (MachineBasicBlock *MBB : depth_first(MF)) { 197 DEBUG(dbgs() << "Inspecting block #" << BasicBlocks.lookup(MBB) << " [" 198 << MBB->getName() << "]\n"); 199 200 LivenessMap::const_iterator BI = BlockLiveness.find(MBB); 201 assert(BI != BlockLiveness.end() && "Block not found"); 202 const BlockLifetimeInfo &BlockInfo = BI->second; 203 204 DEBUG(dbgs()<<"BEGIN : {"); 205 for (unsigned i=0; i < BlockInfo.Begin.size(); ++i) 206 DEBUG(dbgs()<<BlockInfo.Begin.test(i)<<" "); 207 DEBUG(dbgs()<<"}\n"); 208 209 DEBUG(dbgs()<<"END : {"); 210 for (unsigned i=0; i < BlockInfo.End.size(); ++i) 211 DEBUG(dbgs()<<BlockInfo.End.test(i)<<" "); 212 213 DEBUG(dbgs()<<"}\n"); 214 215 DEBUG(dbgs()<<"LIVE_IN: {"); 216 for (unsigned i=0; i < BlockInfo.LiveIn.size(); ++i) 217 DEBUG(dbgs()<<BlockInfo.LiveIn.test(i)<<" "); 218 219 DEBUG(dbgs()<<"}\n"); 220 DEBUG(dbgs()<<"LIVEOUT: {"); 221 for (unsigned i=0; i < BlockInfo.LiveOut.size(); ++i) 222 DEBUG(dbgs()<<BlockInfo.LiveOut.test(i)<<" "); 223 DEBUG(dbgs()<<"}\n"); 224 } 225 } 226 227 unsigned StackColoring::collectMarkers(unsigned NumSlot) { 228 unsigned MarkersFound = 0; 229 // Scan the function to find all lifetime markers. 230 // NOTE: We use the a reverse-post-order iteration to ensure that we obtain a 231 // deterministic numbering, and because we'll need a post-order iteration 232 // later for solving the liveness dataflow problem. 233 for (MachineBasicBlock *MBB : depth_first(MF)) { 234 235 // Assign a serial number to this basic block. 236 BasicBlocks[MBB] = BasicBlockNumbering.size(); 237 BasicBlockNumbering.push_back(MBB); 238 239 // Keep a reference to avoid repeated lookups. 240 BlockLifetimeInfo &BlockInfo = BlockLiveness[MBB]; 241 242 BlockInfo.Begin.resize(NumSlot); 243 BlockInfo.End.resize(NumSlot); 244 245 for (MachineInstr &MI : *MBB) { 246 if (MI.getOpcode() != TargetOpcode::LIFETIME_START && 247 MI.getOpcode() != TargetOpcode::LIFETIME_END) 248 continue; 249 250 Markers.push_back(&MI); 251 252 bool IsStart = MI.getOpcode() == TargetOpcode::LIFETIME_START; 253 const MachineOperand &MO = MI.getOperand(0); 254 unsigned Slot = MO.getIndex(); 255 256 MarkersFound++; 257 258 const AllocaInst *Allocation = MFI->getObjectAllocation(Slot); 259 if (Allocation) { 260 DEBUG(dbgs()<<"Found a lifetime marker for slot #"<<Slot<< 261 " with allocation: "<< Allocation->getName()<<"\n"); 262 } 263 264 if (IsStart) { 265 BlockInfo.Begin.set(Slot); 266 } else { 267 if (BlockInfo.Begin.test(Slot)) { 268 // Allocas that start and end within a single block are handled 269 // specially when computing the LiveIntervals to avoid pessimizing 270 // the liveness propagation. 271 BlockInfo.Begin.reset(Slot); 272 } else { 273 BlockInfo.End.set(Slot); 274 } 275 } 276 } 277 } 278 279 // Update statistics. 280 NumMarkerSeen += MarkersFound; 281 return MarkersFound; 282 } 283 284 void StackColoring::calculateLocalLiveness() { 285 // Perform a standard reverse dataflow computation to solve for 286 // global liveness. The BEGIN set here is equivalent to KILL in the standard 287 // formulation, and END is equivalent to GEN. The result of this computation 288 // is a map from blocks to bitvectors where the bitvectors represent which 289 // allocas are live in/out of that block. 290 SmallPtrSet<const MachineBasicBlock*, 8> BBSet(BasicBlockNumbering.begin(), 291 BasicBlockNumbering.end()); 292 unsigned NumSSMIters = 0; 293 bool changed = true; 294 while (changed) { 295 changed = false; 296 ++NumSSMIters; 297 298 SmallPtrSet<const MachineBasicBlock*, 8> NextBBSet; 299 300 for (const MachineBasicBlock *BB : BasicBlockNumbering) { 301 if (!BBSet.count(BB)) continue; 302 303 // Use an iterator to avoid repeated lookups. 304 LivenessMap::iterator BI = BlockLiveness.find(BB); 305 assert(BI != BlockLiveness.end() && "Block not found"); 306 BlockLifetimeInfo &BlockInfo = BI->second; 307 308 BitVector LocalLiveIn; 309 BitVector LocalLiveOut; 310 311 // Forward propagation from begins to ends. 312 for (MachineBasicBlock::const_pred_iterator PI = BB->pred_begin(), 313 PE = BB->pred_end(); PI != PE; ++PI) { 314 LivenessMap::const_iterator I = BlockLiveness.find(*PI); 315 assert(I != BlockLiveness.end() && "Predecessor not found"); 316 LocalLiveIn |= I->second.LiveOut; 317 } 318 LocalLiveIn |= BlockInfo.End; 319 LocalLiveIn.reset(BlockInfo.Begin); 320 321 // Reverse propagation from ends to begins. 322 for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(), 323 SE = BB->succ_end(); SI != SE; ++SI) { 324 LivenessMap::const_iterator I = BlockLiveness.find(*SI); 325 assert(I != BlockLiveness.end() && "Successor not found"); 326 LocalLiveOut |= I->second.LiveIn; 327 } 328 LocalLiveOut |= BlockInfo.Begin; 329 LocalLiveOut.reset(BlockInfo.End); 330 331 LocalLiveIn |= LocalLiveOut; 332 LocalLiveOut |= LocalLiveIn; 333 334 // After adopting the live bits, we need to turn-off the bits which 335 // are de-activated in this block. 336 LocalLiveOut.reset(BlockInfo.End); 337 LocalLiveIn.reset(BlockInfo.Begin); 338 339 // If we have both BEGIN and END markers in the same basic block then 340 // we know that the BEGIN marker comes after the END, because we already 341 // handle the case where the BEGIN comes before the END when collecting 342 // the markers (and building the BEGIN/END vectore). 343 // Want to enable the LIVE_IN and LIVE_OUT of slots that have both 344 // BEGIN and END because it means that the value lives before and after 345 // this basic block. 346 BitVector LocalEndBegin = BlockInfo.End; 347 LocalEndBegin &= BlockInfo.Begin; 348 LocalLiveIn |= LocalEndBegin; 349 LocalLiveOut |= LocalEndBegin; 350 351 if (LocalLiveIn.test(BlockInfo.LiveIn)) { 352 changed = true; 353 BlockInfo.LiveIn |= LocalLiveIn; 354 355 NextBBSet.insert(BB->pred_begin(), BB->pred_end()); 356 } 357 358 if (LocalLiveOut.test(BlockInfo.LiveOut)) { 359 changed = true; 360 BlockInfo.LiveOut |= LocalLiveOut; 361 362 NextBBSet.insert(BB->succ_begin(), BB->succ_end()); 363 } 364 } 365 366 BBSet = NextBBSet; 367 }// while changed. 368 } 369 370 void StackColoring::calculateLiveIntervals(unsigned NumSlots) { 371 SmallVector<SlotIndex, 16> Starts; 372 SmallVector<SlotIndex, 16> Finishes; 373 374 // For each block, find which slots are active within this block 375 // and update the live intervals. 376 for (const MachineBasicBlock &MBB : *MF) { 377 Starts.clear(); 378 Starts.resize(NumSlots); 379 Finishes.clear(); 380 Finishes.resize(NumSlots); 381 382 // Create the interval for the basic blocks with lifetime markers in them. 383 for (const MachineInstr *MI : Markers) { 384 if (MI->getParent() != &MBB) 385 continue; 386 387 assert((MI->getOpcode() == TargetOpcode::LIFETIME_START || 388 MI->getOpcode() == TargetOpcode::LIFETIME_END) && 389 "Invalid Lifetime marker"); 390 391 bool IsStart = MI->getOpcode() == TargetOpcode::LIFETIME_START; 392 const MachineOperand &Mo = MI->getOperand(0); 393 int Slot = Mo.getIndex(); 394 assert(Slot >= 0 && "Invalid slot"); 395 396 SlotIndex ThisIndex = Indexes->getInstructionIndex(MI); 397 398 if (IsStart) { 399 if (!Starts[Slot].isValid() || Starts[Slot] > ThisIndex) 400 Starts[Slot] = ThisIndex; 401 } else { 402 if (!Finishes[Slot].isValid() || Finishes[Slot] < ThisIndex) 403 Finishes[Slot] = ThisIndex; 404 } 405 } 406 407 // Create the interval of the blocks that we previously found to be 'alive'. 408 BlockLifetimeInfo &MBBLiveness = BlockLiveness[&MBB]; 409 for (int pos = MBBLiveness.LiveIn.find_first(); pos != -1; 410 pos = MBBLiveness.LiveIn.find_next(pos)) { 411 Starts[pos] = Indexes->getMBBStartIdx(&MBB); 412 } 413 for (int pos = MBBLiveness.LiveOut.find_first(); pos != -1; 414 pos = MBBLiveness.LiveOut.find_next(pos)) { 415 Finishes[pos] = Indexes->getMBBEndIdx(&MBB); 416 } 417 418 for (unsigned i = 0; i < NumSlots; ++i) { 419 assert(Starts[i].isValid() == Finishes[i].isValid() && "Unmatched range"); 420 if (!Starts[i].isValid()) 421 continue; 422 423 assert(Starts[i] && Finishes[i] && "Invalid interval"); 424 VNInfo *ValNum = Intervals[i]->getValNumInfo(0); 425 SlotIndex S = Starts[i]; 426 SlotIndex F = Finishes[i]; 427 if (S < F) { 428 // We have a single consecutive region. 429 Intervals[i]->addSegment(LiveInterval::Segment(S, F, ValNum)); 430 } else { 431 // We have two non-consecutive regions. This happens when 432 // LIFETIME_START appears after the LIFETIME_END marker. 433 SlotIndex NewStart = Indexes->getMBBStartIdx(&MBB); 434 SlotIndex NewFin = Indexes->getMBBEndIdx(&MBB); 435 Intervals[i]->addSegment(LiveInterval::Segment(NewStart, F, ValNum)); 436 Intervals[i]->addSegment(LiveInterval::Segment(S, NewFin, ValNum)); 437 } 438 } 439 } 440 } 441 442 bool StackColoring::removeAllMarkers() { 443 unsigned Count = 0; 444 for (MachineInstr *MI : Markers) { 445 MI->eraseFromParent(); 446 Count++; 447 } 448 Markers.clear(); 449 450 DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n"); 451 return Count; 452 } 453 454 void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) { 455 unsigned FixedInstr = 0; 456 unsigned FixedMemOp = 0; 457 unsigned FixedDbg = 0; 458 MachineModuleInfo *MMI = &MF->getMMI(); 459 460 // Remap debug information that refers to stack slots. 461 for (auto &VI : MMI->getVariableDbgInfo()) { 462 if (!VI.Var) 463 continue; 464 if (SlotRemap.count(VI.Slot)) { 465 DEBUG(dbgs()<<"Remapping debug info for ["<<VI.Var->getName()<<"].\n"); 466 VI.Slot = SlotRemap[VI.Slot]; 467 FixedDbg++; 468 } 469 } 470 471 // Keep a list of *allocas* which need to be remapped. 472 DenseMap<const AllocaInst*, const AllocaInst*> Allocas; 473 for (const std::pair<int, int> &SI : SlotRemap) { 474 const AllocaInst *From = MFI->getObjectAllocation(SI.first); 475 const AllocaInst *To = MFI->getObjectAllocation(SI.second); 476 assert(To && From && "Invalid allocation object"); 477 Allocas[From] = To; 478 479 // AA might be used later for instruction scheduling, and we need it to be 480 // able to deduce the correct aliasing releationships between pointers 481 // derived from the alloca being remapped and the target of that remapping. 482 // The only safe way, without directly informing AA about the remapping 483 // somehow, is to directly update the IR to reflect the change being made 484 // here. 485 Instruction *Inst = const_cast<AllocaInst *>(To); 486 if (From->getType() != To->getType()) { 487 BitCastInst *Cast = new BitCastInst(Inst, From->getType()); 488 Cast->insertAfter(Inst); 489 Inst = Cast; 490 } 491 492 // Allow the stack protector to adjust its value map to account for the 493 // upcoming replacement. 494 SP->adjustForColoring(From, To); 495 496 // Note that this will not replace uses in MMOs (which we'll update below), 497 // or anywhere else (which is why we won't delete the original 498 // instruction). 499 const_cast<AllocaInst *>(From)->replaceAllUsesWith(Inst); 500 } 501 502 // Remap all instructions to the new stack slots. 503 for (MachineBasicBlock &BB : *MF) 504 for (MachineInstr &I : BB) { 505 // Skip lifetime markers. We'll remove them soon. 506 if (I.getOpcode() == TargetOpcode::LIFETIME_START || 507 I.getOpcode() == TargetOpcode::LIFETIME_END) 508 continue; 509 510 // Update the MachineMemOperand to use the new alloca. 511 for (MachineMemOperand *MMO : I.memoperands()) { 512 // FIXME: In order to enable the use of TBAA when using AA in CodeGen, 513 // we'll also need to update the TBAA nodes in MMOs with values 514 // derived from the merged allocas. When doing this, we'll need to use 515 // the same variant of GetUnderlyingObjects that is used by the 516 // instruction scheduler (that can look through ptrtoint/inttoptr 517 // pairs). 518 519 // We've replaced IR-level uses of the remapped allocas, so we only 520 // need to replace direct uses here. 521 const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(MMO->getValue()); 522 if (!AI) 523 continue; 524 525 if (!Allocas.count(AI)) 526 continue; 527 528 MMO->setValue(Allocas[AI]); 529 FixedMemOp++; 530 } 531 532 // Update all of the machine instruction operands. 533 for (MachineOperand &MO : I.operands()) { 534 if (!MO.isFI()) 535 continue; 536 int FromSlot = MO.getIndex(); 537 538 // Don't touch arguments. 539 if (FromSlot<0) 540 continue; 541 542 // Only look at mapped slots. 543 if (!SlotRemap.count(FromSlot)) 544 continue; 545 546 // In a debug build, check that the instruction that we are modifying is 547 // inside the expected live range. If the instruction is not inside 548 // the calculated range then it means that the alloca usage moved 549 // outside of the lifetime markers, or that the user has a bug. 550 // NOTE: Alloca address calculations which happen outside the lifetime 551 // zone are are okay, despite the fact that we don't have a good way 552 // for validating all of the usages of the calculation. 553 #ifndef NDEBUG 554 bool TouchesMemory = I.mayLoad() || I.mayStore(); 555 // If we *don't* protect the user from escaped allocas, don't bother 556 // validating the instructions. 557 if (!I.isDebugValue() && TouchesMemory && ProtectFromEscapedAllocas) { 558 SlotIndex Index = Indexes->getInstructionIndex(&I); 559 const LiveInterval *Interval = &*Intervals[FromSlot]; 560 assert(Interval->find(Index) != Interval->end() && 561 "Found instruction usage outside of live range."); 562 } 563 #endif 564 565 // Fix the machine instructions. 566 int ToSlot = SlotRemap[FromSlot]; 567 MO.setIndex(ToSlot); 568 FixedInstr++; 569 } 570 } 571 572 DEBUG(dbgs()<<"Fixed "<<FixedMemOp<<" machine memory operands.\n"); 573 DEBUG(dbgs()<<"Fixed "<<FixedDbg<<" debug locations.\n"); 574 DEBUG(dbgs()<<"Fixed "<<FixedInstr<<" machine instructions.\n"); 575 } 576 577 void StackColoring::removeInvalidSlotRanges() { 578 for (MachineBasicBlock &BB : *MF) 579 for (MachineInstr &I : BB) { 580 if (I.getOpcode() == TargetOpcode::LIFETIME_START || 581 I.getOpcode() == TargetOpcode::LIFETIME_END || I.isDebugValue()) 582 continue; 583 584 // Some intervals are suspicious! In some cases we find address 585 // calculations outside of the lifetime zone, but not actual memory 586 // read or write. Memory accesses outside of the lifetime zone are a clear 587 // violation, but address calculations are okay. This can happen when 588 // GEPs are hoisted outside of the lifetime zone. 589 // So, in here we only check instructions which can read or write memory. 590 if (!I.mayLoad() && !I.mayStore()) 591 continue; 592 593 // Check all of the machine operands. 594 for (const MachineOperand &MO : I.operands()) { 595 if (!MO.isFI()) 596 continue; 597 598 int Slot = MO.getIndex(); 599 600 if (Slot<0) 601 continue; 602 603 if (Intervals[Slot]->empty()) 604 continue; 605 606 // Check that the used slot is inside the calculated lifetime range. 607 // If it is not, warn about it and invalidate the range. 608 LiveInterval *Interval = &*Intervals[Slot]; 609 SlotIndex Index = Indexes->getInstructionIndex(&I); 610 if (Interval->find(Index) == Interval->end()) { 611 Interval->clear(); 612 DEBUG(dbgs()<<"Invalidating range #"<<Slot<<"\n"); 613 EscapedAllocas++; 614 } 615 } 616 } 617 } 618 619 void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap, 620 unsigned NumSlots) { 621 // Expunge slot remap map. 622 for (unsigned i=0; i < NumSlots; ++i) { 623 // If we are remapping i 624 if (SlotRemap.count(i)) { 625 int Target = SlotRemap[i]; 626 // As long as our target is mapped to something else, follow it. 627 while (SlotRemap.count(Target)) { 628 Target = SlotRemap[Target]; 629 SlotRemap[i] = Target; 630 } 631 } 632 } 633 } 634 635 bool StackColoring::runOnMachineFunction(MachineFunction &Func) { 636 if (skipOptnoneFunction(*Func.getFunction())) 637 return false; 638 639 DEBUG(dbgs() << "********** Stack Coloring **********\n" 640 << "********** Function: " 641 << ((const Value*)Func.getFunction())->getName() << '\n'); 642 MF = &Func; 643 MFI = MF->getFrameInfo(); 644 Indexes = &getAnalysis<SlotIndexes>(); 645 SP = &getAnalysis<StackProtector>(); 646 BlockLiveness.clear(); 647 BasicBlocks.clear(); 648 BasicBlockNumbering.clear(); 649 Markers.clear(); 650 Intervals.clear(); 651 VNInfoAllocator.Reset(); 652 653 unsigned NumSlots = MFI->getObjectIndexEnd(); 654 655 // If there are no stack slots then there are no markers to remove. 656 if (!NumSlots) 657 return false; 658 659 SmallVector<int, 8> SortedSlots; 660 661 SortedSlots.reserve(NumSlots); 662 Intervals.reserve(NumSlots); 663 664 unsigned NumMarkers = collectMarkers(NumSlots); 665 666 unsigned TotalSize = 0; 667 DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n"); 668 DEBUG(dbgs()<<"Slot structure:\n"); 669 670 for (int i=0; i < MFI->getObjectIndexEnd(); ++i) { 671 DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n"); 672 TotalSize += MFI->getObjectSize(i); 673 } 674 675 DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n"); 676 677 // Don't continue because there are not enough lifetime markers, or the 678 // stack is too small, or we are told not to optimize the slots. 679 if (NumMarkers < 2 || TotalSize < 16 || DisableColoring) { 680 DEBUG(dbgs()<<"Will not try to merge slots.\n"); 681 return removeAllMarkers(); 682 } 683 684 for (unsigned i=0; i < NumSlots; ++i) { 685 std::unique_ptr<LiveInterval> LI(new LiveInterval(i, 0)); 686 LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator); 687 Intervals.push_back(std::move(LI)); 688 SortedSlots.push_back(i); 689 } 690 691 // Calculate the liveness of each block. 692 calculateLocalLiveness(); 693 694 // Propagate the liveness information. 695 calculateLiveIntervals(NumSlots); 696 697 // Search for allocas which are used outside of the declared lifetime 698 // markers. 699 if (ProtectFromEscapedAllocas) 700 removeInvalidSlotRanges(); 701 702 // Maps old slots to new slots. 703 DenseMap<int, int> SlotRemap; 704 unsigned RemovedSlots = 0; 705 unsigned ReducedSize = 0; 706 707 // Do not bother looking at empty intervals. 708 for (unsigned I = 0; I < NumSlots; ++I) { 709 if (Intervals[SortedSlots[I]]->empty()) 710 SortedSlots[I] = -1; 711 } 712 713 // This is a simple greedy algorithm for merging allocas. First, sort the 714 // slots, placing the largest slots first. Next, perform an n^2 scan and look 715 // for disjoint slots. When you find disjoint slots, merge the samller one 716 // into the bigger one and update the live interval. Remove the small alloca 717 // and continue. 718 719 // Sort the slots according to their size. Place unused slots at the end. 720 // Use stable sort to guarantee deterministic code generation. 721 std::stable_sort(SortedSlots.begin(), SortedSlots.end(), 722 [this](int LHS, int RHS) { 723 // We use -1 to denote a uninteresting slot. Place these slots at the end. 724 if (LHS == -1) return false; 725 if (RHS == -1) return true; 726 // Sort according to size. 727 return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS); 728 }); 729 730 bool Changed = true; 731 while (Changed) { 732 Changed = false; 733 for (unsigned I = 0; I < NumSlots; ++I) { 734 if (SortedSlots[I] == -1) 735 continue; 736 737 for (unsigned J=I+1; J < NumSlots; ++J) { 738 if (SortedSlots[J] == -1) 739 continue; 740 741 int FirstSlot = SortedSlots[I]; 742 int SecondSlot = SortedSlots[J]; 743 LiveInterval *First = &*Intervals[FirstSlot]; 744 LiveInterval *Second = &*Intervals[SecondSlot]; 745 assert (!First->empty() && !Second->empty() && "Found an empty range"); 746 747 // Merge disjoint slots. 748 if (!First->overlaps(*Second)) { 749 Changed = true; 750 First->MergeSegmentsInAsValue(*Second, First->getValNumInfo(0)); 751 SlotRemap[SecondSlot] = FirstSlot; 752 SortedSlots[J] = -1; 753 DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<< 754 SecondSlot<<" together.\n"); 755 unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot), 756 MFI->getObjectAlignment(SecondSlot)); 757 758 assert(MFI->getObjectSize(FirstSlot) >= 759 MFI->getObjectSize(SecondSlot) && 760 "Merging a small object into a larger one"); 761 762 RemovedSlots+=1; 763 ReducedSize += MFI->getObjectSize(SecondSlot); 764 MFI->setObjectAlignment(FirstSlot, MaxAlignment); 765 MFI->RemoveStackObject(SecondSlot); 766 } 767 } 768 } 769 }// While changed. 770 771 // Record statistics. 772 StackSpaceSaved += ReducedSize; 773 StackSlotMerged += RemovedSlots; 774 DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<< 775 ReducedSize<<" bytes\n"); 776 777 // Scan the entire function and update all machine operands that use frame 778 // indices to use the remapped frame index. 779 expungeSlotMap(SlotRemap, NumSlots); 780 remapInstructions(SlotRemap); 781 782 return removeAllMarkers(); 783 } 784