1e8d8bef9SDimitry Andric //===- InstrRefBasedImpl.cpp - Tracking Debug Value MIs -------------------===// 2e8d8bef9SDimitry Andric // 3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6e8d8bef9SDimitry Andric // 7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 8e8d8bef9SDimitry Andric /// \file InstrRefBasedImpl.cpp 9e8d8bef9SDimitry Andric /// 10e8d8bef9SDimitry Andric /// This is a separate implementation of LiveDebugValues, see 11e8d8bef9SDimitry Andric /// LiveDebugValues.cpp and VarLocBasedImpl.cpp for more information. 12e8d8bef9SDimitry Andric /// 13e8d8bef9SDimitry Andric /// This pass propagates variable locations between basic blocks, resolving 14349cc55cSDimitry Andric /// control flow conflicts between them. The problem is SSA construction, where 15349cc55cSDimitry Andric /// each debug instruction assigns the *value* that a variable has, and every 16349cc55cSDimitry Andric /// instruction where the variable is in scope uses that variable. The resulting 17349cc55cSDimitry Andric /// map of instruction-to-value is then translated into a register (or spill) 18349cc55cSDimitry Andric /// location for each variable over each instruction. 19e8d8bef9SDimitry Andric /// 20349cc55cSDimitry Andric /// The primary difference from normal SSA construction is that we cannot 21349cc55cSDimitry Andric /// _create_ PHI values that contain variable values. CodeGen has already 22349cc55cSDimitry Andric /// completed, and we can't alter it just to make debug-info complete. Thus: 23349cc55cSDimitry Andric /// we can identify function positions where we would like a PHI value for a 24349cc55cSDimitry Andric /// variable, but must search the MachineFunction to see whether such a PHI is 25349cc55cSDimitry Andric /// available. If no such PHI exists, the variable location must be dropped. 26e8d8bef9SDimitry Andric /// 27349cc55cSDimitry Andric /// To achieve this, we perform two kinds of analysis. First, we identify 28e8d8bef9SDimitry Andric /// every value defined by every instruction (ignoring those that only move 29349cc55cSDimitry Andric /// another value), then re-compute an SSA-form representation of the 30349cc55cSDimitry Andric /// MachineFunction, using value propagation to eliminate any un-necessary 31349cc55cSDimitry Andric /// PHI values. This gives us a map of every value computed in the function, 32349cc55cSDimitry Andric /// and its location within the register file / stack. 33e8d8bef9SDimitry Andric /// 34349cc55cSDimitry Andric /// Secondly, for each variable we perform the same analysis, where each debug 35349cc55cSDimitry Andric /// instruction is considered a def, and every instruction where the variable 36349cc55cSDimitry Andric /// is in lexical scope as a use. Value propagation is used again to eliminate 37349cc55cSDimitry Andric /// any un-necessary PHIs. This gives us a map of each variable to the value 38349cc55cSDimitry Andric /// it should have in a block. 39e8d8bef9SDimitry Andric /// 40349cc55cSDimitry Andric /// Once both are complete, we have two maps for each block: 41349cc55cSDimitry Andric /// * Variables to the values they should have, 42349cc55cSDimitry Andric /// * Values to the register / spill slot they are located in. 43349cc55cSDimitry Andric /// After which we can marry-up variable values with a location, and emit 44349cc55cSDimitry Andric /// DBG_VALUE instructions specifying those locations. Variable locations may 45349cc55cSDimitry Andric /// be dropped in this process due to the desired variable value not being 46349cc55cSDimitry Andric /// resident in any machine location, or because there is no PHI value in any 47349cc55cSDimitry Andric /// location that accurately represents the desired value. The building of 48349cc55cSDimitry Andric /// location lists for each block is left to DbgEntityHistoryCalculator. 49e8d8bef9SDimitry Andric /// 50349cc55cSDimitry Andric /// This pass is kept efficient because the size of the first SSA problem 51349cc55cSDimitry Andric /// is proportional to the working-set size of the function, which the compiler 52349cc55cSDimitry Andric /// tries to keep small. (It's also proportional to the number of blocks). 53349cc55cSDimitry Andric /// Additionally, we repeatedly perform the second SSA problem analysis with 54349cc55cSDimitry Andric /// only the variables and blocks in a single lexical scope, exploiting their 55349cc55cSDimitry Andric /// locality. 56e8d8bef9SDimitry Andric /// 57e8d8bef9SDimitry Andric /// ### Terminology 58e8d8bef9SDimitry Andric /// 59e8d8bef9SDimitry Andric /// A machine location is a register or spill slot, a value is something that's 60e8d8bef9SDimitry Andric /// defined by an instruction or PHI node, while a variable value is the value 61e8d8bef9SDimitry Andric /// assigned to a variable. A variable location is a machine location, that must 62e8d8bef9SDimitry Andric /// contain the appropriate variable value. A value that is a PHI node is 63e8d8bef9SDimitry Andric /// occasionally called an mphi. 64e8d8bef9SDimitry Andric /// 65349cc55cSDimitry Andric /// The first SSA problem is the "machine value location" problem, 66e8d8bef9SDimitry Andric /// because we're determining which machine locations contain which values. 67e8d8bef9SDimitry Andric /// The "locations" are constant: what's unknown is what value they contain. 68e8d8bef9SDimitry Andric /// 69349cc55cSDimitry Andric /// The second SSA problem (the one for variables) is the "variable value 70e8d8bef9SDimitry Andric /// problem", because it's determining what values a variable has, rather than 71349cc55cSDimitry Andric /// what location those values are placed in. 72e8d8bef9SDimitry Andric /// 73e8d8bef9SDimitry Andric /// TODO: 74e8d8bef9SDimitry Andric /// Overlapping fragments 75e8d8bef9SDimitry Andric /// Entry values 76e8d8bef9SDimitry Andric /// Add back DEBUG statements for debugging this 77e8d8bef9SDimitry Andric /// Collect statistics 78e8d8bef9SDimitry Andric /// 79e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 80e8d8bef9SDimitry Andric 81e8d8bef9SDimitry Andric #include "llvm/ADT/DenseMap.h" 82e8d8bef9SDimitry Andric #include "llvm/ADT/PostOrderIterator.h" 83fe6060f1SDimitry Andric #include "llvm/ADT/STLExtras.h" 84e8d8bef9SDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 85e8d8bef9SDimitry Andric #include "llvm/ADT/SmallSet.h" 86e8d8bef9SDimitry Andric #include "llvm/ADT/SmallVector.h" 8781ad6265SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h" 88e8d8bef9SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h" 89e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h" 90349cc55cSDimitry Andric #include "llvm/CodeGen/MachineDominators.h" 91e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h" 92e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineFunction.h" 93e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineInstr.h" 94e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h" 95fe6060f1SDimitry Andric #include "llvm/CodeGen/MachineInstrBundle.h" 96e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h" 97e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineOperand.h" 98e8d8bef9SDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h" 99e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h" 100e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h" 101e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetLowering.h" 102e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h" 103e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h" 104e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h" 105e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h" 106e8d8bef9SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h" 107e8d8bef9SDimitry Andric #include "llvm/IR/DebugLoc.h" 108e8d8bef9SDimitry Andric #include "llvm/IR/Function.h" 109e8d8bef9SDimitry Andric #include "llvm/MC/MCRegisterInfo.h" 110e8d8bef9SDimitry Andric #include "llvm/Support/Casting.h" 111e8d8bef9SDimitry Andric #include "llvm/Support/Compiler.h" 112e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h" 11381ad6265SDimitry Andric #include "llvm/Support/GenericIteratedDominanceFrontier.h" 114e8d8bef9SDimitry Andric #include "llvm/Support/TypeSize.h" 115e8d8bef9SDimitry Andric #include "llvm/Support/raw_ostream.h" 116fe6060f1SDimitry Andric #include "llvm/Target/TargetMachine.h" 117fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdaterImpl.h" 118e8d8bef9SDimitry Andric #include <algorithm> 119e8d8bef9SDimitry Andric #include <cassert> 12081ad6265SDimitry Andric #include <climits> 121e8d8bef9SDimitry Andric #include <cstdint> 122e8d8bef9SDimitry Andric #include <functional> 123e8d8bef9SDimitry Andric #include <queue> 124e8d8bef9SDimitry Andric #include <tuple> 125e8d8bef9SDimitry Andric #include <utility> 126e8d8bef9SDimitry Andric #include <vector> 127e8d8bef9SDimitry Andric 128349cc55cSDimitry Andric #include "InstrRefBasedImpl.h" 129e8d8bef9SDimitry Andric #include "LiveDebugValues.h" 130e8d8bef9SDimitry Andric 131e8d8bef9SDimitry Andric using namespace llvm; 132349cc55cSDimitry Andric using namespace LiveDebugValues; 133e8d8bef9SDimitry Andric 134fe6060f1SDimitry Andric // SSAUpdaterImple sets DEBUG_TYPE, change it. 135fe6060f1SDimitry Andric #undef DEBUG_TYPE 136e8d8bef9SDimitry Andric #define DEBUG_TYPE "livedebugvalues" 137e8d8bef9SDimitry Andric 138e8d8bef9SDimitry Andric // Act more like the VarLoc implementation, by propagating some locations too 139e8d8bef9SDimitry Andric // far and ignoring some transfers. 140e8d8bef9SDimitry Andric static cl::opt<bool> EmulateOldLDV("emulate-old-livedebugvalues", cl::Hidden, 141e8d8bef9SDimitry Andric cl::desc("Act like old LiveDebugValues did"), 142e8d8bef9SDimitry Andric cl::init(false)); 143e8d8bef9SDimitry Andric 144d56accc7SDimitry Andric // Limit for the maximum number of stack slots we should track, past which we 145d56accc7SDimitry Andric // will ignore any spills. InstrRefBasedLDV gathers detailed information on all 146d56accc7SDimitry Andric // stack slots which leads to high memory consumption, and in some scenarios 147d56accc7SDimitry Andric // (such as asan with very many locals) the working set of the function can be 148d56accc7SDimitry Andric // very large, causing many spills. In these scenarios, it is very unlikely that 149d56accc7SDimitry Andric // the developer has hundreds of variables live at the same time that they're 150d56accc7SDimitry Andric // carefully thinking about -- instead, they probably autogenerated the code. 151d56accc7SDimitry Andric // When this happens, gracefully stop tracking excess spill slots, rather than 152d56accc7SDimitry Andric // consuming all the developer's memory. 153d56accc7SDimitry Andric static cl::opt<unsigned> 154d56accc7SDimitry Andric StackWorkingSetLimit("livedebugvalues-max-stack-slots", cl::Hidden, 155d56accc7SDimitry Andric cl::desc("livedebugvalues-stack-ws-limit"), 156d56accc7SDimitry Andric cl::init(250)); 157d56accc7SDimitry Andric 158e8d8bef9SDimitry Andric /// Tracker for converting machine value locations and variable values into 159e8d8bef9SDimitry Andric /// variable locations (the output of LiveDebugValues), recorded as DBG_VALUEs 160e8d8bef9SDimitry Andric /// specifying block live-in locations and transfers within blocks. 161e8d8bef9SDimitry Andric /// 162e8d8bef9SDimitry Andric /// Operating on a per-block basis, this class takes a (pre-loaded) MLocTracker 163e8d8bef9SDimitry Andric /// and must be initialized with the set of variable values that are live-in to 164e8d8bef9SDimitry Andric /// the block. The caller then repeatedly calls process(). TransferTracker picks 165e8d8bef9SDimitry Andric /// out variable locations for the live-in variable values (if there _is_ a 166e8d8bef9SDimitry Andric /// location) and creates the corresponding DBG_VALUEs. Then, as the block is 167e8d8bef9SDimitry Andric /// stepped through, transfers of values between machine locations are 168e8d8bef9SDimitry Andric /// identified and if profitable, a DBG_VALUE created. 169e8d8bef9SDimitry Andric /// 170e8d8bef9SDimitry Andric /// This is where debug use-before-defs would be resolved: a variable with an 171e8d8bef9SDimitry Andric /// unavailable value could materialize in the middle of a block, when the 172e8d8bef9SDimitry Andric /// value becomes available. Or, we could detect clobbers and re-specify the 173e8d8bef9SDimitry Andric /// variable in a backup location. (XXX these are unimplemented). 174e8d8bef9SDimitry Andric class TransferTracker { 175e8d8bef9SDimitry Andric public: 176e8d8bef9SDimitry Andric const TargetInstrInfo *TII; 177fe6060f1SDimitry Andric const TargetLowering *TLI; 178e8d8bef9SDimitry Andric /// This machine location tracker is assumed to always contain the up-to-date 179e8d8bef9SDimitry Andric /// value mapping for all machine locations. TransferTracker only reads 180e8d8bef9SDimitry Andric /// information from it. (XXX make it const?) 181e8d8bef9SDimitry Andric MLocTracker *MTracker; 182e8d8bef9SDimitry Andric MachineFunction &MF; 183fe6060f1SDimitry Andric bool ShouldEmitDebugEntryValues; 184e8d8bef9SDimitry Andric 185e8d8bef9SDimitry Andric /// Record of all changes in variable locations at a block position. Awkwardly 186e8d8bef9SDimitry Andric /// we allow inserting either before or after the point: MBB != nullptr 187e8d8bef9SDimitry Andric /// indicates it's before, otherwise after. 188e8d8bef9SDimitry Andric struct Transfer { 189fe6060f1SDimitry Andric MachineBasicBlock::instr_iterator Pos; /// Position to insert DBG_VALUes 190e8d8bef9SDimitry Andric MachineBasicBlock *MBB; /// non-null if we should insert after. 191e8d8bef9SDimitry Andric SmallVector<MachineInstr *, 4> Insts; /// Vector of DBG_VALUEs to insert. 192e8d8bef9SDimitry Andric }; 193e8d8bef9SDimitry Andric 194fe6060f1SDimitry Andric struct LocAndProperties { 195e8d8bef9SDimitry Andric LocIdx Loc; 196e8d8bef9SDimitry Andric DbgValueProperties Properties; 197fe6060f1SDimitry Andric }; 198e8d8bef9SDimitry Andric 199e8d8bef9SDimitry Andric /// Collection of transfers (DBG_VALUEs) to be inserted. 200e8d8bef9SDimitry Andric SmallVector<Transfer, 32> Transfers; 201e8d8bef9SDimitry Andric 202e8d8bef9SDimitry Andric /// Local cache of what-value-is-in-what-LocIdx. Used to identify differences 203e8d8bef9SDimitry Andric /// between TransferTrackers view of variable locations and MLocTrackers. For 204e8d8bef9SDimitry Andric /// example, MLocTracker observes all clobbers, but TransferTracker lazily 205e8d8bef9SDimitry Andric /// does not. 206349cc55cSDimitry Andric SmallVector<ValueIDNum, 32> VarLocs; 207e8d8bef9SDimitry Andric 208e8d8bef9SDimitry Andric /// Map from LocIdxes to which DebugVariables are based that location. 209e8d8bef9SDimitry Andric /// Mantained while stepping through the block. Not accurate if 210e8d8bef9SDimitry Andric /// VarLocs[Idx] != MTracker->LocIdxToIDNum[Idx]. 211349cc55cSDimitry Andric DenseMap<LocIdx, SmallSet<DebugVariable, 4>> ActiveMLocs; 212e8d8bef9SDimitry Andric 213e8d8bef9SDimitry Andric /// Map from DebugVariable to it's current location and qualifying meta 214e8d8bef9SDimitry Andric /// information. To be used in conjunction with ActiveMLocs to construct 215e8d8bef9SDimitry Andric /// enough information for the DBG_VALUEs for a particular LocIdx. 216e8d8bef9SDimitry Andric DenseMap<DebugVariable, LocAndProperties> ActiveVLocs; 217e8d8bef9SDimitry Andric 218e8d8bef9SDimitry Andric /// Temporary cache of DBG_VALUEs to be entered into the Transfers collection. 219e8d8bef9SDimitry Andric SmallVector<MachineInstr *, 4> PendingDbgValues; 220e8d8bef9SDimitry Andric 221e8d8bef9SDimitry Andric /// Record of a use-before-def: created when a value that's live-in to the 222e8d8bef9SDimitry Andric /// current block isn't available in any machine location, but it will be 223e8d8bef9SDimitry Andric /// defined in this block. 224e8d8bef9SDimitry Andric struct UseBeforeDef { 225e8d8bef9SDimitry Andric /// Value of this variable, def'd in block. 226e8d8bef9SDimitry Andric ValueIDNum ID; 227e8d8bef9SDimitry Andric /// Identity of this variable. 228e8d8bef9SDimitry Andric DebugVariable Var; 229e8d8bef9SDimitry Andric /// Additional variable properties. 230e8d8bef9SDimitry Andric DbgValueProperties Properties; 231e8d8bef9SDimitry Andric }; 232e8d8bef9SDimitry Andric 233e8d8bef9SDimitry Andric /// Map from instruction index (within the block) to the set of UseBeforeDefs 234e8d8bef9SDimitry Andric /// that become defined at that instruction. 235e8d8bef9SDimitry Andric DenseMap<unsigned, SmallVector<UseBeforeDef, 1>> UseBeforeDefs; 236e8d8bef9SDimitry Andric 237e8d8bef9SDimitry Andric /// The set of variables that are in UseBeforeDefs and can become a location 238e8d8bef9SDimitry Andric /// once the relevant value is defined. An element being erased from this 239e8d8bef9SDimitry Andric /// collection prevents the use-before-def materializing. 240e8d8bef9SDimitry Andric DenseSet<DebugVariable> UseBeforeDefVariables; 241e8d8bef9SDimitry Andric 242e8d8bef9SDimitry Andric const TargetRegisterInfo &TRI; 243e8d8bef9SDimitry Andric const BitVector &CalleeSavedRegs; 244e8d8bef9SDimitry Andric 245e8d8bef9SDimitry Andric TransferTracker(const TargetInstrInfo *TII, MLocTracker *MTracker, 246e8d8bef9SDimitry Andric MachineFunction &MF, const TargetRegisterInfo &TRI, 247fe6060f1SDimitry Andric const BitVector &CalleeSavedRegs, const TargetPassConfig &TPC) 248e8d8bef9SDimitry Andric : TII(TII), MTracker(MTracker), MF(MF), TRI(TRI), 249fe6060f1SDimitry Andric CalleeSavedRegs(CalleeSavedRegs) { 250fe6060f1SDimitry Andric TLI = MF.getSubtarget().getTargetLowering(); 251fe6060f1SDimitry Andric auto &TM = TPC.getTM<TargetMachine>(); 252fe6060f1SDimitry Andric ShouldEmitDebugEntryValues = TM.Options.ShouldEmitDebugEntryValues(); 253fe6060f1SDimitry Andric } 254e8d8bef9SDimitry Andric 255e8d8bef9SDimitry Andric /// Load object with live-in variable values. \p mlocs contains the live-in 256e8d8bef9SDimitry Andric /// values in each machine location, while \p vlocs the live-in variable 257e8d8bef9SDimitry Andric /// values. This method picks variable locations for the live-in variables, 258e8d8bef9SDimitry Andric /// creates DBG_VALUEs and puts them in #Transfers, then prepares the other 259e8d8bef9SDimitry Andric /// object fields to track variable locations as we step through the block. 260e8d8bef9SDimitry Andric /// FIXME: could just examine mloctracker instead of passing in \p mlocs? 26104eeddc0SDimitry Andric void 26281ad6265SDimitry Andric loadInlocs(MachineBasicBlock &MBB, ValueTable &MLocs, 26304eeddc0SDimitry Andric const SmallVectorImpl<std::pair<DebugVariable, DbgValue>> &VLocs, 264e8d8bef9SDimitry Andric unsigned NumLocs) { 265e8d8bef9SDimitry Andric ActiveMLocs.clear(); 266e8d8bef9SDimitry Andric ActiveVLocs.clear(); 267e8d8bef9SDimitry Andric VarLocs.clear(); 268e8d8bef9SDimitry Andric VarLocs.reserve(NumLocs); 269e8d8bef9SDimitry Andric UseBeforeDefs.clear(); 270e8d8bef9SDimitry Andric UseBeforeDefVariables.clear(); 271e8d8bef9SDimitry Andric 272e8d8bef9SDimitry Andric auto isCalleeSaved = [&](LocIdx L) { 273e8d8bef9SDimitry Andric unsigned Reg = MTracker->LocIdxToLocID[L]; 274e8d8bef9SDimitry Andric if (Reg >= MTracker->NumRegs) 275e8d8bef9SDimitry Andric return false; 276e8d8bef9SDimitry Andric for (MCRegAliasIterator RAI(Reg, &TRI, true); RAI.isValid(); ++RAI) 277e8d8bef9SDimitry Andric if (CalleeSavedRegs.test(*RAI)) 278e8d8bef9SDimitry Andric return true; 279e8d8bef9SDimitry Andric return false; 280e8d8bef9SDimitry Andric }; 281e8d8bef9SDimitry Andric 282e8d8bef9SDimitry Andric // Map of the preferred location for each value. 28304eeddc0SDimitry Andric DenseMap<ValueIDNum, LocIdx> ValueToLoc; 2841fd87a68SDimitry Andric 2851fd87a68SDimitry Andric // Initialized the preferred-location map with illegal locations, to be 2861fd87a68SDimitry Andric // filled in later. 287fcaf7f86SDimitry Andric for (const auto &VLoc : VLocs) 2881fd87a68SDimitry Andric if (VLoc.second.Kind == DbgValue::Def) 2891fd87a68SDimitry Andric ValueToLoc.insert({VLoc.second.ID, LocIdx::MakeIllegalLoc()}); 2901fd87a68SDimitry Andric 291349cc55cSDimitry Andric ActiveMLocs.reserve(VLocs.size()); 292349cc55cSDimitry Andric ActiveVLocs.reserve(VLocs.size()); 293e8d8bef9SDimitry Andric 294e8d8bef9SDimitry Andric // Produce a map of value numbers to the current machine locs they live 295e8d8bef9SDimitry Andric // in. When emulating VarLocBasedImpl, there should only be one 296e8d8bef9SDimitry Andric // location; when not, we get to pick. 297e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 298e8d8bef9SDimitry Andric LocIdx Idx = Location.Idx; 299e8d8bef9SDimitry Andric ValueIDNum &VNum = MLocs[Idx.asU64()]; 300e8d8bef9SDimitry Andric VarLocs.push_back(VNum); 30104eeddc0SDimitry Andric 3021fd87a68SDimitry Andric // Is there a variable that wants a location for this value? If not, skip. 3031fd87a68SDimitry Andric auto VIt = ValueToLoc.find(VNum); 3041fd87a68SDimitry Andric if (VIt == ValueToLoc.end()) 30504eeddc0SDimitry Andric continue; 30604eeddc0SDimitry Andric 3071fd87a68SDimitry Andric LocIdx CurLoc = VIt->second; 308e8d8bef9SDimitry Andric // In order of preference, pick: 309e8d8bef9SDimitry Andric // * Callee saved registers, 310e8d8bef9SDimitry Andric // * Other registers, 311e8d8bef9SDimitry Andric // * Spill slots. 3121fd87a68SDimitry Andric if (CurLoc.isIllegal() || MTracker->isSpill(CurLoc) || 3131fd87a68SDimitry Andric (!isCalleeSaved(CurLoc) && isCalleeSaved(Idx.asU64()))) { 314e8d8bef9SDimitry Andric // Insert, or overwrite if insertion failed. 3151fd87a68SDimitry Andric VIt->second = Idx; 316e8d8bef9SDimitry Andric } 317e8d8bef9SDimitry Andric } 318e8d8bef9SDimitry Andric 319e8d8bef9SDimitry Andric // Now map variables to their picked LocIdxes. 32004eeddc0SDimitry Andric for (const auto &Var : VLocs) { 321e8d8bef9SDimitry Andric if (Var.second.Kind == DbgValue::Const) { 322e8d8bef9SDimitry Andric PendingDbgValues.push_back( 323349cc55cSDimitry Andric emitMOLoc(*Var.second.MO, Var.first, Var.second.Properties)); 324e8d8bef9SDimitry Andric continue; 325e8d8bef9SDimitry Andric } 326e8d8bef9SDimitry Andric 327e8d8bef9SDimitry Andric // If the value has no location, we can't make a variable location. 328e8d8bef9SDimitry Andric const ValueIDNum &Num = Var.second.ID; 329e8d8bef9SDimitry Andric auto ValuesPreferredLoc = ValueToLoc.find(Num); 3301fd87a68SDimitry Andric if (ValuesPreferredLoc->second.isIllegal()) { 331e8d8bef9SDimitry Andric // If it's a def that occurs in this block, register it as a 332e8d8bef9SDimitry Andric // use-before-def to be resolved as we step through the block. 333e8d8bef9SDimitry Andric if (Num.getBlock() == (unsigned)MBB.getNumber() && !Num.isPHI()) 334e8d8bef9SDimitry Andric addUseBeforeDef(Var.first, Var.second.Properties, Num); 335fe6060f1SDimitry Andric else 336fe6060f1SDimitry Andric recoverAsEntryValue(Var.first, Var.second.Properties, Num); 337e8d8bef9SDimitry Andric continue; 338e8d8bef9SDimitry Andric } 339e8d8bef9SDimitry Andric 340e8d8bef9SDimitry Andric LocIdx M = ValuesPreferredLoc->second; 341e8d8bef9SDimitry Andric auto NewValue = LocAndProperties{M, Var.second.Properties}; 342e8d8bef9SDimitry Andric auto Result = ActiveVLocs.insert(std::make_pair(Var.first, NewValue)); 343e8d8bef9SDimitry Andric if (!Result.second) 344e8d8bef9SDimitry Andric Result.first->second = NewValue; 345e8d8bef9SDimitry Andric ActiveMLocs[M].insert(Var.first); 346e8d8bef9SDimitry Andric PendingDbgValues.push_back( 347e8d8bef9SDimitry Andric MTracker->emitLoc(M, Var.first, Var.second.Properties)); 348e8d8bef9SDimitry Andric } 349e8d8bef9SDimitry Andric flushDbgValues(MBB.begin(), &MBB); 350e8d8bef9SDimitry Andric } 351e8d8bef9SDimitry Andric 352e8d8bef9SDimitry Andric /// Record that \p Var has value \p ID, a value that becomes available 353e8d8bef9SDimitry Andric /// later in the function. 354e8d8bef9SDimitry Andric void addUseBeforeDef(const DebugVariable &Var, 355e8d8bef9SDimitry Andric const DbgValueProperties &Properties, ValueIDNum ID) { 356e8d8bef9SDimitry Andric UseBeforeDef UBD = {ID, Var, Properties}; 357e8d8bef9SDimitry Andric UseBeforeDefs[ID.getInst()].push_back(UBD); 358e8d8bef9SDimitry Andric UseBeforeDefVariables.insert(Var); 359e8d8bef9SDimitry Andric } 360e8d8bef9SDimitry Andric 361e8d8bef9SDimitry Andric /// After the instruction at index \p Inst and position \p pos has been 362e8d8bef9SDimitry Andric /// processed, check whether it defines a variable value in a use-before-def. 363e8d8bef9SDimitry Andric /// If so, and the variable value hasn't changed since the start of the 364e8d8bef9SDimitry Andric /// block, create a DBG_VALUE. 365e8d8bef9SDimitry Andric void checkInstForNewValues(unsigned Inst, MachineBasicBlock::iterator pos) { 366e8d8bef9SDimitry Andric auto MIt = UseBeforeDefs.find(Inst); 367e8d8bef9SDimitry Andric if (MIt == UseBeforeDefs.end()) 368e8d8bef9SDimitry Andric return; 369e8d8bef9SDimitry Andric 370e8d8bef9SDimitry Andric for (auto &Use : MIt->second) { 371e8d8bef9SDimitry Andric LocIdx L = Use.ID.getLoc(); 372e8d8bef9SDimitry Andric 373e8d8bef9SDimitry Andric // If something goes very wrong, we might end up labelling a COPY 374e8d8bef9SDimitry Andric // instruction or similar with an instruction number, where it doesn't 375e8d8bef9SDimitry Andric // actually define a new value, instead it moves a value. In case this 376e8d8bef9SDimitry Andric // happens, discard. 377349cc55cSDimitry Andric if (MTracker->readMLoc(L) != Use.ID) 378e8d8bef9SDimitry Andric continue; 379e8d8bef9SDimitry Andric 380e8d8bef9SDimitry Andric // If a different debug instruction defined the variable value / location 381e8d8bef9SDimitry Andric // since the start of the block, don't materialize this use-before-def. 382e8d8bef9SDimitry Andric if (!UseBeforeDefVariables.count(Use.Var)) 383e8d8bef9SDimitry Andric continue; 384e8d8bef9SDimitry Andric 385e8d8bef9SDimitry Andric PendingDbgValues.push_back(MTracker->emitLoc(L, Use.Var, Use.Properties)); 386e8d8bef9SDimitry Andric } 387e8d8bef9SDimitry Andric flushDbgValues(pos, nullptr); 388e8d8bef9SDimitry Andric } 389e8d8bef9SDimitry Andric 390e8d8bef9SDimitry Andric /// Helper to move created DBG_VALUEs into Transfers collection. 391e8d8bef9SDimitry Andric void flushDbgValues(MachineBasicBlock::iterator Pos, MachineBasicBlock *MBB) { 392fe6060f1SDimitry Andric if (PendingDbgValues.size() == 0) 393fe6060f1SDimitry Andric return; 394fe6060f1SDimitry Andric 395fe6060f1SDimitry Andric // Pick out the instruction start position. 396fe6060f1SDimitry Andric MachineBasicBlock::instr_iterator BundleStart; 397fe6060f1SDimitry Andric if (MBB && Pos == MBB->begin()) 398fe6060f1SDimitry Andric BundleStart = MBB->instr_begin(); 399fe6060f1SDimitry Andric else 400fe6060f1SDimitry Andric BundleStart = getBundleStart(Pos->getIterator()); 401fe6060f1SDimitry Andric 402fe6060f1SDimitry Andric Transfers.push_back({BundleStart, MBB, PendingDbgValues}); 403e8d8bef9SDimitry Andric PendingDbgValues.clear(); 404e8d8bef9SDimitry Andric } 405fe6060f1SDimitry Andric 406fe6060f1SDimitry Andric bool isEntryValueVariable(const DebugVariable &Var, 407fe6060f1SDimitry Andric const DIExpression *Expr) const { 408fe6060f1SDimitry Andric if (!Var.getVariable()->isParameter()) 409fe6060f1SDimitry Andric return false; 410fe6060f1SDimitry Andric 411fe6060f1SDimitry Andric if (Var.getInlinedAt()) 412fe6060f1SDimitry Andric return false; 413fe6060f1SDimitry Andric 414fe6060f1SDimitry Andric if (Expr->getNumElements() > 0) 415fe6060f1SDimitry Andric return false; 416fe6060f1SDimitry Andric 417fe6060f1SDimitry Andric return true; 418fe6060f1SDimitry Andric } 419fe6060f1SDimitry Andric 420fe6060f1SDimitry Andric bool isEntryValueValue(const ValueIDNum &Val) const { 421fe6060f1SDimitry Andric // Must be in entry block (block number zero), and be a PHI / live-in value. 422fe6060f1SDimitry Andric if (Val.getBlock() || !Val.isPHI()) 423fe6060f1SDimitry Andric return false; 424fe6060f1SDimitry Andric 425fe6060f1SDimitry Andric // Entry values must enter in a register. 426fe6060f1SDimitry Andric if (MTracker->isSpill(Val.getLoc())) 427fe6060f1SDimitry Andric return false; 428fe6060f1SDimitry Andric 429fe6060f1SDimitry Andric Register SP = TLI->getStackPointerRegisterToSaveRestore(); 430fe6060f1SDimitry Andric Register FP = TRI.getFrameRegister(MF); 431fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[Val.getLoc()]; 432fe6060f1SDimitry Andric return Reg != SP && Reg != FP; 433fe6060f1SDimitry Andric } 434fe6060f1SDimitry Andric 43504eeddc0SDimitry Andric bool recoverAsEntryValue(const DebugVariable &Var, 43604eeddc0SDimitry Andric const DbgValueProperties &Prop, 437fe6060f1SDimitry Andric const ValueIDNum &Num) { 438fe6060f1SDimitry Andric // Is this variable location a candidate to be an entry value. First, 439fe6060f1SDimitry Andric // should we be trying this at all? 440fe6060f1SDimitry Andric if (!ShouldEmitDebugEntryValues) 441fe6060f1SDimitry Andric return false; 442fe6060f1SDimitry Andric 443fe6060f1SDimitry Andric // Is the variable appropriate for entry values (i.e., is a parameter). 444fe6060f1SDimitry Andric if (!isEntryValueVariable(Var, Prop.DIExpr)) 445fe6060f1SDimitry Andric return false; 446fe6060f1SDimitry Andric 447fe6060f1SDimitry Andric // Is the value assigned to this variable still the entry value? 448fe6060f1SDimitry Andric if (!isEntryValueValue(Num)) 449fe6060f1SDimitry Andric return false; 450fe6060f1SDimitry Andric 451fe6060f1SDimitry Andric // Emit a variable location using an entry value expression. 452fe6060f1SDimitry Andric DIExpression *NewExpr = 453fe6060f1SDimitry Andric DIExpression::prepend(Prop.DIExpr, DIExpression::EntryValue); 454fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[Num.getLoc()]; 455fe6060f1SDimitry Andric MachineOperand MO = MachineOperand::CreateReg(Reg, false); 456fe6060f1SDimitry Andric 457fe6060f1SDimitry Andric PendingDbgValues.push_back(emitMOLoc(MO, Var, {NewExpr, Prop.Indirect})); 458fe6060f1SDimitry Andric return true; 459e8d8bef9SDimitry Andric } 460e8d8bef9SDimitry Andric 461e8d8bef9SDimitry Andric /// Change a variable value after encountering a DBG_VALUE inside a block. 462e8d8bef9SDimitry Andric void redefVar(const MachineInstr &MI) { 463e8d8bef9SDimitry Andric DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 464e8d8bef9SDimitry Andric MI.getDebugLoc()->getInlinedAt()); 465e8d8bef9SDimitry Andric DbgValueProperties Properties(MI); 466e8d8bef9SDimitry Andric 467e8d8bef9SDimitry Andric const MachineOperand &MO = MI.getOperand(0); 468e8d8bef9SDimitry Andric 469e8d8bef9SDimitry Andric // Ignore non-register locations, we don't transfer those. 470e8d8bef9SDimitry Andric if (!MO.isReg() || MO.getReg() == 0) { 471e8d8bef9SDimitry Andric auto It = ActiveVLocs.find(Var); 472e8d8bef9SDimitry Andric if (It != ActiveVLocs.end()) { 473e8d8bef9SDimitry Andric ActiveMLocs[It->second.Loc].erase(Var); 474e8d8bef9SDimitry Andric ActiveVLocs.erase(It); 475e8d8bef9SDimitry Andric } 476e8d8bef9SDimitry Andric // Any use-before-defs no longer apply. 477e8d8bef9SDimitry Andric UseBeforeDefVariables.erase(Var); 478e8d8bef9SDimitry Andric return; 479e8d8bef9SDimitry Andric } 480e8d8bef9SDimitry Andric 481e8d8bef9SDimitry Andric Register Reg = MO.getReg(); 482e8d8bef9SDimitry Andric LocIdx NewLoc = MTracker->getRegMLoc(Reg); 483e8d8bef9SDimitry Andric redefVar(MI, Properties, NewLoc); 484e8d8bef9SDimitry Andric } 485e8d8bef9SDimitry Andric 486e8d8bef9SDimitry Andric /// Handle a change in variable location within a block. Terminate the 487e8d8bef9SDimitry Andric /// variables current location, and record the value it now refers to, so 488e8d8bef9SDimitry Andric /// that we can detect location transfers later on. 489e8d8bef9SDimitry Andric void redefVar(const MachineInstr &MI, const DbgValueProperties &Properties, 490e8d8bef9SDimitry Andric Optional<LocIdx> OptNewLoc) { 491e8d8bef9SDimitry Andric DebugVariable Var(MI.getDebugVariable(), MI.getDebugExpression(), 492e8d8bef9SDimitry Andric MI.getDebugLoc()->getInlinedAt()); 493e8d8bef9SDimitry Andric // Any use-before-defs no longer apply. 494e8d8bef9SDimitry Andric UseBeforeDefVariables.erase(Var); 495e8d8bef9SDimitry Andric 496e8d8bef9SDimitry Andric // Erase any previous location, 497e8d8bef9SDimitry Andric auto It = ActiveVLocs.find(Var); 498e8d8bef9SDimitry Andric if (It != ActiveVLocs.end()) 499e8d8bef9SDimitry Andric ActiveMLocs[It->second.Loc].erase(Var); 500e8d8bef9SDimitry Andric 501e8d8bef9SDimitry Andric // If there _is_ no new location, all we had to do was erase. 502e8d8bef9SDimitry Andric if (!OptNewLoc) 503e8d8bef9SDimitry Andric return; 504e8d8bef9SDimitry Andric LocIdx NewLoc = *OptNewLoc; 505e8d8bef9SDimitry Andric 506e8d8bef9SDimitry Andric // Check whether our local copy of values-by-location in #VarLocs is out of 507e8d8bef9SDimitry Andric // date. Wipe old tracking data for the location if it's been clobbered in 508e8d8bef9SDimitry Andric // the meantime. 509349cc55cSDimitry Andric if (MTracker->readMLoc(NewLoc) != VarLocs[NewLoc.asU64()]) { 510fcaf7f86SDimitry Andric for (const auto &P : ActiveMLocs[NewLoc]) { 511e8d8bef9SDimitry Andric ActiveVLocs.erase(P); 512e8d8bef9SDimitry Andric } 513e8d8bef9SDimitry Andric ActiveMLocs[NewLoc.asU64()].clear(); 514349cc55cSDimitry Andric VarLocs[NewLoc.asU64()] = MTracker->readMLoc(NewLoc); 515e8d8bef9SDimitry Andric } 516e8d8bef9SDimitry Andric 517e8d8bef9SDimitry Andric ActiveMLocs[NewLoc].insert(Var); 518e8d8bef9SDimitry Andric if (It == ActiveVLocs.end()) { 519e8d8bef9SDimitry Andric ActiveVLocs.insert( 520e8d8bef9SDimitry Andric std::make_pair(Var, LocAndProperties{NewLoc, Properties})); 521e8d8bef9SDimitry Andric } else { 522e8d8bef9SDimitry Andric It->second.Loc = NewLoc; 523e8d8bef9SDimitry Andric It->second.Properties = Properties; 524e8d8bef9SDimitry Andric } 525e8d8bef9SDimitry Andric } 526e8d8bef9SDimitry Andric 527fe6060f1SDimitry Andric /// Account for a location \p mloc being clobbered. Examine the variable 528fe6060f1SDimitry Andric /// locations that will be terminated: and try to recover them by using 529fe6060f1SDimitry Andric /// another location. Optionally, given \p MakeUndef, emit a DBG_VALUE to 530fe6060f1SDimitry Andric /// explicitly terminate a location if it can't be recovered. 531fe6060f1SDimitry Andric void clobberMloc(LocIdx MLoc, MachineBasicBlock::iterator Pos, 532fe6060f1SDimitry Andric bool MakeUndef = true) { 533e8d8bef9SDimitry Andric auto ActiveMLocIt = ActiveMLocs.find(MLoc); 534e8d8bef9SDimitry Andric if (ActiveMLocIt == ActiveMLocs.end()) 535e8d8bef9SDimitry Andric return; 536e8d8bef9SDimitry Andric 537fe6060f1SDimitry Andric // What was the old variable value? 538fe6060f1SDimitry Andric ValueIDNum OldValue = VarLocs[MLoc.asU64()]; 539753f127fSDimitry Andric clobberMloc(MLoc, OldValue, Pos, MakeUndef); 540753f127fSDimitry Andric } 541753f127fSDimitry Andric /// Overload that takes an explicit value \p OldValue for when the value in 542753f127fSDimitry Andric /// \p MLoc has changed and the TransferTracker's locations have not been 543753f127fSDimitry Andric /// updated yet. 544753f127fSDimitry Andric void clobberMloc(LocIdx MLoc, ValueIDNum OldValue, 545753f127fSDimitry Andric MachineBasicBlock::iterator Pos, bool MakeUndef = true) { 546753f127fSDimitry Andric auto ActiveMLocIt = ActiveMLocs.find(MLoc); 547753f127fSDimitry Andric if (ActiveMLocIt == ActiveMLocs.end()) 548753f127fSDimitry Andric return; 549753f127fSDimitry Andric 550e8d8bef9SDimitry Andric VarLocs[MLoc.asU64()] = ValueIDNum::EmptyValue; 551e8d8bef9SDimitry Andric 552fe6060f1SDimitry Andric // Examine the remaining variable locations: if we can find the same value 553fe6060f1SDimitry Andric // again, we can recover the location. 554fe6060f1SDimitry Andric Optional<LocIdx> NewLoc = None; 555fe6060f1SDimitry Andric for (auto Loc : MTracker->locations()) 556fe6060f1SDimitry Andric if (Loc.Value == OldValue) 557fe6060f1SDimitry Andric NewLoc = Loc.Idx; 558fe6060f1SDimitry Andric 559fe6060f1SDimitry Andric // If there is no location, and we weren't asked to make the variable 560fe6060f1SDimitry Andric // explicitly undef, then stop here. 561fe6060f1SDimitry Andric if (!NewLoc && !MakeUndef) { 562fe6060f1SDimitry Andric // Try and recover a few more locations with entry values. 563fcaf7f86SDimitry Andric for (const auto &Var : ActiveMLocIt->second) { 564fe6060f1SDimitry Andric auto &Prop = ActiveVLocs.find(Var)->second.Properties; 565fe6060f1SDimitry Andric recoverAsEntryValue(Var, Prop, OldValue); 566fe6060f1SDimitry Andric } 567fe6060f1SDimitry Andric flushDbgValues(Pos, nullptr); 568fe6060f1SDimitry Andric return; 569fe6060f1SDimitry Andric } 570fe6060f1SDimitry Andric 571fe6060f1SDimitry Andric // Examine all the variables based on this location. 572fe6060f1SDimitry Andric DenseSet<DebugVariable> NewMLocs; 573fcaf7f86SDimitry Andric for (const auto &Var : ActiveMLocIt->second) { 574e8d8bef9SDimitry Andric auto ActiveVLocIt = ActiveVLocs.find(Var); 575fe6060f1SDimitry Andric // Re-state the variable location: if there's no replacement then NewLoc 576fe6060f1SDimitry Andric // is None and a $noreg DBG_VALUE will be created. Otherwise, a DBG_VALUE 577fe6060f1SDimitry Andric // identifying the alternative location will be emitted. 5784824e7fdSDimitry Andric const DbgValueProperties &Properties = ActiveVLocIt->second.Properties; 579fe6060f1SDimitry Andric PendingDbgValues.push_back(MTracker->emitLoc(NewLoc, Var, Properties)); 580fe6060f1SDimitry Andric 581fe6060f1SDimitry Andric // Update machine locations <=> variable locations maps. Defer updating 582fe6060f1SDimitry Andric // ActiveMLocs to avoid invalidaing the ActiveMLocIt iterator. 583fe6060f1SDimitry Andric if (!NewLoc) { 584e8d8bef9SDimitry Andric ActiveVLocs.erase(ActiveVLocIt); 585fe6060f1SDimitry Andric } else { 586fe6060f1SDimitry Andric ActiveVLocIt->second.Loc = *NewLoc; 587fe6060f1SDimitry Andric NewMLocs.insert(Var); 588e8d8bef9SDimitry Andric } 589fe6060f1SDimitry Andric } 590fe6060f1SDimitry Andric 591fe6060f1SDimitry Andric // Commit any deferred ActiveMLoc changes. 592fe6060f1SDimitry Andric if (!NewMLocs.empty()) 593fe6060f1SDimitry Andric for (auto &Var : NewMLocs) 594fe6060f1SDimitry Andric ActiveMLocs[*NewLoc].insert(Var); 595fe6060f1SDimitry Andric 596fe6060f1SDimitry Andric // We lazily track what locations have which values; if we've found a new 597fe6060f1SDimitry Andric // location for the clobbered value, remember it. 598fe6060f1SDimitry Andric if (NewLoc) 599fe6060f1SDimitry Andric VarLocs[NewLoc->asU64()] = OldValue; 600fe6060f1SDimitry Andric 601e8d8bef9SDimitry Andric flushDbgValues(Pos, nullptr); 602e8d8bef9SDimitry Andric 603349cc55cSDimitry Andric // Re-find ActiveMLocIt, iterator could have been invalidated. 604349cc55cSDimitry Andric ActiveMLocIt = ActiveMLocs.find(MLoc); 605e8d8bef9SDimitry Andric ActiveMLocIt->second.clear(); 606e8d8bef9SDimitry Andric } 607e8d8bef9SDimitry Andric 608e8d8bef9SDimitry Andric /// Transfer variables based on \p Src to be based on \p Dst. This handles 609e8d8bef9SDimitry Andric /// both register copies as well as spills and restores. Creates DBG_VALUEs 610e8d8bef9SDimitry Andric /// describing the movement. 611e8d8bef9SDimitry Andric void transferMlocs(LocIdx Src, LocIdx Dst, MachineBasicBlock::iterator Pos) { 612e8d8bef9SDimitry Andric // Does Src still contain the value num we expect? If not, it's been 613e8d8bef9SDimitry Andric // clobbered in the meantime, and our variable locations are stale. 614349cc55cSDimitry Andric if (VarLocs[Src.asU64()] != MTracker->readMLoc(Src)) 615e8d8bef9SDimitry Andric return; 616e8d8bef9SDimitry Andric 617e8d8bef9SDimitry Andric // assert(ActiveMLocs[Dst].size() == 0); 618e8d8bef9SDimitry Andric //^^^ Legitimate scenario on account of un-clobbered slot being assigned to? 619349cc55cSDimitry Andric 620349cc55cSDimitry Andric // Move set of active variables from one location to another. 621349cc55cSDimitry Andric auto MovingVars = ActiveMLocs[Src]; 622349cc55cSDimitry Andric ActiveMLocs[Dst] = MovingVars; 623e8d8bef9SDimitry Andric VarLocs[Dst.asU64()] = VarLocs[Src.asU64()]; 624e8d8bef9SDimitry Andric 625e8d8bef9SDimitry Andric // For each variable based on Src; create a location at Dst. 626fcaf7f86SDimitry Andric for (const auto &Var : MovingVars) { 627e8d8bef9SDimitry Andric auto ActiveVLocIt = ActiveVLocs.find(Var); 628e8d8bef9SDimitry Andric assert(ActiveVLocIt != ActiveVLocs.end()); 629e8d8bef9SDimitry Andric ActiveVLocIt->second.Loc = Dst; 630e8d8bef9SDimitry Andric 631e8d8bef9SDimitry Andric MachineInstr *MI = 632e8d8bef9SDimitry Andric MTracker->emitLoc(Dst, Var, ActiveVLocIt->second.Properties); 633e8d8bef9SDimitry Andric PendingDbgValues.push_back(MI); 634e8d8bef9SDimitry Andric } 635e8d8bef9SDimitry Andric ActiveMLocs[Src].clear(); 636e8d8bef9SDimitry Andric flushDbgValues(Pos, nullptr); 637e8d8bef9SDimitry Andric 638e8d8bef9SDimitry Andric // XXX XXX XXX "pretend to be old LDV" means dropping all tracking data 639e8d8bef9SDimitry Andric // about the old location. 640e8d8bef9SDimitry Andric if (EmulateOldLDV) 641e8d8bef9SDimitry Andric VarLocs[Src.asU64()] = ValueIDNum::EmptyValue; 642e8d8bef9SDimitry Andric } 643e8d8bef9SDimitry Andric 644e8d8bef9SDimitry Andric MachineInstrBuilder emitMOLoc(const MachineOperand &MO, 645e8d8bef9SDimitry Andric const DebugVariable &Var, 646e8d8bef9SDimitry Andric const DbgValueProperties &Properties) { 647e8d8bef9SDimitry Andric DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0, 648e8d8bef9SDimitry Andric Var.getVariable()->getScope(), 649e8d8bef9SDimitry Andric const_cast<DILocation *>(Var.getInlinedAt())); 650e8d8bef9SDimitry Andric auto MIB = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE)); 651e8d8bef9SDimitry Andric MIB.add(MO); 652e8d8bef9SDimitry Andric if (Properties.Indirect) 653e8d8bef9SDimitry Andric MIB.addImm(0); 654e8d8bef9SDimitry Andric else 655e8d8bef9SDimitry Andric MIB.addReg(0); 656e8d8bef9SDimitry Andric MIB.addMetadata(Var.getVariable()); 657e8d8bef9SDimitry Andric MIB.addMetadata(Properties.DIExpr); 658e8d8bef9SDimitry Andric return MIB; 659e8d8bef9SDimitry Andric } 660e8d8bef9SDimitry Andric }; 661e8d8bef9SDimitry Andric 662349cc55cSDimitry Andric //===----------------------------------------------------------------------===// 663349cc55cSDimitry Andric // Implementation 664349cc55cSDimitry Andric //===----------------------------------------------------------------------===// 665e8d8bef9SDimitry Andric 666349cc55cSDimitry Andric ValueIDNum ValueIDNum::EmptyValue = {UINT_MAX, UINT_MAX, UINT_MAX}; 667349cc55cSDimitry Andric ValueIDNum ValueIDNum::TombstoneValue = {UINT_MAX, UINT_MAX, UINT_MAX - 1}; 668e8d8bef9SDimitry Andric 669349cc55cSDimitry Andric #ifndef NDEBUG 670349cc55cSDimitry Andric void DbgValue::dump(const MLocTracker *MTrack) const { 671349cc55cSDimitry Andric if (Kind == Const) { 672349cc55cSDimitry Andric MO->dump(); 673349cc55cSDimitry Andric } else if (Kind == NoVal) { 674349cc55cSDimitry Andric dbgs() << "NoVal(" << BlockNo << ")"; 675349cc55cSDimitry Andric } else if (Kind == VPHI) { 676349cc55cSDimitry Andric dbgs() << "VPHI(" << BlockNo << "," << MTrack->IDAsString(ID) << ")"; 677349cc55cSDimitry Andric } else { 678349cc55cSDimitry Andric assert(Kind == Def); 679349cc55cSDimitry Andric dbgs() << MTrack->IDAsString(ID); 680349cc55cSDimitry Andric } 681349cc55cSDimitry Andric if (Properties.Indirect) 682349cc55cSDimitry Andric dbgs() << " indir"; 683349cc55cSDimitry Andric if (Properties.DIExpr) 684349cc55cSDimitry Andric dbgs() << " " << *Properties.DIExpr; 685349cc55cSDimitry Andric } 686349cc55cSDimitry Andric #endif 687e8d8bef9SDimitry Andric 688349cc55cSDimitry Andric MLocTracker::MLocTracker(MachineFunction &MF, const TargetInstrInfo &TII, 689349cc55cSDimitry Andric const TargetRegisterInfo &TRI, 690349cc55cSDimitry Andric const TargetLowering &TLI) 691349cc55cSDimitry Andric : MF(MF), TII(TII), TRI(TRI), TLI(TLI), 692349cc55cSDimitry Andric LocIdxToIDNum(ValueIDNum::EmptyValue), LocIdxToLocID(0) { 693349cc55cSDimitry Andric NumRegs = TRI.getNumRegs(); 694349cc55cSDimitry Andric reset(); 695349cc55cSDimitry Andric LocIDToLocIdx.resize(NumRegs, LocIdx::MakeIllegalLoc()); 696349cc55cSDimitry Andric assert(NumRegs < (1u << NUM_LOC_BITS)); // Detect bit packing failure 697e8d8bef9SDimitry Andric 698349cc55cSDimitry Andric // Always track SP. This avoids the implicit clobbering caused by regmasks 699349cc55cSDimitry Andric // from affectings its values. (LiveDebugValues disbelieves calls and 700349cc55cSDimitry Andric // regmasks that claim to clobber SP). 701349cc55cSDimitry Andric Register SP = TLI.getStackPointerRegisterToSaveRestore(); 702349cc55cSDimitry Andric if (SP) { 703349cc55cSDimitry Andric unsigned ID = getLocID(SP); 704349cc55cSDimitry Andric (void)lookupOrTrackRegister(ID); 705e8d8bef9SDimitry Andric 706349cc55cSDimitry Andric for (MCRegAliasIterator RAI(SP, &TRI, true); RAI.isValid(); ++RAI) 707349cc55cSDimitry Andric SPAliases.insert(*RAI); 708349cc55cSDimitry Andric } 709e8d8bef9SDimitry Andric 710349cc55cSDimitry Andric // Build some common stack positions -- full registers being spilt to the 711349cc55cSDimitry Andric // stack. 712349cc55cSDimitry Andric StackSlotIdxes.insert({{8, 0}, 0}); 713349cc55cSDimitry Andric StackSlotIdxes.insert({{16, 0}, 1}); 714349cc55cSDimitry Andric StackSlotIdxes.insert({{32, 0}, 2}); 715349cc55cSDimitry Andric StackSlotIdxes.insert({{64, 0}, 3}); 716349cc55cSDimitry Andric StackSlotIdxes.insert({{128, 0}, 4}); 717349cc55cSDimitry Andric StackSlotIdxes.insert({{256, 0}, 5}); 718349cc55cSDimitry Andric StackSlotIdxes.insert({{512, 0}, 6}); 719e8d8bef9SDimitry Andric 720349cc55cSDimitry Andric // Traverse all the subregister idxes, and ensure there's an index for them. 721349cc55cSDimitry Andric // Duplicates are no problem: we're interested in their position in the 722349cc55cSDimitry Andric // stack slot, we don't want to type the slot. 723349cc55cSDimitry Andric for (unsigned int I = 1; I < TRI.getNumSubRegIndices(); ++I) { 724349cc55cSDimitry Andric unsigned Size = TRI.getSubRegIdxSize(I); 725349cc55cSDimitry Andric unsigned Offs = TRI.getSubRegIdxOffset(I); 726349cc55cSDimitry Andric unsigned Idx = StackSlotIdxes.size(); 727e8d8bef9SDimitry Andric 728349cc55cSDimitry Andric // Some subregs have -1, -2 and so forth fed into their fields, to mean 729349cc55cSDimitry Andric // special backend things. Ignore those. 730349cc55cSDimitry Andric if (Size > 60000 || Offs > 60000) 731349cc55cSDimitry Andric continue; 732e8d8bef9SDimitry Andric 733349cc55cSDimitry Andric StackSlotIdxes.insert({{Size, Offs}, Idx}); 734349cc55cSDimitry Andric } 735e8d8bef9SDimitry Andric 73681ad6265SDimitry Andric // There may also be strange register class sizes (think x86 fp80s). 73781ad6265SDimitry Andric for (const TargetRegisterClass *RC : TRI.regclasses()) { 73881ad6265SDimitry Andric unsigned Size = TRI.getRegSizeInBits(*RC); 73981ad6265SDimitry Andric 74081ad6265SDimitry Andric // We might see special reserved values as sizes, and classes for other 74181ad6265SDimitry Andric // stuff the machine tries to model. If it's more than 512 bits, then it 74281ad6265SDimitry Andric // is very unlikely to be a register than can be spilt. 74381ad6265SDimitry Andric if (Size > 512) 74481ad6265SDimitry Andric continue; 74581ad6265SDimitry Andric 74681ad6265SDimitry Andric unsigned Idx = StackSlotIdxes.size(); 74781ad6265SDimitry Andric StackSlotIdxes.insert({{Size, 0}, Idx}); 74881ad6265SDimitry Andric } 74981ad6265SDimitry Andric 750349cc55cSDimitry Andric for (auto &Idx : StackSlotIdxes) 751349cc55cSDimitry Andric StackIdxesToPos[Idx.second] = Idx.first; 752e8d8bef9SDimitry Andric 753349cc55cSDimitry Andric NumSlotIdxes = StackSlotIdxes.size(); 754349cc55cSDimitry Andric } 755e8d8bef9SDimitry Andric 756349cc55cSDimitry Andric LocIdx MLocTracker::trackRegister(unsigned ID) { 757349cc55cSDimitry Andric assert(ID != 0); 758349cc55cSDimitry Andric LocIdx NewIdx = LocIdx(LocIdxToIDNum.size()); 759349cc55cSDimitry Andric LocIdxToIDNum.grow(NewIdx); 760349cc55cSDimitry Andric LocIdxToLocID.grow(NewIdx); 761e8d8bef9SDimitry Andric 762349cc55cSDimitry Andric // Default: it's an mphi. 763349cc55cSDimitry Andric ValueIDNum ValNum = {CurBB, 0, NewIdx}; 764349cc55cSDimitry Andric // Was this reg ever touched by a regmask? 765349cc55cSDimitry Andric for (const auto &MaskPair : reverse(Masks)) { 766349cc55cSDimitry Andric if (MaskPair.first->clobbersPhysReg(ID)) { 767349cc55cSDimitry Andric // There was an earlier def we skipped. 768349cc55cSDimitry Andric ValNum = {CurBB, MaskPair.second, NewIdx}; 769349cc55cSDimitry Andric break; 770349cc55cSDimitry Andric } 771349cc55cSDimitry Andric } 772e8d8bef9SDimitry Andric 773349cc55cSDimitry Andric LocIdxToIDNum[NewIdx] = ValNum; 774349cc55cSDimitry Andric LocIdxToLocID[NewIdx] = ID; 775349cc55cSDimitry Andric return NewIdx; 776349cc55cSDimitry Andric } 777e8d8bef9SDimitry Andric 778349cc55cSDimitry Andric void MLocTracker::writeRegMask(const MachineOperand *MO, unsigned CurBB, 779349cc55cSDimitry Andric unsigned InstID) { 780349cc55cSDimitry Andric // Def any register we track have that isn't preserved. The regmask 781349cc55cSDimitry Andric // terminates the liveness of a register, meaning its value can't be 782349cc55cSDimitry Andric // relied upon -- we represent this by giving it a new value. 783349cc55cSDimitry Andric for (auto Location : locations()) { 784349cc55cSDimitry Andric unsigned ID = LocIdxToLocID[Location.Idx]; 785349cc55cSDimitry Andric // Don't clobber SP, even if the mask says it's clobbered. 786349cc55cSDimitry Andric if (ID < NumRegs && !SPAliases.count(ID) && MO->clobbersPhysReg(ID)) 787349cc55cSDimitry Andric defReg(ID, CurBB, InstID); 788349cc55cSDimitry Andric } 789349cc55cSDimitry Andric Masks.push_back(std::make_pair(MO, InstID)); 790349cc55cSDimitry Andric } 791e8d8bef9SDimitry Andric 792d56accc7SDimitry Andric Optional<SpillLocationNo> MLocTracker::getOrTrackSpillLoc(SpillLoc L) { 793349cc55cSDimitry Andric SpillLocationNo SpillID(SpillLocs.idFor(L)); 794d56accc7SDimitry Andric 795349cc55cSDimitry Andric if (SpillID.id() == 0) { 796d56accc7SDimitry Andric // If there is no location, and we have reached the limit of how many stack 797d56accc7SDimitry Andric // slots to track, then don't track this one. 798d56accc7SDimitry Andric if (SpillLocs.size() >= StackWorkingSetLimit) 799d56accc7SDimitry Andric return None; 800d56accc7SDimitry Andric 801349cc55cSDimitry Andric // Spill location is untracked: create record for this one, and all 802349cc55cSDimitry Andric // subregister slots too. 803349cc55cSDimitry Andric SpillID = SpillLocationNo(SpillLocs.insert(L)); 804349cc55cSDimitry Andric for (unsigned StackIdx = 0; StackIdx < NumSlotIdxes; ++StackIdx) { 805349cc55cSDimitry Andric unsigned L = getSpillIDWithIdx(SpillID, StackIdx); 806349cc55cSDimitry Andric LocIdx Idx = LocIdx(LocIdxToIDNum.size()); // New idx 807349cc55cSDimitry Andric LocIdxToIDNum.grow(Idx); 808349cc55cSDimitry Andric LocIdxToLocID.grow(Idx); 809349cc55cSDimitry Andric LocIDToLocIdx.push_back(Idx); 810349cc55cSDimitry Andric LocIdxToLocID[Idx] = L; 811349cc55cSDimitry Andric // Initialize to PHI value; corresponds to the location's live-in value 812349cc55cSDimitry Andric // during transfer function construction. 813349cc55cSDimitry Andric LocIdxToIDNum[Idx] = ValueIDNum(CurBB, 0, Idx); 814349cc55cSDimitry Andric } 815349cc55cSDimitry Andric } 816349cc55cSDimitry Andric return SpillID; 817349cc55cSDimitry Andric } 818fe6060f1SDimitry Andric 819349cc55cSDimitry Andric std::string MLocTracker::LocIdxToName(LocIdx Idx) const { 820349cc55cSDimitry Andric unsigned ID = LocIdxToLocID[Idx]; 821349cc55cSDimitry Andric if (ID >= NumRegs) { 822349cc55cSDimitry Andric StackSlotPos Pos = locIDToSpillIdx(ID); 823349cc55cSDimitry Andric ID -= NumRegs; 824349cc55cSDimitry Andric unsigned Slot = ID / NumSlotIdxes; 825349cc55cSDimitry Andric return Twine("slot ") 826349cc55cSDimitry Andric .concat(Twine(Slot).concat(Twine(" sz ").concat(Twine(Pos.first) 827349cc55cSDimitry Andric .concat(Twine(" offs ").concat(Twine(Pos.second)))))) 828349cc55cSDimitry Andric .str(); 829349cc55cSDimitry Andric } else { 830349cc55cSDimitry Andric return TRI.getRegAsmName(ID).str(); 831349cc55cSDimitry Andric } 832349cc55cSDimitry Andric } 833fe6060f1SDimitry Andric 834349cc55cSDimitry Andric std::string MLocTracker::IDAsString(const ValueIDNum &Num) const { 835349cc55cSDimitry Andric std::string DefName = LocIdxToName(Num.getLoc()); 836349cc55cSDimitry Andric return Num.asString(DefName); 837349cc55cSDimitry Andric } 838fe6060f1SDimitry Andric 839349cc55cSDimitry Andric #ifndef NDEBUG 840349cc55cSDimitry Andric LLVM_DUMP_METHOD void MLocTracker::dump() { 841349cc55cSDimitry Andric for (auto Location : locations()) { 842349cc55cSDimitry Andric std::string MLocName = LocIdxToName(Location.Value.getLoc()); 843349cc55cSDimitry Andric std::string DefName = Location.Value.asString(MLocName); 844349cc55cSDimitry Andric dbgs() << LocIdxToName(Location.Idx) << " --> " << DefName << "\n"; 845349cc55cSDimitry Andric } 846349cc55cSDimitry Andric } 847e8d8bef9SDimitry Andric 848349cc55cSDimitry Andric LLVM_DUMP_METHOD void MLocTracker::dump_mloc_map() { 849349cc55cSDimitry Andric for (auto Location : locations()) { 850349cc55cSDimitry Andric std::string foo = LocIdxToName(Location.Idx); 851349cc55cSDimitry Andric dbgs() << "Idx " << Location.Idx.asU64() << " " << foo << "\n"; 852349cc55cSDimitry Andric } 853349cc55cSDimitry Andric } 854349cc55cSDimitry Andric #endif 855e8d8bef9SDimitry Andric 856349cc55cSDimitry Andric MachineInstrBuilder MLocTracker::emitLoc(Optional<LocIdx> MLoc, 857349cc55cSDimitry Andric const DebugVariable &Var, 858349cc55cSDimitry Andric const DbgValueProperties &Properties) { 859349cc55cSDimitry Andric DebugLoc DL = DILocation::get(Var.getVariable()->getContext(), 0, 0, 860349cc55cSDimitry Andric Var.getVariable()->getScope(), 861349cc55cSDimitry Andric const_cast<DILocation *>(Var.getInlinedAt())); 862349cc55cSDimitry Andric auto MIB = BuildMI(MF, DL, TII.get(TargetOpcode::DBG_VALUE)); 863e8d8bef9SDimitry Andric 864349cc55cSDimitry Andric const DIExpression *Expr = Properties.DIExpr; 865349cc55cSDimitry Andric if (!MLoc) { 866349cc55cSDimitry Andric // No location -> DBG_VALUE $noreg 867349cc55cSDimitry Andric MIB.addReg(0); 868349cc55cSDimitry Andric MIB.addReg(0); 869349cc55cSDimitry Andric } else if (LocIdxToLocID[*MLoc] >= NumRegs) { 870349cc55cSDimitry Andric unsigned LocID = LocIdxToLocID[*MLoc]; 871349cc55cSDimitry Andric SpillLocationNo SpillID = locIDToSpill(LocID); 872349cc55cSDimitry Andric StackSlotPos StackIdx = locIDToSpillIdx(LocID); 873349cc55cSDimitry Andric unsigned short Offset = StackIdx.second; 874e8d8bef9SDimitry Andric 875349cc55cSDimitry Andric // TODO: support variables that are located in spill slots, with non-zero 876349cc55cSDimitry Andric // offsets from the start of the spill slot. It would require some more 877349cc55cSDimitry Andric // complex DIExpression calculations. This doesn't seem to be produced by 878349cc55cSDimitry Andric // LLVM right now, so don't try and support it. 879349cc55cSDimitry Andric // Accept no-subregister slots and subregisters where the offset is zero. 880349cc55cSDimitry Andric // The consumer should already have type information to work out how large 881349cc55cSDimitry Andric // the variable is. 882349cc55cSDimitry Andric if (Offset == 0) { 883349cc55cSDimitry Andric const SpillLoc &Spill = SpillLocs[SpillID.id()]; 884349cc55cSDimitry Andric unsigned Base = Spill.SpillBase; 885349cc55cSDimitry Andric MIB.addReg(Base); 8864824e7fdSDimitry Andric 88781ad6265SDimitry Andric // There are several ways we can dereference things, and several inputs 88881ad6265SDimitry Andric // to consider: 88981ad6265SDimitry Andric // * NRVO variables will appear with IsIndirect set, but should have 89081ad6265SDimitry Andric // nothing else in their DIExpressions, 89181ad6265SDimitry Andric // * Variables with DW_OP_stack_value in their expr already need an 89281ad6265SDimitry Andric // explicit dereference of the stack location, 89381ad6265SDimitry Andric // * Values that don't match the variable size need DW_OP_deref_size, 89481ad6265SDimitry Andric // * Everything else can just become a simple location expression. 89581ad6265SDimitry Andric 89681ad6265SDimitry Andric // We need to use deref_size whenever there's a mismatch between the 89781ad6265SDimitry Andric // size of value and the size of variable portion being read. 89881ad6265SDimitry Andric // Additionally, we should use it whenever dealing with stack_value 89981ad6265SDimitry Andric // fragments, to avoid the consumer having to determine the deref size 90081ad6265SDimitry Andric // from DW_OP_piece. 90181ad6265SDimitry Andric bool UseDerefSize = false; 90281ad6265SDimitry Andric unsigned ValueSizeInBits = getLocSizeInBits(*MLoc); 90381ad6265SDimitry Andric unsigned DerefSizeInBytes = ValueSizeInBits / 8; 90481ad6265SDimitry Andric if (auto Fragment = Var.getFragment()) { 90581ad6265SDimitry Andric unsigned VariableSizeInBits = Fragment->SizeInBits; 90681ad6265SDimitry Andric if (VariableSizeInBits != ValueSizeInBits || Expr->isComplex()) 90781ad6265SDimitry Andric UseDerefSize = true; 90881ad6265SDimitry Andric } else if (auto Size = Var.getVariable()->getSizeInBits()) { 90981ad6265SDimitry Andric if (*Size != ValueSizeInBits) { 91081ad6265SDimitry Andric UseDerefSize = true; 91181ad6265SDimitry Andric } 91281ad6265SDimitry Andric } 91381ad6265SDimitry Andric 9144824e7fdSDimitry Andric if (Properties.Indirect) { 91581ad6265SDimitry Andric // This is something like an NRVO variable, where the pointer has been 91681ad6265SDimitry Andric // spilt to the stack, or a dbg.addr pointing at a coroutine frame 91781ad6265SDimitry Andric // field. It should end up being a memory location, with the pointer 91881ad6265SDimitry Andric // to the variable loaded off the stack with a deref. It can't be a 91981ad6265SDimitry Andric // DW_OP_stack_value expression. 92081ad6265SDimitry Andric assert(!Expr->isImplicit()); 92181ad6265SDimitry Andric Expr = TRI.prependOffsetExpression( 92281ad6265SDimitry Andric Expr, DIExpression::ApplyOffset | DIExpression::DerefAfter, 92381ad6265SDimitry Andric Spill.SpillOffset); 92481ad6265SDimitry Andric MIB.addImm(0); 92581ad6265SDimitry Andric } else if (UseDerefSize) { 92681ad6265SDimitry Andric // We're loading a value off the stack that's not the same size as the 92781ad6265SDimitry Andric // variable. Add / subtract stack offset, explicitly deref with a size, 92881ad6265SDimitry Andric // and add DW_OP_stack_value if not already present. 92981ad6265SDimitry Andric SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, 93081ad6265SDimitry Andric DerefSizeInBytes}; 93181ad6265SDimitry Andric Expr = DIExpression::prependOpcodes(Expr, Ops, true); 93281ad6265SDimitry Andric unsigned Flags = DIExpression::StackValue | DIExpression::ApplyOffset; 93381ad6265SDimitry Andric Expr = TRI.prependOffsetExpression(Expr, Flags, Spill.SpillOffset); 93481ad6265SDimitry Andric MIB.addReg(0); 93581ad6265SDimitry Andric } else if (Expr->isComplex()) { 93681ad6265SDimitry Andric // A variable with no size ambiguity, but with extra elements in it's 93781ad6265SDimitry Andric // expression. Manually dereference the stack location. 93881ad6265SDimitry Andric assert(Expr->isComplex()); 93981ad6265SDimitry Andric Expr = TRI.prependOffsetExpression( 94081ad6265SDimitry Andric Expr, DIExpression::ApplyOffset | DIExpression::DerefAfter, 94181ad6265SDimitry Andric Spill.SpillOffset); 94281ad6265SDimitry Andric MIB.addReg(0); 94381ad6265SDimitry Andric } else { 94481ad6265SDimitry Andric // A plain value that has been spilt to the stack, with no further 94581ad6265SDimitry Andric // context. Request a location expression, marking the DBG_VALUE as 94681ad6265SDimitry Andric // IsIndirect. 94781ad6265SDimitry Andric Expr = TRI.prependOffsetExpression(Expr, DIExpression::ApplyOffset, 94881ad6265SDimitry Andric Spill.SpillOffset); 94981ad6265SDimitry Andric MIB.addImm(0); 9504824e7fdSDimitry Andric } 951349cc55cSDimitry Andric } else { 952349cc55cSDimitry Andric // This is a stack location with a weird subregister offset: emit an undef 953349cc55cSDimitry Andric // DBG_VALUE instead. 954349cc55cSDimitry Andric MIB.addReg(0); 955349cc55cSDimitry Andric MIB.addReg(0); 956349cc55cSDimitry Andric } 957349cc55cSDimitry Andric } else { 958349cc55cSDimitry Andric // Non-empty, non-stack slot, must be a plain register. 959349cc55cSDimitry Andric unsigned LocID = LocIdxToLocID[*MLoc]; 960349cc55cSDimitry Andric MIB.addReg(LocID); 961349cc55cSDimitry Andric if (Properties.Indirect) 962349cc55cSDimitry Andric MIB.addImm(0); 963349cc55cSDimitry Andric else 964349cc55cSDimitry Andric MIB.addReg(0); 965349cc55cSDimitry Andric } 966e8d8bef9SDimitry Andric 967349cc55cSDimitry Andric MIB.addMetadata(Var.getVariable()); 968349cc55cSDimitry Andric MIB.addMetadata(Expr); 969349cc55cSDimitry Andric return MIB; 970349cc55cSDimitry Andric } 971e8d8bef9SDimitry Andric 972e8d8bef9SDimitry Andric /// Default construct and initialize the pass. 97381ad6265SDimitry Andric InstrRefBasedLDV::InstrRefBasedLDV() = default; 974e8d8bef9SDimitry Andric 975349cc55cSDimitry Andric bool InstrRefBasedLDV::isCalleeSaved(LocIdx L) const { 976e8d8bef9SDimitry Andric unsigned Reg = MTracker->LocIdxToLocID[L]; 977e8d8bef9SDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 978e8d8bef9SDimitry Andric if (CalleeSavedRegs.test(*RAI)) 979e8d8bef9SDimitry Andric return true; 980e8d8bef9SDimitry Andric return false; 981e8d8bef9SDimitry Andric } 982e8d8bef9SDimitry Andric 983e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 984e8d8bef9SDimitry Andric // Debug Range Extension Implementation 985e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 986e8d8bef9SDimitry Andric 987e8d8bef9SDimitry Andric #ifndef NDEBUG 988e8d8bef9SDimitry Andric // Something to restore in the future. 989e8d8bef9SDimitry Andric // void InstrRefBasedLDV::printVarLocInMBB(..) 990e8d8bef9SDimitry Andric #endif 991e8d8bef9SDimitry Andric 992d56accc7SDimitry Andric Optional<SpillLocationNo> 993e8d8bef9SDimitry Andric InstrRefBasedLDV::extractSpillBaseRegAndOffset(const MachineInstr &MI) { 994e8d8bef9SDimitry Andric assert(MI.hasOneMemOperand() && 995e8d8bef9SDimitry Andric "Spill instruction does not have exactly one memory operand?"); 996e8d8bef9SDimitry Andric auto MMOI = MI.memoperands_begin(); 997e8d8bef9SDimitry Andric const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue(); 998e8d8bef9SDimitry Andric assert(PVal->kind() == PseudoSourceValue::FixedStack && 999e8d8bef9SDimitry Andric "Inconsistent memory operand in spill instruction"); 1000e8d8bef9SDimitry Andric int FI = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex(); 1001e8d8bef9SDimitry Andric const MachineBasicBlock *MBB = MI.getParent(); 1002e8d8bef9SDimitry Andric Register Reg; 1003e8d8bef9SDimitry Andric StackOffset Offset = TFI->getFrameIndexReference(*MBB->getParent(), FI, Reg); 1004349cc55cSDimitry Andric return MTracker->getOrTrackSpillLoc({Reg, Offset}); 1005349cc55cSDimitry Andric } 1006349cc55cSDimitry Andric 1007d56accc7SDimitry Andric Optional<LocIdx> 1008d56accc7SDimitry Andric InstrRefBasedLDV::findLocationForMemOperand(const MachineInstr &MI) { 1009d56accc7SDimitry Andric Optional<SpillLocationNo> SpillLoc = extractSpillBaseRegAndOffset(MI); 1010d56accc7SDimitry Andric if (!SpillLoc) 1011d56accc7SDimitry Andric return None; 1012349cc55cSDimitry Andric 1013349cc55cSDimitry Andric // Where in the stack slot is this value defined -- i.e., what size of value 1014349cc55cSDimitry Andric // is this? An important question, because it could be loaded into a register 1015349cc55cSDimitry Andric // from the stack at some point. Happily the memory operand will tell us 1016349cc55cSDimitry Andric // the size written to the stack. 1017349cc55cSDimitry Andric auto *MemOperand = *MI.memoperands_begin(); 1018349cc55cSDimitry Andric unsigned SizeInBits = MemOperand->getSizeInBits(); 1019349cc55cSDimitry Andric 1020349cc55cSDimitry Andric // Find that position in the stack indexes we're tracking. 1021349cc55cSDimitry Andric auto IdxIt = MTracker->StackSlotIdxes.find({SizeInBits, 0}); 1022349cc55cSDimitry Andric if (IdxIt == MTracker->StackSlotIdxes.end()) 1023349cc55cSDimitry Andric // That index is not tracked. This is suprising, and unlikely to ever 1024349cc55cSDimitry Andric // occur, but the safe action is to indicate the variable is optimised out. 1025349cc55cSDimitry Andric return None; 1026349cc55cSDimitry Andric 1027d56accc7SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillLoc, IdxIt->second); 1028349cc55cSDimitry Andric return MTracker->getSpillMLoc(SpillID); 1029e8d8bef9SDimitry Andric } 1030e8d8bef9SDimitry Andric 1031e8d8bef9SDimitry Andric /// End all previous ranges related to @MI and start a new range from @MI 1032e8d8bef9SDimitry Andric /// if it is a DBG_VALUE instr. 1033e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferDebugValue(const MachineInstr &MI) { 1034e8d8bef9SDimitry Andric if (!MI.isDebugValue()) 1035e8d8bef9SDimitry Andric return false; 1036e8d8bef9SDimitry Andric 1037e8d8bef9SDimitry Andric const DILocalVariable *Var = MI.getDebugVariable(); 1038e8d8bef9SDimitry Andric const DIExpression *Expr = MI.getDebugExpression(); 1039e8d8bef9SDimitry Andric const DILocation *DebugLoc = MI.getDebugLoc(); 1040e8d8bef9SDimitry Andric const DILocation *InlinedAt = DebugLoc->getInlinedAt(); 1041e8d8bef9SDimitry Andric assert(Var->isValidLocationForIntrinsic(DebugLoc) && 1042e8d8bef9SDimitry Andric "Expected inlined-at fields to agree"); 1043e8d8bef9SDimitry Andric 1044e8d8bef9SDimitry Andric DebugVariable V(Var, Expr, InlinedAt); 1045e8d8bef9SDimitry Andric DbgValueProperties Properties(MI); 1046e8d8bef9SDimitry Andric 1047e8d8bef9SDimitry Andric // If there are no instructions in this lexical scope, do no location tracking 1048e8d8bef9SDimitry Andric // at all, this variable shouldn't get a legitimate location range. 1049e8d8bef9SDimitry Andric auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get()); 1050e8d8bef9SDimitry Andric if (Scope == nullptr) 1051e8d8bef9SDimitry Andric return true; // handled it; by doing nothing 1052e8d8bef9SDimitry Andric 1053349cc55cSDimitry Andric // For now, ignore DBG_VALUE_LISTs when extending ranges. Allow it to 1054349cc55cSDimitry Andric // contribute to locations in this block, but don't propagate further. 1055349cc55cSDimitry Andric // Interpret it like a DBG_VALUE $noreg. 1056349cc55cSDimitry Andric if (MI.isDebugValueList()) { 1057349cc55cSDimitry Andric if (VTracker) 1058349cc55cSDimitry Andric VTracker->defVar(MI, Properties, None); 1059349cc55cSDimitry Andric if (TTracker) 1060349cc55cSDimitry Andric TTracker->redefVar(MI, Properties, None); 1061349cc55cSDimitry Andric return true; 1062349cc55cSDimitry Andric } 1063349cc55cSDimitry Andric 1064e8d8bef9SDimitry Andric const MachineOperand &MO = MI.getOperand(0); 1065e8d8bef9SDimitry Andric 1066e8d8bef9SDimitry Andric // MLocTracker needs to know that this register is read, even if it's only 1067e8d8bef9SDimitry Andric // read by a debug inst. 1068e8d8bef9SDimitry Andric if (MO.isReg() && MO.getReg() != 0) 1069e8d8bef9SDimitry Andric (void)MTracker->readReg(MO.getReg()); 1070e8d8bef9SDimitry Andric 1071e8d8bef9SDimitry Andric // If we're preparing for the second analysis (variables), the machine value 1072e8d8bef9SDimitry Andric // locations are already solved, and we report this DBG_VALUE and the value 1073e8d8bef9SDimitry Andric // it refers to to VLocTracker. 1074e8d8bef9SDimitry Andric if (VTracker) { 1075e8d8bef9SDimitry Andric if (MO.isReg()) { 1076e8d8bef9SDimitry Andric // Feed defVar the new variable location, or if this is a 1077e8d8bef9SDimitry Andric // DBG_VALUE $noreg, feed defVar None. 1078e8d8bef9SDimitry Andric if (MO.getReg()) 1079e8d8bef9SDimitry Andric VTracker->defVar(MI, Properties, MTracker->readReg(MO.getReg())); 1080e8d8bef9SDimitry Andric else 1081e8d8bef9SDimitry Andric VTracker->defVar(MI, Properties, None); 1082e8d8bef9SDimitry Andric } else if (MI.getOperand(0).isImm() || MI.getOperand(0).isFPImm() || 1083e8d8bef9SDimitry Andric MI.getOperand(0).isCImm()) { 1084e8d8bef9SDimitry Andric VTracker->defVar(MI, MI.getOperand(0)); 1085e8d8bef9SDimitry Andric } 1086e8d8bef9SDimitry Andric } 1087e8d8bef9SDimitry Andric 1088e8d8bef9SDimitry Andric // If performing final tracking of transfers, report this variable definition 1089e8d8bef9SDimitry Andric // to the TransferTracker too. 1090e8d8bef9SDimitry Andric if (TTracker) 1091e8d8bef9SDimitry Andric TTracker->redefVar(MI); 1092e8d8bef9SDimitry Andric return true; 1093e8d8bef9SDimitry Andric } 1094e8d8bef9SDimitry Andric 1095fe6060f1SDimitry Andric bool InstrRefBasedLDV::transferDebugInstrRef(MachineInstr &MI, 109681ad6265SDimitry Andric const ValueTable *MLiveOuts, 109781ad6265SDimitry Andric const ValueTable *MLiveIns) { 1098e8d8bef9SDimitry Andric if (!MI.isDebugRef()) 1099e8d8bef9SDimitry Andric return false; 1100e8d8bef9SDimitry Andric 1101e8d8bef9SDimitry Andric // Only handle this instruction when we are building the variable value 1102e8d8bef9SDimitry Andric // transfer function. 1103d56accc7SDimitry Andric if (!VTracker && !TTracker) 1104e8d8bef9SDimitry Andric return false; 1105e8d8bef9SDimitry Andric 1106e8d8bef9SDimitry Andric unsigned InstNo = MI.getOperand(0).getImm(); 1107e8d8bef9SDimitry Andric unsigned OpNo = MI.getOperand(1).getImm(); 1108e8d8bef9SDimitry Andric 1109e8d8bef9SDimitry Andric const DILocalVariable *Var = MI.getDebugVariable(); 1110e8d8bef9SDimitry Andric const DIExpression *Expr = MI.getDebugExpression(); 1111e8d8bef9SDimitry Andric const DILocation *DebugLoc = MI.getDebugLoc(); 1112e8d8bef9SDimitry Andric const DILocation *InlinedAt = DebugLoc->getInlinedAt(); 1113e8d8bef9SDimitry Andric assert(Var->isValidLocationForIntrinsic(DebugLoc) && 1114e8d8bef9SDimitry Andric "Expected inlined-at fields to agree"); 1115e8d8bef9SDimitry Andric 1116e8d8bef9SDimitry Andric DebugVariable V(Var, Expr, InlinedAt); 1117e8d8bef9SDimitry Andric 1118e8d8bef9SDimitry Andric auto *Scope = LS.findLexicalScope(MI.getDebugLoc().get()); 1119e8d8bef9SDimitry Andric if (Scope == nullptr) 1120e8d8bef9SDimitry Andric return true; // Handled by doing nothing. This variable is never in scope. 1121e8d8bef9SDimitry Andric 1122e8d8bef9SDimitry Andric const MachineFunction &MF = *MI.getParent()->getParent(); 1123e8d8bef9SDimitry Andric 1124e8d8bef9SDimitry Andric // Various optimizations may have happened to the value during codegen, 1125e8d8bef9SDimitry Andric // recorded in the value substitution table. Apply any substitutions to 1126fe6060f1SDimitry Andric // the instruction / operand number in this DBG_INSTR_REF, and collect 1127fe6060f1SDimitry Andric // any subregister extractions performed during optimization. 1128fe6060f1SDimitry Andric 1129fe6060f1SDimitry Andric // Create dummy substitution with Src set, for lookup. 1130fe6060f1SDimitry Andric auto SoughtSub = 1131fe6060f1SDimitry Andric MachineFunction::DebugSubstitution({InstNo, OpNo}, {0, 0}, 0); 1132fe6060f1SDimitry Andric 1133fe6060f1SDimitry Andric SmallVector<unsigned, 4> SeenSubregs; 1134fe6060f1SDimitry Andric auto LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub); 1135fe6060f1SDimitry Andric while (LowerBoundIt != MF.DebugValueSubstitutions.end() && 1136fe6060f1SDimitry Andric LowerBoundIt->Src == SoughtSub.Src) { 1137fe6060f1SDimitry Andric std::tie(InstNo, OpNo) = LowerBoundIt->Dest; 1138fe6060f1SDimitry Andric SoughtSub.Src = LowerBoundIt->Dest; 1139fe6060f1SDimitry Andric if (unsigned Subreg = LowerBoundIt->Subreg) 1140fe6060f1SDimitry Andric SeenSubregs.push_back(Subreg); 1141fe6060f1SDimitry Andric LowerBoundIt = llvm::lower_bound(MF.DebugValueSubstitutions, SoughtSub); 1142e8d8bef9SDimitry Andric } 1143e8d8bef9SDimitry Andric 1144e8d8bef9SDimitry Andric // Default machine value number is <None> -- if no instruction defines 1145e8d8bef9SDimitry Andric // the corresponding value, it must have been optimized out. 1146e8d8bef9SDimitry Andric Optional<ValueIDNum> NewID = None; 1147e8d8bef9SDimitry Andric 1148e8d8bef9SDimitry Andric // Try to lookup the instruction number, and find the machine value number 1149fe6060f1SDimitry Andric // that it defines. It could be an instruction, or a PHI. 1150e8d8bef9SDimitry Andric auto InstrIt = DebugInstrNumToInstr.find(InstNo); 1151fe6060f1SDimitry Andric auto PHIIt = std::lower_bound(DebugPHINumToValue.begin(), 1152fe6060f1SDimitry Andric DebugPHINumToValue.end(), InstNo); 1153e8d8bef9SDimitry Andric if (InstrIt != DebugInstrNumToInstr.end()) { 1154e8d8bef9SDimitry Andric const MachineInstr &TargetInstr = *InstrIt->second.first; 1155e8d8bef9SDimitry Andric uint64_t BlockNo = TargetInstr.getParent()->getNumber(); 1156e8d8bef9SDimitry Andric 1157349cc55cSDimitry Andric // Pick out the designated operand. It might be a memory reference, if 1158349cc55cSDimitry Andric // a register def was folded into a stack store. 1159349cc55cSDimitry Andric if (OpNo == MachineFunction::DebugOperandMemNumber && 1160349cc55cSDimitry Andric TargetInstr.hasOneMemOperand()) { 1161349cc55cSDimitry Andric Optional<LocIdx> L = findLocationForMemOperand(TargetInstr); 1162349cc55cSDimitry Andric if (L) 1163349cc55cSDimitry Andric NewID = ValueIDNum(BlockNo, InstrIt->second.second, *L); 1164349cc55cSDimitry Andric } else if (OpNo != MachineFunction::DebugOperandMemNumber) { 116581ad6265SDimitry Andric // Permit the debug-info to be completely wrong: identifying a nonexistant 116681ad6265SDimitry Andric // operand, or one that is not a register definition, means something 116781ad6265SDimitry Andric // unexpected happened during optimisation. Broken debug-info, however, 116881ad6265SDimitry Andric // shouldn't crash the compiler -- instead leave the variable value as 116981ad6265SDimitry Andric // None, which will make it appear "optimised out". 117081ad6265SDimitry Andric if (OpNo < TargetInstr.getNumOperands()) { 1171e8d8bef9SDimitry Andric const MachineOperand &MO = TargetInstr.getOperand(OpNo); 1172e8d8bef9SDimitry Andric 117381ad6265SDimitry Andric if (MO.isReg() && MO.isDef() && MO.getReg()) { 1174349cc55cSDimitry Andric unsigned LocID = MTracker->getLocID(MO.getReg()); 1175e8d8bef9SDimitry Andric LocIdx L = MTracker->LocIDToLocIdx[LocID]; 1176e8d8bef9SDimitry Andric NewID = ValueIDNum(BlockNo, InstrIt->second.second, L); 1177349cc55cSDimitry Andric } 117881ad6265SDimitry Andric } 117981ad6265SDimitry Andric 118081ad6265SDimitry Andric if (!NewID) { 118181ad6265SDimitry Andric LLVM_DEBUG( 118281ad6265SDimitry Andric { dbgs() << "Seen instruction reference to illegal operand\n"; }); 118381ad6265SDimitry Andric } 118481ad6265SDimitry Andric } 1185349cc55cSDimitry Andric // else: NewID is left as None. 1186fe6060f1SDimitry Andric } else if (PHIIt != DebugPHINumToValue.end() && PHIIt->InstrNum == InstNo) { 1187fe6060f1SDimitry Andric // It's actually a PHI value. Which value it is might not be obvious, use 1188fe6060f1SDimitry Andric // the resolver helper to find out. 1189fe6060f1SDimitry Andric NewID = resolveDbgPHIs(*MI.getParent()->getParent(), MLiveOuts, MLiveIns, 1190fe6060f1SDimitry Andric MI, InstNo); 1191fe6060f1SDimitry Andric } 1192fe6060f1SDimitry Andric 1193fe6060f1SDimitry Andric // Apply any subregister extractions, in reverse. We might have seen code 1194fe6060f1SDimitry Andric // like this: 1195fe6060f1SDimitry Andric // CALL64 @foo, implicit-def $rax 1196fe6060f1SDimitry Andric // %0:gr64 = COPY $rax 1197fe6060f1SDimitry Andric // %1:gr32 = COPY %0.sub_32bit 1198fe6060f1SDimitry Andric // %2:gr16 = COPY %1.sub_16bit 1199fe6060f1SDimitry Andric // %3:gr8 = COPY %2.sub_8bit 1200fe6060f1SDimitry Andric // In which case each copy would have been recorded as a substitution with 1201fe6060f1SDimitry Andric // a subregister qualifier. Apply those qualifiers now. 1202fe6060f1SDimitry Andric if (NewID && !SeenSubregs.empty()) { 1203fe6060f1SDimitry Andric unsigned Offset = 0; 1204fe6060f1SDimitry Andric unsigned Size = 0; 1205fe6060f1SDimitry Andric 1206fe6060f1SDimitry Andric // Look at each subregister that we passed through, and progressively 1207fe6060f1SDimitry Andric // narrow in, accumulating any offsets that occur. Substitutions should 1208fe6060f1SDimitry Andric // only ever be the same or narrower width than what they read from; 1209fe6060f1SDimitry Andric // iterate in reverse order so that we go from wide to small. 1210fe6060f1SDimitry Andric for (unsigned Subreg : reverse(SeenSubregs)) { 1211fe6060f1SDimitry Andric unsigned ThisSize = TRI->getSubRegIdxSize(Subreg); 1212fe6060f1SDimitry Andric unsigned ThisOffset = TRI->getSubRegIdxOffset(Subreg); 1213fe6060f1SDimitry Andric Offset += ThisOffset; 1214fe6060f1SDimitry Andric Size = (Size == 0) ? ThisSize : std::min(Size, ThisSize); 1215fe6060f1SDimitry Andric } 1216fe6060f1SDimitry Andric 1217fe6060f1SDimitry Andric // If that worked, look for an appropriate subregister with the register 1218fe6060f1SDimitry Andric // where the define happens. Don't look at values that were defined during 1219fe6060f1SDimitry Andric // a stack write: we can't currently express register locations within 1220fe6060f1SDimitry Andric // spills. 1221fe6060f1SDimitry Andric LocIdx L = NewID->getLoc(); 1222fe6060f1SDimitry Andric if (NewID && !MTracker->isSpill(L)) { 1223fe6060f1SDimitry Andric // Find the register class for the register where this def happened. 1224fe6060f1SDimitry Andric // FIXME: no index for this? 1225fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[L]; 1226fe6060f1SDimitry Andric const TargetRegisterClass *TRC = nullptr; 1227fcaf7f86SDimitry Andric for (const auto *TRCI : TRI->regclasses()) 1228fe6060f1SDimitry Andric if (TRCI->contains(Reg)) 1229fe6060f1SDimitry Andric TRC = TRCI; 1230fe6060f1SDimitry Andric assert(TRC && "Couldn't find target register class?"); 1231fe6060f1SDimitry Andric 1232fe6060f1SDimitry Andric // If the register we have isn't the right size or in the right place, 1233fe6060f1SDimitry Andric // Try to find a subregister inside it. 1234fe6060f1SDimitry Andric unsigned MainRegSize = TRI->getRegSizeInBits(*TRC); 1235fe6060f1SDimitry Andric if (Size != MainRegSize || Offset) { 1236fe6060f1SDimitry Andric // Enumerate all subregisters, searching. 1237fe6060f1SDimitry Andric Register NewReg = 0; 1238fe6060f1SDimitry Andric for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { 1239fe6060f1SDimitry Andric unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI); 1240fe6060f1SDimitry Andric unsigned SubregSize = TRI->getSubRegIdxSize(Subreg); 1241fe6060f1SDimitry Andric unsigned SubregOffset = TRI->getSubRegIdxOffset(Subreg); 1242fe6060f1SDimitry Andric if (SubregSize == Size && SubregOffset == Offset) { 1243fe6060f1SDimitry Andric NewReg = *SRI; 1244fe6060f1SDimitry Andric break; 1245fe6060f1SDimitry Andric } 1246fe6060f1SDimitry Andric } 1247fe6060f1SDimitry Andric 1248fe6060f1SDimitry Andric // If we didn't find anything: there's no way to express our value. 1249fe6060f1SDimitry Andric if (!NewReg) { 1250fe6060f1SDimitry Andric NewID = None; 1251fe6060f1SDimitry Andric } else { 1252fe6060f1SDimitry Andric // Re-state the value as being defined within the subregister 1253fe6060f1SDimitry Andric // that we found. 1254fe6060f1SDimitry Andric LocIdx NewLoc = MTracker->lookupOrTrackRegister(NewReg); 1255fe6060f1SDimitry Andric NewID = ValueIDNum(NewID->getBlock(), NewID->getInst(), NewLoc); 1256fe6060f1SDimitry Andric } 1257fe6060f1SDimitry Andric } 1258fe6060f1SDimitry Andric } else { 1259fe6060f1SDimitry Andric // If we can't handle subregisters, unset the new value. 1260fe6060f1SDimitry Andric NewID = None; 1261fe6060f1SDimitry Andric } 1262e8d8bef9SDimitry Andric } 1263e8d8bef9SDimitry Andric 1264e8d8bef9SDimitry Andric // We, we have a value number or None. Tell the variable value tracker about 1265e8d8bef9SDimitry Andric // it. The rest of this LiveDebugValues implementation acts exactly the same 1266e8d8bef9SDimitry Andric // for DBG_INSTR_REFs as DBG_VALUEs (just, the former can refer to values that 1267e8d8bef9SDimitry Andric // aren't immediately available). 1268e8d8bef9SDimitry Andric DbgValueProperties Properties(Expr, false); 1269d56accc7SDimitry Andric if (VTracker) 1270e8d8bef9SDimitry Andric VTracker->defVar(MI, Properties, NewID); 1271e8d8bef9SDimitry Andric 1272e8d8bef9SDimitry Andric // If we're on the final pass through the function, decompose this INSTR_REF 1273e8d8bef9SDimitry Andric // into a plain DBG_VALUE. 1274e8d8bef9SDimitry Andric if (!TTracker) 1275e8d8bef9SDimitry Andric return true; 1276e8d8bef9SDimitry Andric 1277e8d8bef9SDimitry Andric // Pick a location for the machine value number, if such a location exists. 1278e8d8bef9SDimitry Andric // (This information could be stored in TransferTracker to make it faster). 1279e8d8bef9SDimitry Andric Optional<LocIdx> FoundLoc = None; 1280e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 1281e8d8bef9SDimitry Andric LocIdx CurL = Location.Idx; 1282349cc55cSDimitry Andric ValueIDNum ID = MTracker->readMLoc(CurL); 1283e8d8bef9SDimitry Andric if (NewID && ID == NewID) { 1284e8d8bef9SDimitry Andric // If this is the first location with that value, pick it. Otherwise, 1285e8d8bef9SDimitry Andric // consider whether it's a "longer term" location. 1286e8d8bef9SDimitry Andric if (!FoundLoc) { 1287e8d8bef9SDimitry Andric FoundLoc = CurL; 1288e8d8bef9SDimitry Andric continue; 1289e8d8bef9SDimitry Andric } 1290e8d8bef9SDimitry Andric 1291e8d8bef9SDimitry Andric if (MTracker->isSpill(CurL)) 1292e8d8bef9SDimitry Andric FoundLoc = CurL; // Spills are a longer term location. 1293e8d8bef9SDimitry Andric else if (!MTracker->isSpill(*FoundLoc) && 1294e8d8bef9SDimitry Andric !MTracker->isSpill(CurL) && 1295e8d8bef9SDimitry Andric !isCalleeSaved(*FoundLoc) && 1296e8d8bef9SDimitry Andric isCalleeSaved(CurL)) 1297e8d8bef9SDimitry Andric FoundLoc = CurL; // Callee saved regs are longer term than normal. 1298e8d8bef9SDimitry Andric } 1299e8d8bef9SDimitry Andric } 1300e8d8bef9SDimitry Andric 1301e8d8bef9SDimitry Andric // Tell transfer tracker that the variable value has changed. 1302e8d8bef9SDimitry Andric TTracker->redefVar(MI, Properties, FoundLoc); 1303e8d8bef9SDimitry Andric 1304e8d8bef9SDimitry Andric // If there was a value with no location; but the value is defined in a 1305e8d8bef9SDimitry Andric // later instruction in this block, this is a block-local use-before-def. 1306e8d8bef9SDimitry Andric if (!FoundLoc && NewID && NewID->getBlock() == CurBB && 1307e8d8bef9SDimitry Andric NewID->getInst() > CurInst) 1308e8d8bef9SDimitry Andric TTracker->addUseBeforeDef(V, {MI.getDebugExpression(), false}, *NewID); 1309e8d8bef9SDimitry Andric 1310e8d8bef9SDimitry Andric // Produce a DBG_VALUE representing what this DBG_INSTR_REF meant. 1311e8d8bef9SDimitry Andric // This DBG_VALUE is potentially a $noreg / undefined location, if 1312e8d8bef9SDimitry Andric // FoundLoc is None. 1313e8d8bef9SDimitry Andric // (XXX -- could morph the DBG_INSTR_REF in the future). 1314e8d8bef9SDimitry Andric MachineInstr *DbgMI = MTracker->emitLoc(FoundLoc, V, Properties); 1315e8d8bef9SDimitry Andric TTracker->PendingDbgValues.push_back(DbgMI); 1316e8d8bef9SDimitry Andric TTracker->flushDbgValues(MI.getIterator(), nullptr); 1317fe6060f1SDimitry Andric return true; 1318fe6060f1SDimitry Andric } 1319fe6060f1SDimitry Andric 1320fe6060f1SDimitry Andric bool InstrRefBasedLDV::transferDebugPHI(MachineInstr &MI) { 1321fe6060f1SDimitry Andric if (!MI.isDebugPHI()) 1322fe6060f1SDimitry Andric return false; 1323fe6060f1SDimitry Andric 1324fe6060f1SDimitry Andric // Analyse these only when solving the machine value location problem. 1325fe6060f1SDimitry Andric if (VTracker || TTracker) 1326fe6060f1SDimitry Andric return true; 1327fe6060f1SDimitry Andric 1328fe6060f1SDimitry Andric // First operand is the value location, either a stack slot or register. 1329fe6060f1SDimitry Andric // Second is the debug instruction number of the original PHI. 1330fe6060f1SDimitry Andric const MachineOperand &MO = MI.getOperand(0); 1331fe6060f1SDimitry Andric unsigned InstrNum = MI.getOperand(1).getImm(); 1332fe6060f1SDimitry Andric 1333*972a253aSDimitry Andric auto EmitBadPHI = [this, &MI, InstrNum]() -> bool { 133481ad6265SDimitry Andric // Helper lambda to do any accounting when we fail to find a location for 133581ad6265SDimitry Andric // a DBG_PHI. This can happen if DBG_PHIs are malformed, or refer to a 133681ad6265SDimitry Andric // dead stack slot, for example. 133781ad6265SDimitry Andric // Record a DebugPHIRecord with an empty value + location. 133881ad6265SDimitry Andric DebugPHINumToValue.push_back({InstrNum, MI.getParent(), None, None}); 133981ad6265SDimitry Andric return true; 134081ad6265SDimitry Andric }; 134181ad6265SDimitry Andric 134281ad6265SDimitry Andric if (MO.isReg() && MO.getReg()) { 1343fe6060f1SDimitry Andric // The value is whatever's currently in the register. Read and record it, 1344fe6060f1SDimitry Andric // to be analysed later. 1345fe6060f1SDimitry Andric Register Reg = MO.getReg(); 1346fe6060f1SDimitry Andric ValueIDNum Num = MTracker->readReg(Reg); 1347fe6060f1SDimitry Andric auto PHIRec = DebugPHIRecord( 1348fe6060f1SDimitry Andric {InstrNum, MI.getParent(), Num, MTracker->lookupOrTrackRegister(Reg)}); 1349fe6060f1SDimitry Andric DebugPHINumToValue.push_back(PHIRec); 1350349cc55cSDimitry Andric 1351349cc55cSDimitry Andric // Ensure this register is tracked. 1352349cc55cSDimitry Andric for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI) 1353349cc55cSDimitry Andric MTracker->lookupOrTrackRegister(*RAI); 135481ad6265SDimitry Andric } else if (MO.isFI()) { 1355fe6060f1SDimitry Andric // The value is whatever's in this stack slot. 1356fe6060f1SDimitry Andric unsigned FI = MO.getIndex(); 1357fe6060f1SDimitry Andric 1358fe6060f1SDimitry Andric // If the stack slot is dead, then this was optimized away. 1359fe6060f1SDimitry Andric // FIXME: stack slot colouring should account for slots that get merged. 1360fe6060f1SDimitry Andric if (MFI->isDeadObjectIndex(FI)) 136181ad6265SDimitry Andric return EmitBadPHI(); 1362fe6060f1SDimitry Andric 1363349cc55cSDimitry Andric // Identify this spill slot, ensure it's tracked. 1364fe6060f1SDimitry Andric Register Base; 1365fe6060f1SDimitry Andric StackOffset Offs = TFI->getFrameIndexReference(*MI.getMF(), FI, Base); 1366fe6060f1SDimitry Andric SpillLoc SL = {Base, Offs}; 1367d56accc7SDimitry Andric Optional<SpillLocationNo> SpillNo = MTracker->getOrTrackSpillLoc(SL); 1368d56accc7SDimitry Andric 1369d56accc7SDimitry Andric // We might be able to find a value, but have chosen not to, to avoid 1370d56accc7SDimitry Andric // tracking too much stack information. 1371d56accc7SDimitry Andric if (!SpillNo) 137281ad6265SDimitry Andric return EmitBadPHI(); 1373fe6060f1SDimitry Andric 137481ad6265SDimitry Andric // Any stack location DBG_PHI should have an associate bit-size. 137581ad6265SDimitry Andric assert(MI.getNumOperands() == 3 && "Stack DBG_PHI with no size?"); 137681ad6265SDimitry Andric unsigned slotBitSize = MI.getOperand(2).getImm(); 1377349cc55cSDimitry Andric 137881ad6265SDimitry Andric unsigned SpillID = MTracker->getLocID(*SpillNo, {slotBitSize, 0}); 137981ad6265SDimitry Andric LocIdx SpillLoc = MTracker->getSpillMLoc(SpillID); 138081ad6265SDimitry Andric ValueIDNum Result = MTracker->readMLoc(SpillLoc); 1381fe6060f1SDimitry Andric 1382fe6060f1SDimitry Andric // Record this DBG_PHI for later analysis. 138381ad6265SDimitry Andric auto DbgPHI = DebugPHIRecord({InstrNum, MI.getParent(), Result, SpillLoc}); 1384fe6060f1SDimitry Andric DebugPHINumToValue.push_back(DbgPHI); 138581ad6265SDimitry Andric } else { 138681ad6265SDimitry Andric // Else: if the operand is neither a legal register or a stack slot, then 138781ad6265SDimitry Andric // we're being fed illegal debug-info. Record an empty PHI, so that any 138881ad6265SDimitry Andric // debug users trying to read this number will be put off trying to 138981ad6265SDimitry Andric // interpret the value. 139081ad6265SDimitry Andric LLVM_DEBUG( 139181ad6265SDimitry Andric { dbgs() << "Seen DBG_PHI with unrecognised operand format\n"; }); 139281ad6265SDimitry Andric return EmitBadPHI(); 1393fe6060f1SDimitry Andric } 1394e8d8bef9SDimitry Andric 1395e8d8bef9SDimitry Andric return true; 1396e8d8bef9SDimitry Andric } 1397e8d8bef9SDimitry Andric 1398e8d8bef9SDimitry Andric void InstrRefBasedLDV::transferRegisterDef(MachineInstr &MI) { 1399e8d8bef9SDimitry Andric // Meta Instructions do not affect the debug liveness of any register they 1400e8d8bef9SDimitry Andric // define. 1401e8d8bef9SDimitry Andric if (MI.isImplicitDef()) { 1402e8d8bef9SDimitry Andric // Except when there's an implicit def, and the location it's defining has 1403e8d8bef9SDimitry Andric // no value number. The whole point of an implicit def is to announce that 1404e8d8bef9SDimitry Andric // the register is live, without be specific about it's value. So define 1405e8d8bef9SDimitry Andric // a value if there isn't one already. 1406e8d8bef9SDimitry Andric ValueIDNum Num = MTracker->readReg(MI.getOperand(0).getReg()); 1407e8d8bef9SDimitry Andric // Has a legitimate value -> ignore the implicit def. 1408e8d8bef9SDimitry Andric if (Num.getLoc() != 0) 1409e8d8bef9SDimitry Andric return; 1410e8d8bef9SDimitry Andric // Otherwise, def it here. 1411e8d8bef9SDimitry Andric } else if (MI.isMetaInstruction()) 1412e8d8bef9SDimitry Andric return; 1413e8d8bef9SDimitry Andric 14144824e7fdSDimitry Andric // We always ignore SP defines on call instructions, they don't actually 14154824e7fdSDimitry Andric // change the value of the stack pointer... except for win32's _chkstk. This 14164824e7fdSDimitry Andric // is rare: filter quickly for the common case (no stack adjustments, not a 14174824e7fdSDimitry Andric // call, etc). If it is a call that modifies SP, recognise the SP register 14184824e7fdSDimitry Andric // defs. 14194824e7fdSDimitry Andric bool CallChangesSP = false; 14204824e7fdSDimitry Andric if (AdjustsStackInCalls && MI.isCall() && MI.getOperand(0).isSymbol() && 14214824e7fdSDimitry Andric !strcmp(MI.getOperand(0).getSymbolName(), StackProbeSymbolName.data())) 14224824e7fdSDimitry Andric CallChangesSP = true; 14234824e7fdSDimitry Andric 14244824e7fdSDimitry Andric // Test whether we should ignore a def of this register due to it being part 14254824e7fdSDimitry Andric // of the stack pointer. 14264824e7fdSDimitry Andric auto IgnoreSPAlias = [this, &MI, CallChangesSP](Register R) -> bool { 14274824e7fdSDimitry Andric if (CallChangesSP) 14284824e7fdSDimitry Andric return false; 14294824e7fdSDimitry Andric return MI.isCall() && MTracker->SPAliases.count(R); 14304824e7fdSDimitry Andric }; 14314824e7fdSDimitry Andric 1432e8d8bef9SDimitry Andric // Find the regs killed by MI, and find regmasks of preserved regs. 1433e8d8bef9SDimitry Andric // Max out the number of statically allocated elements in `DeadRegs`, as this 1434e8d8bef9SDimitry Andric // prevents fallback to std::set::count() operations. 1435e8d8bef9SDimitry Andric SmallSet<uint32_t, 32> DeadRegs; 1436e8d8bef9SDimitry Andric SmallVector<const uint32_t *, 4> RegMasks; 1437e8d8bef9SDimitry Andric SmallVector<const MachineOperand *, 4> RegMaskPtrs; 1438e8d8bef9SDimitry Andric for (const MachineOperand &MO : MI.operands()) { 1439e8d8bef9SDimitry Andric // Determine whether the operand is a register def. 1440e8d8bef9SDimitry Andric if (MO.isReg() && MO.isDef() && MO.getReg() && 1441e8d8bef9SDimitry Andric Register::isPhysicalRegister(MO.getReg()) && 14424824e7fdSDimitry Andric !IgnoreSPAlias(MO.getReg())) { 1443e8d8bef9SDimitry Andric // Remove ranges of all aliased registers. 1444e8d8bef9SDimitry Andric for (MCRegAliasIterator RAI(MO.getReg(), TRI, true); RAI.isValid(); ++RAI) 1445e8d8bef9SDimitry Andric // FIXME: Can we break out of this loop early if no insertion occurs? 1446e8d8bef9SDimitry Andric DeadRegs.insert(*RAI); 1447e8d8bef9SDimitry Andric } else if (MO.isRegMask()) { 1448e8d8bef9SDimitry Andric RegMasks.push_back(MO.getRegMask()); 1449e8d8bef9SDimitry Andric RegMaskPtrs.push_back(&MO); 1450e8d8bef9SDimitry Andric } 1451e8d8bef9SDimitry Andric } 1452e8d8bef9SDimitry Andric 1453e8d8bef9SDimitry Andric // Tell MLocTracker about all definitions, of regmasks and otherwise. 1454e8d8bef9SDimitry Andric for (uint32_t DeadReg : DeadRegs) 1455e8d8bef9SDimitry Andric MTracker->defReg(DeadReg, CurBB, CurInst); 1456e8d8bef9SDimitry Andric 1457fcaf7f86SDimitry Andric for (const auto *MO : RegMaskPtrs) 1458e8d8bef9SDimitry Andric MTracker->writeRegMask(MO, CurBB, CurInst); 1459fe6060f1SDimitry Andric 1460349cc55cSDimitry Andric // If this instruction writes to a spill slot, def that slot. 1461349cc55cSDimitry Andric if (hasFoldedStackStore(MI)) { 1462d56accc7SDimitry Andric if (Optional<SpillLocationNo> SpillNo = extractSpillBaseRegAndOffset(MI)) { 1463349cc55cSDimitry Andric for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) { 1464d56accc7SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I); 1465349cc55cSDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID); 1466349cc55cSDimitry Andric MTracker->setMLoc(L, ValueIDNum(CurBB, CurInst, L)); 1467349cc55cSDimitry Andric } 1468349cc55cSDimitry Andric } 1469d56accc7SDimitry Andric } 1470349cc55cSDimitry Andric 1471fe6060f1SDimitry Andric if (!TTracker) 1472fe6060f1SDimitry Andric return; 1473fe6060f1SDimitry Andric 1474fe6060f1SDimitry Andric // When committing variable values to locations: tell transfer tracker that 1475fe6060f1SDimitry Andric // we've clobbered things. It may be able to recover the variable from a 1476fe6060f1SDimitry Andric // different location. 1477fe6060f1SDimitry Andric 1478fe6060f1SDimitry Andric // Inform TTracker about any direct clobbers. 1479fe6060f1SDimitry Andric for (uint32_t DeadReg : DeadRegs) { 1480fe6060f1SDimitry Andric LocIdx Loc = MTracker->lookupOrTrackRegister(DeadReg); 1481fe6060f1SDimitry Andric TTracker->clobberMloc(Loc, MI.getIterator(), false); 1482fe6060f1SDimitry Andric } 1483fe6060f1SDimitry Andric 1484fe6060f1SDimitry Andric // Look for any clobbers performed by a register mask. Only test locations 1485fe6060f1SDimitry Andric // that are actually being tracked. 14861fd87a68SDimitry Andric if (!RegMaskPtrs.empty()) { 1487fe6060f1SDimitry Andric for (auto L : MTracker->locations()) { 1488fe6060f1SDimitry Andric // Stack locations can't be clobbered by regmasks. 1489fe6060f1SDimitry Andric if (MTracker->isSpill(L.Idx)) 1490fe6060f1SDimitry Andric continue; 1491fe6060f1SDimitry Andric 1492fe6060f1SDimitry Andric Register Reg = MTracker->LocIdxToLocID[L.Idx]; 14934824e7fdSDimitry Andric if (IgnoreSPAlias(Reg)) 14944824e7fdSDimitry Andric continue; 14954824e7fdSDimitry Andric 1496fcaf7f86SDimitry Andric for (const auto *MO : RegMaskPtrs) 1497fe6060f1SDimitry Andric if (MO->clobbersPhysReg(Reg)) 1498fe6060f1SDimitry Andric TTracker->clobberMloc(L.Idx, MI.getIterator(), false); 1499fe6060f1SDimitry Andric } 15001fd87a68SDimitry Andric } 1501349cc55cSDimitry Andric 1502349cc55cSDimitry Andric // Tell TTracker about any folded stack store. 1503349cc55cSDimitry Andric if (hasFoldedStackStore(MI)) { 1504d56accc7SDimitry Andric if (Optional<SpillLocationNo> SpillNo = extractSpillBaseRegAndOffset(MI)) { 1505349cc55cSDimitry Andric for (unsigned int I = 0; I < MTracker->NumSlotIdxes; ++I) { 1506d56accc7SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*SpillNo, I); 1507349cc55cSDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID); 1508349cc55cSDimitry Andric TTracker->clobberMloc(L, MI.getIterator(), true); 1509349cc55cSDimitry Andric } 1510349cc55cSDimitry Andric } 1511e8d8bef9SDimitry Andric } 1512d56accc7SDimitry Andric } 1513e8d8bef9SDimitry Andric 1514e8d8bef9SDimitry Andric void InstrRefBasedLDV::performCopy(Register SrcRegNum, Register DstRegNum) { 1515349cc55cSDimitry Andric // In all circumstances, re-def all aliases. It's definitely a new value now. 1516349cc55cSDimitry Andric for (MCRegAliasIterator RAI(DstRegNum, TRI, true); RAI.isValid(); ++RAI) 1517349cc55cSDimitry Andric MTracker->defReg(*RAI, CurBB, CurInst); 1518e8d8bef9SDimitry Andric 1519349cc55cSDimitry Andric ValueIDNum SrcValue = MTracker->readReg(SrcRegNum); 1520e8d8bef9SDimitry Andric MTracker->setReg(DstRegNum, SrcValue); 1521e8d8bef9SDimitry Andric 1522349cc55cSDimitry Andric // Copy subregisters from one location to another. 1523e8d8bef9SDimitry Andric for (MCSubRegIndexIterator SRI(SrcRegNum, TRI); SRI.isValid(); ++SRI) { 1524e8d8bef9SDimitry Andric unsigned SrcSubReg = SRI.getSubReg(); 1525e8d8bef9SDimitry Andric unsigned SubRegIdx = SRI.getSubRegIndex(); 1526e8d8bef9SDimitry Andric unsigned DstSubReg = TRI->getSubReg(DstRegNum, SubRegIdx); 1527e8d8bef9SDimitry Andric if (!DstSubReg) 1528e8d8bef9SDimitry Andric continue; 1529e8d8bef9SDimitry Andric 1530e8d8bef9SDimitry Andric // Do copy. There are two matching subregisters, the source value should 1531e8d8bef9SDimitry Andric // have been def'd when the super-reg was, the latter might not be tracked 1532e8d8bef9SDimitry Andric // yet. 1533349cc55cSDimitry Andric // This will force SrcSubReg to be tracked, if it isn't yet. Will read 1534349cc55cSDimitry Andric // mphi values if it wasn't tracked. 1535349cc55cSDimitry Andric LocIdx SrcL = MTracker->lookupOrTrackRegister(SrcSubReg); 1536349cc55cSDimitry Andric LocIdx DstL = MTracker->lookupOrTrackRegister(DstSubReg); 1537349cc55cSDimitry Andric (void)SrcL; 1538e8d8bef9SDimitry Andric (void)DstL; 1539349cc55cSDimitry Andric ValueIDNum CpyValue = MTracker->readReg(SrcSubReg); 1540e8d8bef9SDimitry Andric 1541e8d8bef9SDimitry Andric MTracker->setReg(DstSubReg, CpyValue); 1542e8d8bef9SDimitry Andric } 1543e8d8bef9SDimitry Andric } 1544e8d8bef9SDimitry Andric 1545d56accc7SDimitry Andric Optional<SpillLocationNo> 1546d56accc7SDimitry Andric InstrRefBasedLDV::isSpillInstruction(const MachineInstr &MI, 1547e8d8bef9SDimitry Andric MachineFunction *MF) { 1548e8d8bef9SDimitry Andric // TODO: Handle multiple stores folded into one. 1549e8d8bef9SDimitry Andric if (!MI.hasOneMemOperand()) 1550d56accc7SDimitry Andric return None; 1551e8d8bef9SDimitry Andric 1552349cc55cSDimitry Andric // Reject any memory operand that's aliased -- we can't guarantee its value. 1553349cc55cSDimitry Andric auto MMOI = MI.memoperands_begin(); 1554349cc55cSDimitry Andric const PseudoSourceValue *PVal = (*MMOI)->getPseudoValue(); 1555349cc55cSDimitry Andric if (PVal->isAliased(MFI)) 1556d56accc7SDimitry Andric return None; 1557349cc55cSDimitry Andric 1558e8d8bef9SDimitry Andric if (!MI.getSpillSize(TII) && !MI.getFoldedSpillSize(TII)) 1559d56accc7SDimitry Andric return None; // This is not a spill instruction, since no valid size was 1560e8d8bef9SDimitry Andric // returned from either function. 1561e8d8bef9SDimitry Andric 1562d56accc7SDimitry Andric return extractSpillBaseRegAndOffset(MI); 1563e8d8bef9SDimitry Andric } 1564e8d8bef9SDimitry Andric 1565e8d8bef9SDimitry Andric bool InstrRefBasedLDV::isLocationSpill(const MachineInstr &MI, 1566e8d8bef9SDimitry Andric MachineFunction *MF, unsigned &Reg) { 1567e8d8bef9SDimitry Andric if (!isSpillInstruction(MI, MF)) 1568e8d8bef9SDimitry Andric return false; 1569e8d8bef9SDimitry Andric 1570e8d8bef9SDimitry Andric int FI; 1571e8d8bef9SDimitry Andric Reg = TII->isStoreToStackSlotPostFE(MI, FI); 1572e8d8bef9SDimitry Andric return Reg != 0; 1573e8d8bef9SDimitry Andric } 1574e8d8bef9SDimitry Andric 1575349cc55cSDimitry Andric Optional<SpillLocationNo> 1576e8d8bef9SDimitry Andric InstrRefBasedLDV::isRestoreInstruction(const MachineInstr &MI, 1577e8d8bef9SDimitry Andric MachineFunction *MF, unsigned &Reg) { 1578e8d8bef9SDimitry Andric if (!MI.hasOneMemOperand()) 1579e8d8bef9SDimitry Andric return None; 1580e8d8bef9SDimitry Andric 1581e8d8bef9SDimitry Andric // FIXME: Handle folded restore instructions with more than one memory 1582e8d8bef9SDimitry Andric // operand. 1583e8d8bef9SDimitry Andric if (MI.getRestoreSize(TII)) { 1584e8d8bef9SDimitry Andric Reg = MI.getOperand(0).getReg(); 1585e8d8bef9SDimitry Andric return extractSpillBaseRegAndOffset(MI); 1586e8d8bef9SDimitry Andric } 1587e8d8bef9SDimitry Andric return None; 1588e8d8bef9SDimitry Andric } 1589e8d8bef9SDimitry Andric 1590e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferSpillOrRestoreInst(MachineInstr &MI) { 1591e8d8bef9SDimitry Andric // XXX -- it's too difficult to implement VarLocBasedImpl's stack location 1592e8d8bef9SDimitry Andric // limitations under the new model. Therefore, when comparing them, compare 1593e8d8bef9SDimitry Andric // versions that don't attempt spills or restores at all. 1594e8d8bef9SDimitry Andric if (EmulateOldLDV) 1595e8d8bef9SDimitry Andric return false; 1596e8d8bef9SDimitry Andric 1597349cc55cSDimitry Andric // Strictly limit ourselves to plain loads and stores, not all instructions 1598349cc55cSDimitry Andric // that can access the stack. 1599349cc55cSDimitry Andric int DummyFI = -1; 1600349cc55cSDimitry Andric if (!TII->isStoreToStackSlotPostFE(MI, DummyFI) && 1601349cc55cSDimitry Andric !TII->isLoadFromStackSlotPostFE(MI, DummyFI)) 1602349cc55cSDimitry Andric return false; 1603349cc55cSDimitry Andric 1604e8d8bef9SDimitry Andric MachineFunction *MF = MI.getMF(); 1605e8d8bef9SDimitry Andric unsigned Reg; 1606e8d8bef9SDimitry Andric 1607e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Examining instruction: "; MI.dump();); 1608e8d8bef9SDimitry Andric 1609349cc55cSDimitry Andric // Strictly limit ourselves to plain loads and stores, not all instructions 1610349cc55cSDimitry Andric // that can access the stack. 1611349cc55cSDimitry Andric int FIDummy; 1612349cc55cSDimitry Andric if (!TII->isStoreToStackSlotPostFE(MI, FIDummy) && 1613349cc55cSDimitry Andric !TII->isLoadFromStackSlotPostFE(MI, FIDummy)) 1614349cc55cSDimitry Andric return false; 1615349cc55cSDimitry Andric 1616e8d8bef9SDimitry Andric // First, if there are any DBG_VALUEs pointing at a spill slot that is 1617e8d8bef9SDimitry Andric // written to, terminate that variable location. The value in memory 1618e8d8bef9SDimitry Andric // will have changed. DbgEntityHistoryCalculator doesn't try to detect this. 1619d56accc7SDimitry Andric if (Optional<SpillLocationNo> Loc = isSpillInstruction(MI, MF)) { 1620349cc55cSDimitry Andric // Un-set this location and clobber, so that earlier locations don't 1621349cc55cSDimitry Andric // continue past this store. 1622349cc55cSDimitry Andric for (unsigned SlotIdx = 0; SlotIdx < MTracker->NumSlotIdxes; ++SlotIdx) { 1623d56accc7SDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(*Loc, SlotIdx); 1624349cc55cSDimitry Andric Optional<LocIdx> MLoc = MTracker->getSpillMLoc(SpillID); 1625349cc55cSDimitry Andric if (!MLoc) 1626349cc55cSDimitry Andric continue; 1627349cc55cSDimitry Andric 1628349cc55cSDimitry Andric // We need to over-write the stack slot with something (here, a def at 1629349cc55cSDimitry Andric // this instruction) to ensure no values are preserved in this stack slot 1630349cc55cSDimitry Andric // after the spill. It also prevents TTracker from trying to recover the 1631349cc55cSDimitry Andric // location and re-installing it in the same place. 1632349cc55cSDimitry Andric ValueIDNum Def(CurBB, CurInst, *MLoc); 1633349cc55cSDimitry Andric MTracker->setMLoc(*MLoc, Def); 1634349cc55cSDimitry Andric if (TTracker) 1635e8d8bef9SDimitry Andric TTracker->clobberMloc(*MLoc, MI.getIterator()); 1636e8d8bef9SDimitry Andric } 1637e8d8bef9SDimitry Andric } 1638e8d8bef9SDimitry Andric 1639e8d8bef9SDimitry Andric // Try to recognise spill and restore instructions that may transfer a value. 1640e8d8bef9SDimitry Andric if (isLocationSpill(MI, MF, Reg)) { 1641d56accc7SDimitry Andric // isLocationSpill returning true should guarantee we can extract a 1642d56accc7SDimitry Andric // location. 1643d56accc7SDimitry Andric SpillLocationNo Loc = *extractSpillBaseRegAndOffset(MI); 1644e8d8bef9SDimitry Andric 1645349cc55cSDimitry Andric auto DoTransfer = [&](Register SrcReg, unsigned SpillID) { 1646349cc55cSDimitry Andric auto ReadValue = MTracker->readReg(SrcReg); 1647349cc55cSDimitry Andric LocIdx DstLoc = MTracker->getSpillMLoc(SpillID); 1648349cc55cSDimitry Andric MTracker->setMLoc(DstLoc, ReadValue); 1649e8d8bef9SDimitry Andric 1650349cc55cSDimitry Andric if (TTracker) { 1651349cc55cSDimitry Andric LocIdx SrcLoc = MTracker->getRegMLoc(SrcReg); 1652349cc55cSDimitry Andric TTracker->transferMlocs(SrcLoc, DstLoc, MI.getIterator()); 1653e8d8bef9SDimitry Andric } 1654349cc55cSDimitry Andric }; 1655349cc55cSDimitry Andric 1656349cc55cSDimitry Andric // Then, transfer subreg bits. 1657349cc55cSDimitry Andric for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { 1658349cc55cSDimitry Andric // Ensure this reg is tracked, 1659349cc55cSDimitry Andric (void)MTracker->lookupOrTrackRegister(*SRI); 1660349cc55cSDimitry Andric unsigned SubregIdx = TRI->getSubRegIndex(Reg, *SRI); 1661349cc55cSDimitry Andric unsigned SpillID = MTracker->getLocID(Loc, SubregIdx); 1662349cc55cSDimitry Andric DoTransfer(*SRI, SpillID); 1663349cc55cSDimitry Andric } 1664349cc55cSDimitry Andric 1665349cc55cSDimitry Andric // Directly lookup size of main source reg, and transfer. 1666349cc55cSDimitry Andric unsigned Size = TRI->getRegSizeInBits(Reg, *MRI); 1667349cc55cSDimitry Andric unsigned SpillID = MTracker->getLocID(Loc, {Size, 0}); 1668349cc55cSDimitry Andric DoTransfer(Reg, SpillID); 1669349cc55cSDimitry Andric } else { 1670d56accc7SDimitry Andric Optional<SpillLocationNo> Loc = isRestoreInstruction(MI, MF, Reg); 1671d56accc7SDimitry Andric if (!Loc) 1672349cc55cSDimitry Andric return false; 1673349cc55cSDimitry Andric 1674349cc55cSDimitry Andric // Assumption: we're reading from the base of the stack slot, not some 1675349cc55cSDimitry Andric // offset into it. It seems very unlikely LLVM would ever generate 1676349cc55cSDimitry Andric // restores where this wasn't true. This then becomes a question of what 1677349cc55cSDimitry Andric // subregisters in the destination register line up with positions in the 1678349cc55cSDimitry Andric // stack slot. 1679349cc55cSDimitry Andric 1680349cc55cSDimitry Andric // Def all registers that alias the destination. 1681349cc55cSDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 1682349cc55cSDimitry Andric MTracker->defReg(*RAI, CurBB, CurInst); 1683349cc55cSDimitry Andric 1684349cc55cSDimitry Andric // Now find subregisters within the destination register, and load values 1685349cc55cSDimitry Andric // from stack slot positions. 1686349cc55cSDimitry Andric auto DoTransfer = [&](Register DestReg, unsigned SpillID) { 1687349cc55cSDimitry Andric LocIdx SrcIdx = MTracker->getSpillMLoc(SpillID); 1688349cc55cSDimitry Andric auto ReadValue = MTracker->readMLoc(SrcIdx); 1689349cc55cSDimitry Andric MTracker->setReg(DestReg, ReadValue); 1690349cc55cSDimitry Andric }; 1691349cc55cSDimitry Andric 1692349cc55cSDimitry Andric for (MCSubRegIterator SRI(Reg, TRI, false); SRI.isValid(); ++SRI) { 1693349cc55cSDimitry Andric unsigned Subreg = TRI->getSubRegIndex(Reg, *SRI); 1694d56accc7SDimitry Andric unsigned SpillID = MTracker->getLocID(*Loc, Subreg); 1695349cc55cSDimitry Andric DoTransfer(*SRI, SpillID); 1696349cc55cSDimitry Andric } 1697349cc55cSDimitry Andric 1698349cc55cSDimitry Andric // Directly look up this registers slot idx by size, and transfer. 1699349cc55cSDimitry Andric unsigned Size = TRI->getRegSizeInBits(Reg, *MRI); 1700d56accc7SDimitry Andric unsigned SpillID = MTracker->getLocID(*Loc, {Size, 0}); 1701349cc55cSDimitry Andric DoTransfer(Reg, SpillID); 1702e8d8bef9SDimitry Andric } 1703e8d8bef9SDimitry Andric return true; 1704e8d8bef9SDimitry Andric } 1705e8d8bef9SDimitry Andric 1706e8d8bef9SDimitry Andric bool InstrRefBasedLDV::transferRegisterCopy(MachineInstr &MI) { 1707e8d8bef9SDimitry Andric auto DestSrc = TII->isCopyInstr(MI); 1708e8d8bef9SDimitry Andric if (!DestSrc) 1709e8d8bef9SDimitry Andric return false; 1710e8d8bef9SDimitry Andric 1711e8d8bef9SDimitry Andric const MachineOperand *DestRegOp = DestSrc->Destination; 1712e8d8bef9SDimitry Andric const MachineOperand *SrcRegOp = DestSrc->Source; 1713e8d8bef9SDimitry Andric 1714e8d8bef9SDimitry Andric auto isCalleeSavedReg = [&](unsigned Reg) { 1715e8d8bef9SDimitry Andric for (MCRegAliasIterator RAI(Reg, TRI, true); RAI.isValid(); ++RAI) 1716e8d8bef9SDimitry Andric if (CalleeSavedRegs.test(*RAI)) 1717e8d8bef9SDimitry Andric return true; 1718e8d8bef9SDimitry Andric return false; 1719e8d8bef9SDimitry Andric }; 1720e8d8bef9SDimitry Andric 1721e8d8bef9SDimitry Andric Register SrcReg = SrcRegOp->getReg(); 1722e8d8bef9SDimitry Andric Register DestReg = DestRegOp->getReg(); 1723e8d8bef9SDimitry Andric 1724e8d8bef9SDimitry Andric // Ignore identity copies. Yep, these make it as far as LiveDebugValues. 1725e8d8bef9SDimitry Andric if (SrcReg == DestReg) 1726e8d8bef9SDimitry Andric return true; 1727e8d8bef9SDimitry Andric 1728e8d8bef9SDimitry Andric // For emulating VarLocBasedImpl: 1729e8d8bef9SDimitry Andric // We want to recognize instructions where destination register is callee 1730e8d8bef9SDimitry Andric // saved register. If register that could be clobbered by the call is 1731e8d8bef9SDimitry Andric // included, there would be a great chance that it is going to be clobbered 1732e8d8bef9SDimitry Andric // soon. It is more likely that previous register, which is callee saved, is 1733e8d8bef9SDimitry Andric // going to stay unclobbered longer, even if it is killed. 1734e8d8bef9SDimitry Andric // 1735e8d8bef9SDimitry Andric // For InstrRefBasedImpl, we can track multiple locations per value, so 1736e8d8bef9SDimitry Andric // ignore this condition. 1737e8d8bef9SDimitry Andric if (EmulateOldLDV && !isCalleeSavedReg(DestReg)) 1738e8d8bef9SDimitry Andric return false; 1739e8d8bef9SDimitry Andric 1740e8d8bef9SDimitry Andric // InstrRefBasedImpl only followed killing copies. 1741e8d8bef9SDimitry Andric if (EmulateOldLDV && !SrcRegOp->isKill()) 1742e8d8bef9SDimitry Andric return false; 1743e8d8bef9SDimitry Andric 1744753f127fSDimitry Andric // Before we update MTracker, remember which values were present in each of 1745753f127fSDimitry Andric // the locations about to be overwritten, so that we can recover any 1746753f127fSDimitry Andric // potentially clobbered variables. 1747753f127fSDimitry Andric DenseMap<LocIdx, ValueIDNum> ClobberedLocs; 1748753f127fSDimitry Andric if (TTracker) { 1749753f127fSDimitry Andric for (MCRegAliasIterator RAI(DestReg, TRI, true); RAI.isValid(); ++RAI) { 1750753f127fSDimitry Andric LocIdx ClobberedLoc = MTracker->getRegMLoc(*RAI); 1751753f127fSDimitry Andric auto MLocIt = TTracker->ActiveMLocs.find(ClobberedLoc); 1752753f127fSDimitry Andric // If ActiveMLocs isn't tracking this location or there are no variables 1753753f127fSDimitry Andric // using it, don't bother remembering. 1754753f127fSDimitry Andric if (MLocIt == TTracker->ActiveMLocs.end() || MLocIt->second.empty()) 1755753f127fSDimitry Andric continue; 1756753f127fSDimitry Andric ValueIDNum Value = MTracker->readReg(*RAI); 1757753f127fSDimitry Andric ClobberedLocs[ClobberedLoc] = Value; 1758753f127fSDimitry Andric } 1759753f127fSDimitry Andric } 1760753f127fSDimitry Andric 1761e8d8bef9SDimitry Andric // Copy MTracker info, including subregs if available. 1762e8d8bef9SDimitry Andric InstrRefBasedLDV::performCopy(SrcReg, DestReg); 1763e8d8bef9SDimitry Andric 1764753f127fSDimitry Andric // The copy might have clobbered variables based on the destination register. 1765753f127fSDimitry Andric // Tell TTracker about it, passing the old ValueIDNum to search for 1766753f127fSDimitry Andric // alternative locations (or else terminating those variables). 1767753f127fSDimitry Andric if (TTracker) { 1768753f127fSDimitry Andric for (auto LocVal : ClobberedLocs) { 1769753f127fSDimitry Andric TTracker->clobberMloc(LocVal.first, LocVal.second, MI.getIterator(), false); 1770753f127fSDimitry Andric } 1771753f127fSDimitry Andric } 1772753f127fSDimitry Andric 1773e8d8bef9SDimitry Andric // Only produce a transfer of DBG_VALUE within a block where old LDV 1774e8d8bef9SDimitry Andric // would have. We might make use of the additional value tracking in some 1775e8d8bef9SDimitry Andric // other way, later. 1776e8d8bef9SDimitry Andric if (TTracker && isCalleeSavedReg(DestReg) && SrcRegOp->isKill()) 1777e8d8bef9SDimitry Andric TTracker->transferMlocs(MTracker->getRegMLoc(SrcReg), 1778e8d8bef9SDimitry Andric MTracker->getRegMLoc(DestReg), MI.getIterator()); 1779e8d8bef9SDimitry Andric 1780e8d8bef9SDimitry Andric // VarLocBasedImpl would quit tracking the old location after copying. 1781e8d8bef9SDimitry Andric if (EmulateOldLDV && SrcReg != DestReg) 1782e8d8bef9SDimitry Andric MTracker->defReg(SrcReg, CurBB, CurInst); 1783e8d8bef9SDimitry Andric 1784e8d8bef9SDimitry Andric return true; 1785e8d8bef9SDimitry Andric } 1786e8d8bef9SDimitry Andric 1787e8d8bef9SDimitry Andric /// Accumulate a mapping between each DILocalVariable fragment and other 1788e8d8bef9SDimitry Andric /// fragments of that DILocalVariable which overlap. This reduces work during 1789e8d8bef9SDimitry Andric /// the data-flow stage from "Find any overlapping fragments" to "Check if the 1790e8d8bef9SDimitry Andric /// known-to-overlap fragments are present". 17914824e7fdSDimitry Andric /// \param MI A previously unprocessed debug instruction to analyze for 1792e8d8bef9SDimitry Andric /// fragment usage. 1793e8d8bef9SDimitry Andric void InstrRefBasedLDV::accumulateFragmentMap(MachineInstr &MI) { 17944824e7fdSDimitry Andric assert(MI.isDebugValue() || MI.isDebugRef()); 1795e8d8bef9SDimitry Andric DebugVariable MIVar(MI.getDebugVariable(), MI.getDebugExpression(), 1796e8d8bef9SDimitry Andric MI.getDebugLoc()->getInlinedAt()); 1797e8d8bef9SDimitry Andric FragmentInfo ThisFragment = MIVar.getFragmentOrDefault(); 1798e8d8bef9SDimitry Andric 1799e8d8bef9SDimitry Andric // If this is the first sighting of this variable, then we are guaranteed 1800e8d8bef9SDimitry Andric // there are currently no overlapping fragments either. Initialize the set 1801e8d8bef9SDimitry Andric // of seen fragments, record no overlaps for the current one, and return. 1802e8d8bef9SDimitry Andric auto SeenIt = SeenFragments.find(MIVar.getVariable()); 1803e8d8bef9SDimitry Andric if (SeenIt == SeenFragments.end()) { 1804e8d8bef9SDimitry Andric SmallSet<FragmentInfo, 4> OneFragment; 1805e8d8bef9SDimitry Andric OneFragment.insert(ThisFragment); 1806e8d8bef9SDimitry Andric SeenFragments.insert({MIVar.getVariable(), OneFragment}); 1807e8d8bef9SDimitry Andric 1808e8d8bef9SDimitry Andric OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}}); 1809e8d8bef9SDimitry Andric return; 1810e8d8bef9SDimitry Andric } 1811e8d8bef9SDimitry Andric 1812e8d8bef9SDimitry Andric // If this particular Variable/Fragment pair already exists in the overlap 1813e8d8bef9SDimitry Andric // map, it has already been accounted for. 1814e8d8bef9SDimitry Andric auto IsInOLapMap = 1815e8d8bef9SDimitry Andric OverlapFragments.insert({{MIVar.getVariable(), ThisFragment}, {}}); 1816e8d8bef9SDimitry Andric if (!IsInOLapMap.second) 1817e8d8bef9SDimitry Andric return; 1818e8d8bef9SDimitry Andric 1819e8d8bef9SDimitry Andric auto &ThisFragmentsOverlaps = IsInOLapMap.first->second; 1820e8d8bef9SDimitry Andric auto &AllSeenFragments = SeenIt->second; 1821e8d8bef9SDimitry Andric 1822e8d8bef9SDimitry Andric // Otherwise, examine all other seen fragments for this variable, with "this" 1823e8d8bef9SDimitry Andric // fragment being a previously unseen fragment. Record any pair of 1824e8d8bef9SDimitry Andric // overlapping fragments. 1825fcaf7f86SDimitry Andric for (const auto &ASeenFragment : AllSeenFragments) { 1826e8d8bef9SDimitry Andric // Does this previously seen fragment overlap? 1827e8d8bef9SDimitry Andric if (DIExpression::fragmentsOverlap(ThisFragment, ASeenFragment)) { 1828e8d8bef9SDimitry Andric // Yes: Mark the current fragment as being overlapped. 1829e8d8bef9SDimitry Andric ThisFragmentsOverlaps.push_back(ASeenFragment); 1830e8d8bef9SDimitry Andric // Mark the previously seen fragment as being overlapped by the current 1831e8d8bef9SDimitry Andric // one. 1832e8d8bef9SDimitry Andric auto ASeenFragmentsOverlaps = 1833e8d8bef9SDimitry Andric OverlapFragments.find({MIVar.getVariable(), ASeenFragment}); 1834e8d8bef9SDimitry Andric assert(ASeenFragmentsOverlaps != OverlapFragments.end() && 1835e8d8bef9SDimitry Andric "Previously seen var fragment has no vector of overlaps"); 1836e8d8bef9SDimitry Andric ASeenFragmentsOverlaps->second.push_back(ThisFragment); 1837e8d8bef9SDimitry Andric } 1838e8d8bef9SDimitry Andric } 1839e8d8bef9SDimitry Andric 1840e8d8bef9SDimitry Andric AllSeenFragments.insert(ThisFragment); 1841e8d8bef9SDimitry Andric } 1842e8d8bef9SDimitry Andric 184381ad6265SDimitry Andric void InstrRefBasedLDV::process(MachineInstr &MI, const ValueTable *MLiveOuts, 184481ad6265SDimitry Andric const ValueTable *MLiveIns) { 1845e8d8bef9SDimitry Andric // Try to interpret an MI as a debug or transfer instruction. Only if it's 1846e8d8bef9SDimitry Andric // none of these should we interpret it's register defs as new value 1847e8d8bef9SDimitry Andric // definitions. 1848e8d8bef9SDimitry Andric if (transferDebugValue(MI)) 1849e8d8bef9SDimitry Andric return; 1850fe6060f1SDimitry Andric if (transferDebugInstrRef(MI, MLiveOuts, MLiveIns)) 1851fe6060f1SDimitry Andric return; 1852fe6060f1SDimitry Andric if (transferDebugPHI(MI)) 1853e8d8bef9SDimitry Andric return; 1854e8d8bef9SDimitry Andric if (transferRegisterCopy(MI)) 1855e8d8bef9SDimitry Andric return; 1856e8d8bef9SDimitry Andric if (transferSpillOrRestoreInst(MI)) 1857e8d8bef9SDimitry Andric return; 1858e8d8bef9SDimitry Andric transferRegisterDef(MI); 1859e8d8bef9SDimitry Andric } 1860e8d8bef9SDimitry Andric 1861e8d8bef9SDimitry Andric void InstrRefBasedLDV::produceMLocTransferFunction( 1862e8d8bef9SDimitry Andric MachineFunction &MF, SmallVectorImpl<MLocTransferMap> &MLocTransfer, 1863e8d8bef9SDimitry Andric unsigned MaxNumBlocks) { 1864e8d8bef9SDimitry Andric // Because we try to optimize around register mask operands by ignoring regs 1865e8d8bef9SDimitry Andric // that aren't currently tracked, we set up something ugly for later: RegMask 1866e8d8bef9SDimitry Andric // operands that are seen earlier than the first use of a register, still need 1867e8d8bef9SDimitry Andric // to clobber that register in the transfer function. But this information 1868e8d8bef9SDimitry Andric // isn't actively recorded. Instead, we track each RegMask used in each block, 1869e8d8bef9SDimitry Andric // and accumulated the clobbered but untracked registers in each block into 1870e8d8bef9SDimitry Andric // the following bitvector. Later, if new values are tracked, we can add 1871e8d8bef9SDimitry Andric // appropriate clobbers. 1872e8d8bef9SDimitry Andric SmallVector<BitVector, 32> BlockMasks; 1873e8d8bef9SDimitry Andric BlockMasks.resize(MaxNumBlocks); 1874e8d8bef9SDimitry Andric 1875e8d8bef9SDimitry Andric // Reserve one bit per register for the masks described above. 1876e8d8bef9SDimitry Andric unsigned BVWords = MachineOperand::getRegMaskSize(TRI->getNumRegs()); 1877e8d8bef9SDimitry Andric for (auto &BV : BlockMasks) 1878e8d8bef9SDimitry Andric BV.resize(TRI->getNumRegs(), true); 1879e8d8bef9SDimitry Andric 1880e8d8bef9SDimitry Andric // Step through all instructions and inhale the transfer function. 1881e8d8bef9SDimitry Andric for (auto &MBB : MF) { 1882e8d8bef9SDimitry Andric // Object fields that are read by trackers to know where we are in the 1883e8d8bef9SDimitry Andric // function. 1884e8d8bef9SDimitry Andric CurBB = MBB.getNumber(); 1885e8d8bef9SDimitry Andric CurInst = 1; 1886e8d8bef9SDimitry Andric 1887e8d8bef9SDimitry Andric // Set all machine locations to a PHI value. For transfer function 1888e8d8bef9SDimitry Andric // production only, this signifies the live-in value to the block. 1889e8d8bef9SDimitry Andric MTracker->reset(); 1890e8d8bef9SDimitry Andric MTracker->setMPhis(CurBB); 1891e8d8bef9SDimitry Andric 1892e8d8bef9SDimitry Andric // Step through each instruction in this block. 1893e8d8bef9SDimitry Andric for (auto &MI : MBB) { 189481ad6265SDimitry Andric // Pass in an empty unique_ptr for the value tables when accumulating the 189581ad6265SDimitry Andric // machine transfer function. 189681ad6265SDimitry Andric process(MI, nullptr, nullptr); 189781ad6265SDimitry Andric 1898e8d8bef9SDimitry Andric // Also accumulate fragment map. 18994824e7fdSDimitry Andric if (MI.isDebugValue() || MI.isDebugRef()) 1900e8d8bef9SDimitry Andric accumulateFragmentMap(MI); 1901e8d8bef9SDimitry Andric 1902e8d8bef9SDimitry Andric // Create a map from the instruction number (if present) to the 1903e8d8bef9SDimitry Andric // MachineInstr and its position. 1904e8d8bef9SDimitry Andric if (uint64_t InstrNo = MI.peekDebugInstrNum()) { 1905e8d8bef9SDimitry Andric auto InstrAndPos = std::make_pair(&MI, CurInst); 1906e8d8bef9SDimitry Andric auto InsertResult = 1907e8d8bef9SDimitry Andric DebugInstrNumToInstr.insert(std::make_pair(InstrNo, InstrAndPos)); 1908e8d8bef9SDimitry Andric 1909e8d8bef9SDimitry Andric // There should never be duplicate instruction numbers. 1910e8d8bef9SDimitry Andric assert(InsertResult.second); 1911e8d8bef9SDimitry Andric (void)InsertResult; 1912e8d8bef9SDimitry Andric } 1913e8d8bef9SDimitry Andric 1914e8d8bef9SDimitry Andric ++CurInst; 1915e8d8bef9SDimitry Andric } 1916e8d8bef9SDimitry Andric 1917e8d8bef9SDimitry Andric // Produce the transfer function, a map of machine location to new value. If 1918e8d8bef9SDimitry Andric // any machine location has the live-in phi value from the start of the 1919e8d8bef9SDimitry Andric // block, it's live-through and doesn't need recording in the transfer 1920e8d8bef9SDimitry Andric // function. 1921e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 1922e8d8bef9SDimitry Andric LocIdx Idx = Location.Idx; 1923e8d8bef9SDimitry Andric ValueIDNum &P = Location.Value; 1924e8d8bef9SDimitry Andric if (P.isPHI() && P.getLoc() == Idx.asU64()) 1925e8d8bef9SDimitry Andric continue; 1926e8d8bef9SDimitry Andric 1927e8d8bef9SDimitry Andric // Insert-or-update. 1928e8d8bef9SDimitry Andric auto &TransferMap = MLocTransfer[CurBB]; 1929e8d8bef9SDimitry Andric auto Result = TransferMap.insert(std::make_pair(Idx.asU64(), P)); 1930e8d8bef9SDimitry Andric if (!Result.second) 1931e8d8bef9SDimitry Andric Result.first->second = P; 1932e8d8bef9SDimitry Andric } 1933e8d8bef9SDimitry Andric 1934e8d8bef9SDimitry Andric // Accumulate any bitmask operands into the clobberred reg mask for this 1935e8d8bef9SDimitry Andric // block. 1936e8d8bef9SDimitry Andric for (auto &P : MTracker->Masks) { 1937e8d8bef9SDimitry Andric BlockMasks[CurBB].clearBitsNotInMask(P.first->getRegMask(), BVWords); 1938e8d8bef9SDimitry Andric } 1939e8d8bef9SDimitry Andric } 1940e8d8bef9SDimitry Andric 1941e8d8bef9SDimitry Andric // Compute a bitvector of all the registers that are tracked in this block. 1942e8d8bef9SDimitry Andric BitVector UsedRegs(TRI->getNumRegs()); 1943e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 1944e8d8bef9SDimitry Andric unsigned ID = MTracker->LocIdxToLocID[Location.Idx]; 1945349cc55cSDimitry Andric // Ignore stack slots, and aliases of the stack pointer. 1946349cc55cSDimitry Andric if (ID >= TRI->getNumRegs() || MTracker->SPAliases.count(ID)) 1947e8d8bef9SDimitry Andric continue; 1948e8d8bef9SDimitry Andric UsedRegs.set(ID); 1949e8d8bef9SDimitry Andric } 1950e8d8bef9SDimitry Andric 1951e8d8bef9SDimitry Andric // Check that any regmask-clobber of a register that gets tracked, is not 1952e8d8bef9SDimitry Andric // live-through in the transfer function. It needs to be clobbered at the 1953e8d8bef9SDimitry Andric // very least. 1954e8d8bef9SDimitry Andric for (unsigned int I = 0; I < MaxNumBlocks; ++I) { 1955e8d8bef9SDimitry Andric BitVector &BV = BlockMasks[I]; 1956e8d8bef9SDimitry Andric BV.flip(); 1957e8d8bef9SDimitry Andric BV &= UsedRegs; 1958e8d8bef9SDimitry Andric // This produces all the bits that we clobber, but also use. Check that 1959e8d8bef9SDimitry Andric // they're all clobbered or at least set in the designated transfer 1960e8d8bef9SDimitry Andric // elem. 1961e8d8bef9SDimitry Andric for (unsigned Bit : BV.set_bits()) { 1962349cc55cSDimitry Andric unsigned ID = MTracker->getLocID(Bit); 1963e8d8bef9SDimitry Andric LocIdx Idx = MTracker->LocIDToLocIdx[ID]; 1964e8d8bef9SDimitry Andric auto &TransferMap = MLocTransfer[I]; 1965e8d8bef9SDimitry Andric 1966e8d8bef9SDimitry Andric // Install a value representing the fact that this location is effectively 1967e8d8bef9SDimitry Andric // written to in this block. As there's no reserved value, instead use 1968e8d8bef9SDimitry Andric // a value number that is never generated. Pick the value number for the 1969e8d8bef9SDimitry Andric // first instruction in the block, def'ing this location, which we know 1970e8d8bef9SDimitry Andric // this block never used anyway. 1971e8d8bef9SDimitry Andric ValueIDNum NotGeneratedNum = ValueIDNum(I, 1, Idx); 1972e8d8bef9SDimitry Andric auto Result = 1973e8d8bef9SDimitry Andric TransferMap.insert(std::make_pair(Idx.asU64(), NotGeneratedNum)); 1974e8d8bef9SDimitry Andric if (!Result.second) { 1975e8d8bef9SDimitry Andric ValueIDNum &ValueID = Result.first->second; 1976e8d8bef9SDimitry Andric if (ValueID.getBlock() == I && ValueID.isPHI()) 1977e8d8bef9SDimitry Andric // It was left as live-through. Set it to clobbered. 1978e8d8bef9SDimitry Andric ValueID = NotGeneratedNum; 1979e8d8bef9SDimitry Andric } 1980e8d8bef9SDimitry Andric } 1981e8d8bef9SDimitry Andric } 1982e8d8bef9SDimitry Andric } 1983e8d8bef9SDimitry Andric 1984349cc55cSDimitry Andric bool InstrRefBasedLDV::mlocJoin( 1985349cc55cSDimitry Andric MachineBasicBlock &MBB, SmallPtrSet<const MachineBasicBlock *, 16> &Visited, 198681ad6265SDimitry Andric FuncValueTable &OutLocs, ValueTable &InLocs) { 1987e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n"); 1988e8d8bef9SDimitry Andric bool Changed = false; 1989e8d8bef9SDimitry Andric 1990349cc55cSDimitry Andric // Handle value-propagation when control flow merges on entry to a block. For 1991349cc55cSDimitry Andric // any location without a PHI already placed, the location has the same value 1992349cc55cSDimitry Andric // as its predecessors. If a PHI is placed, test to see whether it's now a 1993349cc55cSDimitry Andric // redundant PHI that we can eliminate. 1994349cc55cSDimitry Andric 1995e8d8bef9SDimitry Andric SmallVector<const MachineBasicBlock *, 8> BlockOrders; 1996fcaf7f86SDimitry Andric for (auto *Pred : MBB.predecessors()) 1997e8d8bef9SDimitry Andric BlockOrders.push_back(Pred); 1998e8d8bef9SDimitry Andric 1999e8d8bef9SDimitry Andric // Visit predecessors in RPOT order. 2000e8d8bef9SDimitry Andric auto Cmp = [&](const MachineBasicBlock *A, const MachineBasicBlock *B) { 2001e8d8bef9SDimitry Andric return BBToOrder.find(A)->second < BBToOrder.find(B)->second; 2002e8d8bef9SDimitry Andric }; 2003e8d8bef9SDimitry Andric llvm::sort(BlockOrders, Cmp); 2004e8d8bef9SDimitry Andric 2005e8d8bef9SDimitry Andric // Skip entry block. 2006e8d8bef9SDimitry Andric if (BlockOrders.size() == 0) 2007349cc55cSDimitry Andric return false; 2008e8d8bef9SDimitry Andric 2009349cc55cSDimitry Andric // Step through all machine locations, look at each predecessor and test 2010349cc55cSDimitry Andric // whether we can eliminate redundant PHIs. 2011e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 2012e8d8bef9SDimitry Andric LocIdx Idx = Location.Idx; 2013349cc55cSDimitry Andric 2014e8d8bef9SDimitry Andric // Pick out the first predecessors live-out value for this location. It's 2015349cc55cSDimitry Andric // guaranteed to not be a backedge, as we order by RPO. 2016349cc55cSDimitry Andric ValueIDNum FirstVal = OutLocs[BlockOrders[0]->getNumber()][Idx.asU64()]; 2017e8d8bef9SDimitry Andric 2018349cc55cSDimitry Andric // If we've already eliminated a PHI here, do no further checking, just 2019349cc55cSDimitry Andric // propagate the first live-in value into this block. 2020349cc55cSDimitry Andric if (InLocs[Idx.asU64()] != ValueIDNum(MBB.getNumber(), 0, Idx)) { 2021349cc55cSDimitry Andric if (InLocs[Idx.asU64()] != FirstVal) { 2022349cc55cSDimitry Andric InLocs[Idx.asU64()] = FirstVal; 2023349cc55cSDimitry Andric Changed |= true; 2024349cc55cSDimitry Andric } 2025349cc55cSDimitry Andric continue; 2026349cc55cSDimitry Andric } 2027349cc55cSDimitry Andric 2028349cc55cSDimitry Andric // We're now examining a PHI to see whether it's un-necessary. Loop around 2029349cc55cSDimitry Andric // the other live-in values and test whether they're all the same. 2030e8d8bef9SDimitry Andric bool Disagree = false; 2031e8d8bef9SDimitry Andric for (unsigned int I = 1; I < BlockOrders.size(); ++I) { 2032349cc55cSDimitry Andric const MachineBasicBlock *PredMBB = BlockOrders[I]; 2033349cc55cSDimitry Andric const ValueIDNum &PredLiveOut = 2034349cc55cSDimitry Andric OutLocs[PredMBB->getNumber()][Idx.asU64()]; 2035349cc55cSDimitry Andric 2036349cc55cSDimitry Andric // Incoming values agree, continue trying to eliminate this PHI. 2037349cc55cSDimitry Andric if (FirstVal == PredLiveOut) 2038349cc55cSDimitry Andric continue; 2039349cc55cSDimitry Andric 2040349cc55cSDimitry Andric // We can also accept a PHI value that feeds back into itself. 2041349cc55cSDimitry Andric if (PredLiveOut == ValueIDNum(MBB.getNumber(), 0, Idx)) 2042349cc55cSDimitry Andric continue; 2043349cc55cSDimitry Andric 2044e8d8bef9SDimitry Andric // Live-out of a predecessor disagrees with the first predecessor. 2045e8d8bef9SDimitry Andric Disagree = true; 2046e8d8bef9SDimitry Andric } 2047e8d8bef9SDimitry Andric 2048349cc55cSDimitry Andric // No disagreement? No PHI. Otherwise, leave the PHI in live-ins. 2049349cc55cSDimitry Andric if (!Disagree) { 2050349cc55cSDimitry Andric InLocs[Idx.asU64()] = FirstVal; 2051e8d8bef9SDimitry Andric Changed |= true; 2052e8d8bef9SDimitry Andric } 2053e8d8bef9SDimitry Andric } 2054e8d8bef9SDimitry Andric 2055e8d8bef9SDimitry Andric // TODO: Reimplement NumInserted and NumRemoved. 2056349cc55cSDimitry Andric return Changed; 2057e8d8bef9SDimitry Andric } 2058e8d8bef9SDimitry Andric 2059349cc55cSDimitry Andric void InstrRefBasedLDV::findStackIndexInterference( 2060349cc55cSDimitry Andric SmallVectorImpl<unsigned> &Slots) { 2061349cc55cSDimitry Andric // We could spend a bit of time finding the exact, minimal, set of stack 2062349cc55cSDimitry Andric // indexes that interfere with each other, much like reg units. Or, we can 2063349cc55cSDimitry Andric // rely on the fact that: 2064349cc55cSDimitry Andric // * The smallest / lowest index will interfere with everything at zero 2065349cc55cSDimitry Andric // offset, which will be the largest set of registers, 2066349cc55cSDimitry Andric // * Most indexes with non-zero offset will end up being interference units 2067349cc55cSDimitry Andric // anyway. 2068349cc55cSDimitry Andric // So just pick those out and return them. 2069349cc55cSDimitry Andric 2070349cc55cSDimitry Andric // We can rely on a single-byte stack index existing already, because we 2071349cc55cSDimitry Andric // initialize them in MLocTracker. 2072349cc55cSDimitry Andric auto It = MTracker->StackSlotIdxes.find({8, 0}); 2073349cc55cSDimitry Andric assert(It != MTracker->StackSlotIdxes.end()); 2074349cc55cSDimitry Andric Slots.push_back(It->second); 2075349cc55cSDimitry Andric 2076349cc55cSDimitry Andric // Find anything that has a non-zero offset and add that too. 2077349cc55cSDimitry Andric for (auto &Pair : MTracker->StackSlotIdxes) { 2078349cc55cSDimitry Andric // Is offset zero? If so, ignore. 2079349cc55cSDimitry Andric if (!Pair.first.second) 2080349cc55cSDimitry Andric continue; 2081349cc55cSDimitry Andric Slots.push_back(Pair.second); 2082349cc55cSDimitry Andric } 2083349cc55cSDimitry Andric } 2084349cc55cSDimitry Andric 2085349cc55cSDimitry Andric void InstrRefBasedLDV::placeMLocPHIs( 2086349cc55cSDimitry Andric MachineFunction &MF, SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 208781ad6265SDimitry Andric FuncValueTable &MInLocs, SmallVectorImpl<MLocTransferMap> &MLocTransfer) { 2088349cc55cSDimitry Andric SmallVector<unsigned, 4> StackUnits; 2089349cc55cSDimitry Andric findStackIndexInterference(StackUnits); 2090349cc55cSDimitry Andric 2091349cc55cSDimitry Andric // To avoid repeatedly running the PHI placement algorithm, leverage the 2092349cc55cSDimitry Andric // fact that a def of register MUST also def its register units. Find the 2093349cc55cSDimitry Andric // units for registers, place PHIs for them, and then replicate them for 2094349cc55cSDimitry Andric // aliasing registers. Some inputs that are never def'd (DBG_PHIs of 2095349cc55cSDimitry Andric // arguments) don't lead to register units being tracked, just place PHIs for 2096349cc55cSDimitry Andric // those registers directly. Stack slots have their own form of "unit", 2097349cc55cSDimitry Andric // store them to one side. 2098349cc55cSDimitry Andric SmallSet<Register, 32> RegUnitsToPHIUp; 2099349cc55cSDimitry Andric SmallSet<LocIdx, 32> NormalLocsToPHI; 2100349cc55cSDimitry Andric SmallSet<SpillLocationNo, 32> StackSlots; 2101349cc55cSDimitry Andric for (auto Location : MTracker->locations()) { 2102349cc55cSDimitry Andric LocIdx L = Location.Idx; 2103349cc55cSDimitry Andric if (MTracker->isSpill(L)) { 2104349cc55cSDimitry Andric StackSlots.insert(MTracker->locIDToSpill(MTracker->LocIdxToLocID[L])); 2105349cc55cSDimitry Andric continue; 2106349cc55cSDimitry Andric } 2107349cc55cSDimitry Andric 2108349cc55cSDimitry Andric Register R = MTracker->LocIdxToLocID[L]; 2109349cc55cSDimitry Andric SmallSet<Register, 8> FoundRegUnits; 2110349cc55cSDimitry Andric bool AnyIllegal = false; 2111349cc55cSDimitry Andric for (MCRegUnitIterator RUI(R.asMCReg(), TRI); RUI.isValid(); ++RUI) { 2112349cc55cSDimitry Andric for (MCRegUnitRootIterator URoot(*RUI, TRI); URoot.isValid(); ++URoot){ 2113349cc55cSDimitry Andric if (!MTracker->isRegisterTracked(*URoot)) { 2114349cc55cSDimitry Andric // Not all roots were loaded into the tracking map: this register 2115349cc55cSDimitry Andric // isn't actually def'd anywhere, we only read from it. Generate PHIs 2116349cc55cSDimitry Andric // for this reg, but don't iterate units. 2117349cc55cSDimitry Andric AnyIllegal = true; 2118349cc55cSDimitry Andric } else { 2119349cc55cSDimitry Andric FoundRegUnits.insert(*URoot); 2120349cc55cSDimitry Andric } 2121349cc55cSDimitry Andric } 2122349cc55cSDimitry Andric } 2123349cc55cSDimitry Andric 2124349cc55cSDimitry Andric if (AnyIllegal) { 2125349cc55cSDimitry Andric NormalLocsToPHI.insert(L); 2126349cc55cSDimitry Andric continue; 2127349cc55cSDimitry Andric } 2128349cc55cSDimitry Andric 2129349cc55cSDimitry Andric RegUnitsToPHIUp.insert(FoundRegUnits.begin(), FoundRegUnits.end()); 2130349cc55cSDimitry Andric } 2131349cc55cSDimitry Andric 2132349cc55cSDimitry Andric // Lambda to fetch PHIs for a given location, and write into the PHIBlocks 2133349cc55cSDimitry Andric // collection. 2134349cc55cSDimitry Andric SmallVector<MachineBasicBlock *, 32> PHIBlocks; 2135349cc55cSDimitry Andric auto CollectPHIsForLoc = [&](LocIdx L) { 2136349cc55cSDimitry Andric // Collect the set of defs. 2137349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> DefBlocks; 2138349cc55cSDimitry Andric for (unsigned int I = 0; I < OrderToBB.size(); ++I) { 2139349cc55cSDimitry Andric MachineBasicBlock *MBB = OrderToBB[I]; 2140349cc55cSDimitry Andric const auto &TransferFunc = MLocTransfer[MBB->getNumber()]; 2141349cc55cSDimitry Andric if (TransferFunc.find(L) != TransferFunc.end()) 2142349cc55cSDimitry Andric DefBlocks.insert(MBB); 2143349cc55cSDimitry Andric } 2144349cc55cSDimitry Andric 2145349cc55cSDimitry Andric // The entry block defs the location too: it's the live-in / argument value. 2146349cc55cSDimitry Andric // Only insert if there are other defs though; everything is trivially live 2147349cc55cSDimitry Andric // through otherwise. 2148349cc55cSDimitry Andric if (!DefBlocks.empty()) 2149349cc55cSDimitry Andric DefBlocks.insert(&*MF.begin()); 2150349cc55cSDimitry Andric 2151349cc55cSDimitry Andric // Ask the SSA construction algorithm where we should put PHIs. Clear 2152349cc55cSDimitry Andric // anything that might have been hanging around from earlier. 2153349cc55cSDimitry Andric PHIBlocks.clear(); 2154349cc55cSDimitry Andric BlockPHIPlacement(AllBlocks, DefBlocks, PHIBlocks); 2155349cc55cSDimitry Andric }; 2156349cc55cSDimitry Andric 2157349cc55cSDimitry Andric auto InstallPHIsAtLoc = [&PHIBlocks, &MInLocs](LocIdx L) { 2158349cc55cSDimitry Andric for (const MachineBasicBlock *MBB : PHIBlocks) 2159349cc55cSDimitry Andric MInLocs[MBB->getNumber()][L.asU64()] = ValueIDNum(MBB->getNumber(), 0, L); 2160349cc55cSDimitry Andric }; 2161349cc55cSDimitry Andric 2162349cc55cSDimitry Andric // For locations with no reg units, just place PHIs. 2163349cc55cSDimitry Andric for (LocIdx L : NormalLocsToPHI) { 2164349cc55cSDimitry Andric CollectPHIsForLoc(L); 2165349cc55cSDimitry Andric // Install those PHI values into the live-in value array. 2166349cc55cSDimitry Andric InstallPHIsAtLoc(L); 2167349cc55cSDimitry Andric } 2168349cc55cSDimitry Andric 2169349cc55cSDimitry Andric // For stack slots, calculate PHIs for the equivalent of the units, then 2170349cc55cSDimitry Andric // install for each index. 2171349cc55cSDimitry Andric for (SpillLocationNo Slot : StackSlots) { 2172349cc55cSDimitry Andric for (unsigned Idx : StackUnits) { 2173349cc55cSDimitry Andric unsigned SpillID = MTracker->getSpillIDWithIdx(Slot, Idx); 2174349cc55cSDimitry Andric LocIdx L = MTracker->getSpillMLoc(SpillID); 2175349cc55cSDimitry Andric CollectPHIsForLoc(L); 2176349cc55cSDimitry Andric InstallPHIsAtLoc(L); 2177349cc55cSDimitry Andric 2178349cc55cSDimitry Andric // Find anything that aliases this stack index, install PHIs for it too. 2179349cc55cSDimitry Andric unsigned Size, Offset; 2180349cc55cSDimitry Andric std::tie(Size, Offset) = MTracker->StackIdxesToPos[Idx]; 2181349cc55cSDimitry Andric for (auto &Pair : MTracker->StackSlotIdxes) { 2182349cc55cSDimitry Andric unsigned ThisSize, ThisOffset; 2183349cc55cSDimitry Andric std::tie(ThisSize, ThisOffset) = Pair.first; 2184349cc55cSDimitry Andric if (ThisSize + ThisOffset <= Offset || Size + Offset <= ThisOffset) 2185349cc55cSDimitry Andric continue; 2186349cc55cSDimitry Andric 2187349cc55cSDimitry Andric unsigned ThisID = MTracker->getSpillIDWithIdx(Slot, Pair.second); 2188349cc55cSDimitry Andric LocIdx ThisL = MTracker->getSpillMLoc(ThisID); 2189349cc55cSDimitry Andric InstallPHIsAtLoc(ThisL); 2190349cc55cSDimitry Andric } 2191349cc55cSDimitry Andric } 2192349cc55cSDimitry Andric } 2193349cc55cSDimitry Andric 2194349cc55cSDimitry Andric // For reg units, place PHIs, and then place them for any aliasing registers. 2195349cc55cSDimitry Andric for (Register R : RegUnitsToPHIUp) { 2196349cc55cSDimitry Andric LocIdx L = MTracker->lookupOrTrackRegister(R); 2197349cc55cSDimitry Andric CollectPHIsForLoc(L); 2198349cc55cSDimitry Andric 2199349cc55cSDimitry Andric // Install those PHI values into the live-in value array. 2200349cc55cSDimitry Andric InstallPHIsAtLoc(L); 2201349cc55cSDimitry Andric 2202349cc55cSDimitry Andric // Now find aliases and install PHIs for those. 2203349cc55cSDimitry Andric for (MCRegAliasIterator RAI(R, TRI, true); RAI.isValid(); ++RAI) { 2204349cc55cSDimitry Andric // Super-registers that are "above" the largest register read/written by 2205349cc55cSDimitry Andric // the function will alias, but will not be tracked. 2206349cc55cSDimitry Andric if (!MTracker->isRegisterTracked(*RAI)) 2207349cc55cSDimitry Andric continue; 2208349cc55cSDimitry Andric 2209349cc55cSDimitry Andric LocIdx AliasLoc = MTracker->lookupOrTrackRegister(*RAI); 2210349cc55cSDimitry Andric InstallPHIsAtLoc(AliasLoc); 2211349cc55cSDimitry Andric } 2212349cc55cSDimitry Andric } 2213349cc55cSDimitry Andric } 2214349cc55cSDimitry Andric 2215349cc55cSDimitry Andric void InstrRefBasedLDV::buildMLocValueMap( 221681ad6265SDimitry Andric MachineFunction &MF, FuncValueTable &MInLocs, FuncValueTable &MOutLocs, 2217e8d8bef9SDimitry Andric SmallVectorImpl<MLocTransferMap> &MLocTransfer) { 2218e8d8bef9SDimitry Andric std::priority_queue<unsigned int, std::vector<unsigned int>, 2219e8d8bef9SDimitry Andric std::greater<unsigned int>> 2220e8d8bef9SDimitry Andric Worklist, Pending; 2221e8d8bef9SDimitry Andric 2222e8d8bef9SDimitry Andric // We track what is on the current and pending worklist to avoid inserting 2223e8d8bef9SDimitry Andric // the same thing twice. We could avoid this with a custom priority queue, 2224e8d8bef9SDimitry Andric // but this is probably not worth it. 2225e8d8bef9SDimitry Andric SmallPtrSet<MachineBasicBlock *, 16> OnPending, OnWorklist; 2226e8d8bef9SDimitry Andric 2227349cc55cSDimitry Andric // Initialize worklist with every block to be visited. Also produce list of 2228349cc55cSDimitry Andric // all blocks. 2229349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> AllBlocks; 2230e8d8bef9SDimitry Andric for (unsigned int I = 0; I < BBToOrder.size(); ++I) { 2231e8d8bef9SDimitry Andric Worklist.push(I); 2232e8d8bef9SDimitry Andric OnWorklist.insert(OrderToBB[I]); 2233349cc55cSDimitry Andric AllBlocks.insert(OrderToBB[I]); 2234e8d8bef9SDimitry Andric } 2235e8d8bef9SDimitry Andric 2236349cc55cSDimitry Andric // Initialize entry block to PHIs. These represent arguments. 2237349cc55cSDimitry Andric for (auto Location : MTracker->locations()) 2238349cc55cSDimitry Andric MInLocs[0][Location.Idx.asU64()] = ValueIDNum(0, 0, Location.Idx); 2239349cc55cSDimitry Andric 2240e8d8bef9SDimitry Andric MTracker->reset(); 2241e8d8bef9SDimitry Andric 2242349cc55cSDimitry Andric // Start by placing PHIs, using the usual SSA constructor algorithm. Consider 2243349cc55cSDimitry Andric // any machine-location that isn't live-through a block to be def'd in that 2244349cc55cSDimitry Andric // block. 2245349cc55cSDimitry Andric placeMLocPHIs(MF, AllBlocks, MInLocs, MLocTransfer); 2246e8d8bef9SDimitry Andric 2247349cc55cSDimitry Andric // Propagate values to eliminate redundant PHIs. At the same time, this 2248349cc55cSDimitry Andric // produces the table of Block x Location => Value for the entry to each 2249349cc55cSDimitry Andric // block. 2250349cc55cSDimitry Andric // The kind of PHIs we can eliminate are, for example, where one path in a 2251349cc55cSDimitry Andric // conditional spills and restores a register, and the register still has 2252349cc55cSDimitry Andric // the same value once control flow joins, unbeknowns to the PHI placement 2253349cc55cSDimitry Andric // code. Propagating values allows us to identify such un-necessary PHIs and 2254349cc55cSDimitry Andric // remove them. 2255e8d8bef9SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 16> Visited; 2256e8d8bef9SDimitry Andric while (!Worklist.empty() || !Pending.empty()) { 2257e8d8bef9SDimitry Andric // Vector for storing the evaluated block transfer function. 2258e8d8bef9SDimitry Andric SmallVector<std::pair<LocIdx, ValueIDNum>, 32> ToRemap; 2259e8d8bef9SDimitry Andric 2260e8d8bef9SDimitry Andric while (!Worklist.empty()) { 2261e8d8bef9SDimitry Andric MachineBasicBlock *MBB = OrderToBB[Worklist.top()]; 2262e8d8bef9SDimitry Andric CurBB = MBB->getNumber(); 2263e8d8bef9SDimitry Andric Worklist.pop(); 2264e8d8bef9SDimitry Andric 2265e8d8bef9SDimitry Andric // Join the values in all predecessor blocks. 2266349cc55cSDimitry Andric bool InLocsChanged; 2267349cc55cSDimitry Andric InLocsChanged = mlocJoin(*MBB, Visited, MOutLocs, MInLocs[CurBB]); 2268e8d8bef9SDimitry Andric InLocsChanged |= Visited.insert(MBB).second; 2269e8d8bef9SDimitry Andric 2270e8d8bef9SDimitry Andric // Don't examine transfer function if we've visited this loc at least 2271e8d8bef9SDimitry Andric // once, and inlocs haven't changed. 2272e8d8bef9SDimitry Andric if (!InLocsChanged) 2273e8d8bef9SDimitry Andric continue; 2274e8d8bef9SDimitry Andric 2275e8d8bef9SDimitry Andric // Load the current set of live-ins into MLocTracker. 2276e8d8bef9SDimitry Andric MTracker->loadFromArray(MInLocs[CurBB], CurBB); 2277e8d8bef9SDimitry Andric 2278e8d8bef9SDimitry Andric // Each element of the transfer function can be a new def, or a read of 2279e8d8bef9SDimitry Andric // a live-in value. Evaluate each element, and store to "ToRemap". 2280e8d8bef9SDimitry Andric ToRemap.clear(); 2281e8d8bef9SDimitry Andric for (auto &P : MLocTransfer[CurBB]) { 2282e8d8bef9SDimitry Andric if (P.second.getBlock() == CurBB && P.second.isPHI()) { 2283e8d8bef9SDimitry Andric // This is a movement of whatever was live in. Read it. 2284349cc55cSDimitry Andric ValueIDNum NewID = MTracker->readMLoc(P.second.getLoc()); 2285e8d8bef9SDimitry Andric ToRemap.push_back(std::make_pair(P.first, NewID)); 2286e8d8bef9SDimitry Andric } else { 2287e8d8bef9SDimitry Andric // It's a def. Just set it. 2288e8d8bef9SDimitry Andric assert(P.second.getBlock() == CurBB); 2289e8d8bef9SDimitry Andric ToRemap.push_back(std::make_pair(P.first, P.second)); 2290e8d8bef9SDimitry Andric } 2291e8d8bef9SDimitry Andric } 2292e8d8bef9SDimitry Andric 2293e8d8bef9SDimitry Andric // Commit the transfer function changes into mloc tracker, which 2294e8d8bef9SDimitry Andric // transforms the contents of the MLocTracker into the live-outs. 2295e8d8bef9SDimitry Andric for (auto &P : ToRemap) 2296e8d8bef9SDimitry Andric MTracker->setMLoc(P.first, P.second); 2297e8d8bef9SDimitry Andric 2298e8d8bef9SDimitry Andric // Now copy out-locs from mloc tracker into out-loc vector, checking 2299e8d8bef9SDimitry Andric // whether changes have occurred. These changes can have come from both 2300e8d8bef9SDimitry Andric // the transfer function, and mlocJoin. 2301e8d8bef9SDimitry Andric bool OLChanged = false; 2302e8d8bef9SDimitry Andric for (auto Location : MTracker->locations()) { 2303e8d8bef9SDimitry Andric OLChanged |= MOutLocs[CurBB][Location.Idx.asU64()] != Location.Value; 2304e8d8bef9SDimitry Andric MOutLocs[CurBB][Location.Idx.asU64()] = Location.Value; 2305e8d8bef9SDimitry Andric } 2306e8d8bef9SDimitry Andric 2307e8d8bef9SDimitry Andric MTracker->reset(); 2308e8d8bef9SDimitry Andric 2309e8d8bef9SDimitry Andric // No need to examine successors again if out-locs didn't change. 2310e8d8bef9SDimitry Andric if (!OLChanged) 2311e8d8bef9SDimitry Andric continue; 2312e8d8bef9SDimitry Andric 2313e8d8bef9SDimitry Andric // All successors should be visited: put any back-edges on the pending 2314349cc55cSDimitry Andric // list for the next pass-through, and any other successors to be 2315349cc55cSDimitry Andric // visited this pass, if they're not going to be already. 2316fcaf7f86SDimitry Andric for (auto *s : MBB->successors()) { 2317e8d8bef9SDimitry Andric // Does branching to this successor represent a back-edge? 2318e8d8bef9SDimitry Andric if (BBToOrder[s] > BBToOrder[MBB]) { 2319e8d8bef9SDimitry Andric // No: visit it during this dataflow iteration. 2320e8d8bef9SDimitry Andric if (OnWorklist.insert(s).second) 2321e8d8bef9SDimitry Andric Worklist.push(BBToOrder[s]); 2322e8d8bef9SDimitry Andric } else { 2323e8d8bef9SDimitry Andric // Yes: visit it on the next iteration. 2324e8d8bef9SDimitry Andric if (OnPending.insert(s).second) 2325e8d8bef9SDimitry Andric Pending.push(BBToOrder[s]); 2326e8d8bef9SDimitry Andric } 2327e8d8bef9SDimitry Andric } 2328e8d8bef9SDimitry Andric } 2329e8d8bef9SDimitry Andric 2330e8d8bef9SDimitry Andric Worklist.swap(Pending); 2331e8d8bef9SDimitry Andric std::swap(OnPending, OnWorklist); 2332e8d8bef9SDimitry Andric OnPending.clear(); 2333e8d8bef9SDimitry Andric // At this point, pending must be empty, since it was just the empty 2334e8d8bef9SDimitry Andric // worklist 2335e8d8bef9SDimitry Andric assert(Pending.empty() && "Pending should be empty"); 2336e8d8bef9SDimitry Andric } 2337e8d8bef9SDimitry Andric 2338349cc55cSDimitry Andric // Once all the live-ins don't change on mlocJoin(), we've eliminated all 2339349cc55cSDimitry Andric // redundant PHIs. 2340e8d8bef9SDimitry Andric } 2341e8d8bef9SDimitry Andric 2342349cc55cSDimitry Andric void InstrRefBasedLDV::BlockPHIPlacement( 2343349cc55cSDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &AllBlocks, 2344349cc55cSDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &DefBlocks, 2345349cc55cSDimitry Andric SmallVectorImpl<MachineBasicBlock *> &PHIBlocks) { 2346349cc55cSDimitry Andric // Apply IDF calculator to the designated set of location defs, storing 2347349cc55cSDimitry Andric // required PHIs into PHIBlocks. Uses the dominator tree stored in the 2348349cc55cSDimitry Andric // InstrRefBasedLDV object. 23491fd87a68SDimitry Andric IDFCalculatorBase<MachineBasicBlock, false> IDF(DomTree->getBase()); 2350349cc55cSDimitry Andric 2351349cc55cSDimitry Andric IDF.setLiveInBlocks(AllBlocks); 2352349cc55cSDimitry Andric IDF.setDefiningBlocks(DefBlocks); 2353349cc55cSDimitry Andric IDF.calculate(PHIBlocks); 2354e8d8bef9SDimitry Andric } 2355e8d8bef9SDimitry Andric 2356349cc55cSDimitry Andric Optional<ValueIDNum> InstrRefBasedLDV::pickVPHILoc( 2357349cc55cSDimitry Andric const MachineBasicBlock &MBB, const DebugVariable &Var, 235881ad6265SDimitry Andric const LiveIdxT &LiveOuts, FuncValueTable &MOutLocs, 2359349cc55cSDimitry Andric const SmallVectorImpl<const MachineBasicBlock *> &BlockOrders) { 2360e8d8bef9SDimitry Andric // Collect a set of locations from predecessor where its live-out value can 2361e8d8bef9SDimitry Andric // be found. 2362e8d8bef9SDimitry Andric SmallVector<SmallVector<LocIdx, 4>, 8> Locs; 2363349cc55cSDimitry Andric SmallVector<const DbgValueProperties *, 4> Properties; 2364e8d8bef9SDimitry Andric unsigned NumLocs = MTracker->getNumLocs(); 2365349cc55cSDimitry Andric 2366349cc55cSDimitry Andric // No predecessors means no PHIs. 2367349cc55cSDimitry Andric if (BlockOrders.empty()) 2368349cc55cSDimitry Andric return None; 2369e8d8bef9SDimitry Andric 2370fcaf7f86SDimitry Andric for (const auto *p : BlockOrders) { 2371e8d8bef9SDimitry Andric unsigned ThisBBNum = p->getNumber(); 2372349cc55cSDimitry Andric auto OutValIt = LiveOuts.find(p); 2373349cc55cSDimitry Andric if (OutValIt == LiveOuts.end()) 2374349cc55cSDimitry Andric // If we have a predecessor not in scope, we'll never find a PHI position. 2375349cc55cSDimitry Andric return None; 2376349cc55cSDimitry Andric const DbgValue &OutVal = *OutValIt->second; 2377e8d8bef9SDimitry Andric 2378e8d8bef9SDimitry Andric if (OutVal.Kind == DbgValue::Const || OutVal.Kind == DbgValue::NoVal) 2379e8d8bef9SDimitry Andric // Consts and no-values cannot have locations we can join on. 2380349cc55cSDimitry Andric return None; 2381e8d8bef9SDimitry Andric 2382349cc55cSDimitry Andric Properties.push_back(&OutVal.Properties); 2383349cc55cSDimitry Andric 2384349cc55cSDimitry Andric // Create new empty vector of locations. 2385349cc55cSDimitry Andric Locs.resize(Locs.size() + 1); 2386349cc55cSDimitry Andric 2387349cc55cSDimitry Andric // If the live-in value is a def, find the locations where that value is 2388349cc55cSDimitry Andric // present. Do the same for VPHIs where we know the VPHI value. 2389349cc55cSDimitry Andric if (OutVal.Kind == DbgValue::Def || 2390349cc55cSDimitry Andric (OutVal.Kind == DbgValue::VPHI && OutVal.BlockNo != MBB.getNumber() && 2391349cc55cSDimitry Andric OutVal.ID != ValueIDNum::EmptyValue)) { 2392e8d8bef9SDimitry Andric ValueIDNum ValToLookFor = OutVal.ID; 2393e8d8bef9SDimitry Andric // Search the live-outs of the predecessor for the specified value. 2394e8d8bef9SDimitry Andric for (unsigned int I = 0; I < NumLocs; ++I) { 2395e8d8bef9SDimitry Andric if (MOutLocs[ThisBBNum][I] == ValToLookFor) 2396e8d8bef9SDimitry Andric Locs.back().push_back(LocIdx(I)); 2397e8d8bef9SDimitry Andric } 2398349cc55cSDimitry Andric } else { 2399349cc55cSDimitry Andric assert(OutVal.Kind == DbgValue::VPHI); 2400349cc55cSDimitry Andric // For VPHIs where we don't know the location, we definitely can't find 2401349cc55cSDimitry Andric // a join loc. 2402349cc55cSDimitry Andric if (OutVal.BlockNo != MBB.getNumber()) 2403349cc55cSDimitry Andric return None; 2404349cc55cSDimitry Andric 2405349cc55cSDimitry Andric // Otherwise: this is a VPHI on a backedge feeding back into itself, i.e. 2406349cc55cSDimitry Andric // a value that's live-through the whole loop. (It has to be a backedge, 2407349cc55cSDimitry Andric // because a block can't dominate itself). We can accept as a PHI location 2408349cc55cSDimitry Andric // any location where the other predecessors agree, _and_ the machine 2409349cc55cSDimitry Andric // locations feed back into themselves. Therefore, add all self-looping 2410349cc55cSDimitry Andric // machine-value PHI locations. 2411349cc55cSDimitry Andric for (unsigned int I = 0; I < NumLocs; ++I) { 2412349cc55cSDimitry Andric ValueIDNum MPHI(MBB.getNumber(), 0, LocIdx(I)); 2413349cc55cSDimitry Andric if (MOutLocs[ThisBBNum][I] == MPHI) 2414349cc55cSDimitry Andric Locs.back().push_back(LocIdx(I)); 2415349cc55cSDimitry Andric } 2416349cc55cSDimitry Andric } 2417e8d8bef9SDimitry Andric } 2418e8d8bef9SDimitry Andric 2419349cc55cSDimitry Andric // We should have found locations for all predecessors, or returned. 2420349cc55cSDimitry Andric assert(Locs.size() == BlockOrders.size()); 2421e8d8bef9SDimitry Andric 2422349cc55cSDimitry Andric // Check that all properties are the same. We can't pick a location if they're 2423349cc55cSDimitry Andric // not. 2424349cc55cSDimitry Andric const DbgValueProperties *Properties0 = Properties[0]; 2425fcaf7f86SDimitry Andric for (const auto *Prop : Properties) 2426349cc55cSDimitry Andric if (*Prop != *Properties0) 2427349cc55cSDimitry Andric return None; 2428349cc55cSDimitry Andric 2429e8d8bef9SDimitry Andric // Starting with the first set of locations, take the intersection with 2430e8d8bef9SDimitry Andric // subsequent sets. 2431349cc55cSDimitry Andric SmallVector<LocIdx, 4> CandidateLocs = Locs[0]; 2432349cc55cSDimitry Andric for (unsigned int I = 1; I < Locs.size(); ++I) { 2433349cc55cSDimitry Andric auto &LocVec = Locs[I]; 2434349cc55cSDimitry Andric SmallVector<LocIdx, 4> NewCandidates; 2435349cc55cSDimitry Andric std::set_intersection(CandidateLocs.begin(), CandidateLocs.end(), 2436349cc55cSDimitry Andric LocVec.begin(), LocVec.end(), std::inserter(NewCandidates, NewCandidates.begin())); 2437349cc55cSDimitry Andric CandidateLocs = NewCandidates; 2438e8d8bef9SDimitry Andric } 2439349cc55cSDimitry Andric if (CandidateLocs.empty()) 2440e8d8bef9SDimitry Andric return None; 2441e8d8bef9SDimitry Andric 2442e8d8bef9SDimitry Andric // We now have a set of LocIdxes that contain the right output value in 2443e8d8bef9SDimitry Andric // each of the predecessors. Pick the lowest; if there's a register loc, 2444e8d8bef9SDimitry Andric // that'll be it. 2445349cc55cSDimitry Andric LocIdx L = *CandidateLocs.begin(); 2446e8d8bef9SDimitry Andric 2447e8d8bef9SDimitry Andric // Return a PHI-value-number for the found location. 2448e8d8bef9SDimitry Andric ValueIDNum PHIVal = {(unsigned)MBB.getNumber(), 0, L}; 2449349cc55cSDimitry Andric return PHIVal; 2450e8d8bef9SDimitry Andric } 2451e8d8bef9SDimitry Andric 2452349cc55cSDimitry Andric bool InstrRefBasedLDV::vlocJoin( 2453349cc55cSDimitry Andric MachineBasicBlock &MBB, LiveIdxT &VLOCOutLocs, 2454e8d8bef9SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> &BlocksToExplore, 2455349cc55cSDimitry Andric DbgValue &LiveIn) { 2456e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "join MBB: " << MBB.getNumber() << "\n"); 2457e8d8bef9SDimitry Andric bool Changed = false; 2458e8d8bef9SDimitry Andric 2459e8d8bef9SDimitry Andric // Order predecessors by RPOT order, for exploring them in that order. 2460fe6060f1SDimitry Andric SmallVector<MachineBasicBlock *, 8> BlockOrders(MBB.predecessors()); 2461e8d8bef9SDimitry Andric 2462e8d8bef9SDimitry Andric auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 2463e8d8bef9SDimitry Andric return BBToOrder[A] < BBToOrder[B]; 2464e8d8bef9SDimitry Andric }; 2465e8d8bef9SDimitry Andric 2466e8d8bef9SDimitry Andric llvm::sort(BlockOrders, Cmp); 2467e8d8bef9SDimitry Andric 2468e8d8bef9SDimitry Andric unsigned CurBlockRPONum = BBToOrder[&MBB]; 2469e8d8bef9SDimitry Andric 2470349cc55cSDimitry Andric // Collect all the incoming DbgValues for this variable, from predecessor 2471349cc55cSDimitry Andric // live-out values. 2472e8d8bef9SDimitry Andric SmallVector<InValueT, 8> Values; 2473e8d8bef9SDimitry Andric bool Bail = false; 2474349cc55cSDimitry Andric int BackEdgesStart = 0; 2475fcaf7f86SDimitry Andric for (auto *p : BlockOrders) { 2476e8d8bef9SDimitry Andric // If the predecessor isn't in scope / to be explored, we'll never be 2477e8d8bef9SDimitry Andric // able to join any locations. 2478e8d8bef9SDimitry Andric if (!BlocksToExplore.contains(p)) { 2479e8d8bef9SDimitry Andric Bail = true; 2480e8d8bef9SDimitry Andric break; 2481e8d8bef9SDimitry Andric } 2482e8d8bef9SDimitry Andric 2483349cc55cSDimitry Andric // All Live-outs will have been initialized. 2484349cc55cSDimitry Andric DbgValue &OutLoc = *VLOCOutLocs.find(p)->second; 2485e8d8bef9SDimitry Andric 2486e8d8bef9SDimitry Andric // Keep track of where back-edges begin in the Values vector. Relies on 2487e8d8bef9SDimitry Andric // BlockOrders being sorted by RPO. 2488e8d8bef9SDimitry Andric unsigned ThisBBRPONum = BBToOrder[p]; 2489e8d8bef9SDimitry Andric if (ThisBBRPONum < CurBlockRPONum) 2490e8d8bef9SDimitry Andric ++BackEdgesStart; 2491e8d8bef9SDimitry Andric 2492349cc55cSDimitry Andric Values.push_back(std::make_pair(p, &OutLoc)); 2493e8d8bef9SDimitry Andric } 2494e8d8bef9SDimitry Andric 2495e8d8bef9SDimitry Andric // If there were no values, or one of the predecessors couldn't have a 2496e8d8bef9SDimitry Andric // value, then give up immediately. It's not safe to produce a live-in 2497349cc55cSDimitry Andric // value. Leave as whatever it was before. 2498e8d8bef9SDimitry Andric if (Bail || Values.size() == 0) 2499349cc55cSDimitry Andric return false; 2500e8d8bef9SDimitry Andric 2501e8d8bef9SDimitry Andric // All (non-entry) blocks have at least one non-backedge predecessor. 2502e8d8bef9SDimitry Andric // Pick the variable value from the first of these, to compare against 2503e8d8bef9SDimitry Andric // all others. 2504e8d8bef9SDimitry Andric const DbgValue &FirstVal = *Values[0].second; 2505e8d8bef9SDimitry Andric 2506349cc55cSDimitry Andric // If the old live-in value is not a PHI then either a) no PHI is needed 2507349cc55cSDimitry Andric // here, or b) we eliminated the PHI that was here. If so, we can just 2508349cc55cSDimitry Andric // propagate in the first parent's incoming value. 2509349cc55cSDimitry Andric if (LiveIn.Kind != DbgValue::VPHI || LiveIn.BlockNo != MBB.getNumber()) { 2510349cc55cSDimitry Andric Changed = LiveIn != FirstVal; 2511349cc55cSDimitry Andric if (Changed) 2512349cc55cSDimitry Andric LiveIn = FirstVal; 2513349cc55cSDimitry Andric return Changed; 2514349cc55cSDimitry Andric } 2515349cc55cSDimitry Andric 2516349cc55cSDimitry Andric // Scan for variable values that can never be resolved: if they have 2517349cc55cSDimitry Andric // different DIExpressions, different indirectness, or are mixed constants / 2518e8d8bef9SDimitry Andric // non-constants. 2519e8d8bef9SDimitry Andric for (auto &V : Values) { 2520e8d8bef9SDimitry Andric if (V.second->Properties != FirstVal.Properties) 2521349cc55cSDimitry Andric return false; 2522349cc55cSDimitry Andric if (V.second->Kind == DbgValue::NoVal) 2523349cc55cSDimitry Andric return false; 2524e8d8bef9SDimitry Andric if (V.second->Kind == DbgValue::Const && FirstVal.Kind != DbgValue::Const) 2525349cc55cSDimitry Andric return false; 2526e8d8bef9SDimitry Andric } 2527e8d8bef9SDimitry Andric 2528349cc55cSDimitry Andric // Try to eliminate this PHI. Do the incoming values all agree? 2529e8d8bef9SDimitry Andric bool Disagree = false; 2530e8d8bef9SDimitry Andric for (auto &V : Values) { 2531e8d8bef9SDimitry Andric if (*V.second == FirstVal) 2532e8d8bef9SDimitry Andric continue; // No disagreement. 2533e8d8bef9SDimitry Andric 2534349cc55cSDimitry Andric // Eliminate if a backedge feeds a VPHI back into itself. 2535349cc55cSDimitry Andric if (V.second->Kind == DbgValue::VPHI && 2536349cc55cSDimitry Andric V.second->BlockNo == MBB.getNumber() && 2537349cc55cSDimitry Andric // Is this a backedge? 2538349cc55cSDimitry Andric std::distance(Values.begin(), &V) >= BackEdgesStart) 2539349cc55cSDimitry Andric continue; 2540349cc55cSDimitry Andric 2541e8d8bef9SDimitry Andric Disagree = true; 2542e8d8bef9SDimitry Andric } 2543e8d8bef9SDimitry Andric 2544349cc55cSDimitry Andric // No disagreement -> live-through value. 2545349cc55cSDimitry Andric if (!Disagree) { 2546349cc55cSDimitry Andric Changed = LiveIn != FirstVal; 2547e8d8bef9SDimitry Andric if (Changed) 2548349cc55cSDimitry Andric LiveIn = FirstVal; 2549349cc55cSDimitry Andric return Changed; 2550349cc55cSDimitry Andric } else { 2551349cc55cSDimitry Andric // Otherwise use a VPHI. 2552349cc55cSDimitry Andric DbgValue VPHI(MBB.getNumber(), FirstVal.Properties, DbgValue::VPHI); 2553349cc55cSDimitry Andric Changed = LiveIn != VPHI; 2554349cc55cSDimitry Andric if (Changed) 2555349cc55cSDimitry Andric LiveIn = VPHI; 2556349cc55cSDimitry Andric return Changed; 2557349cc55cSDimitry Andric } 2558e8d8bef9SDimitry Andric } 2559e8d8bef9SDimitry Andric 25601fd87a68SDimitry Andric void InstrRefBasedLDV::getBlocksForScope( 25611fd87a68SDimitry Andric const DILocation *DILoc, 25621fd87a68SDimitry Andric SmallPtrSetImpl<const MachineBasicBlock *> &BlocksToExplore, 25631fd87a68SDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks) { 25641fd87a68SDimitry Andric // Get the set of "normal" in-lexical-scope blocks. 25651fd87a68SDimitry Andric LS.getMachineBasicBlocks(DILoc, BlocksToExplore); 25661fd87a68SDimitry Andric 25671fd87a68SDimitry Andric // VarLoc LiveDebugValues tracks variable locations that are defined in 25681fd87a68SDimitry Andric // blocks not in scope. This is something we could legitimately ignore, but 25691fd87a68SDimitry Andric // lets allow it for now for the sake of coverage. 25701fd87a68SDimitry Andric BlocksToExplore.insert(AssignBlocks.begin(), AssignBlocks.end()); 25711fd87a68SDimitry Andric 25721fd87a68SDimitry Andric // Storage for artificial blocks we intend to add to BlocksToExplore. 25731fd87a68SDimitry Andric DenseSet<const MachineBasicBlock *> ToAdd; 25741fd87a68SDimitry Andric 25751fd87a68SDimitry Andric // To avoid needlessly dropping large volumes of variable locations, propagate 25761fd87a68SDimitry Andric // variables through aritifical blocks, i.e. those that don't have any 25771fd87a68SDimitry Andric // instructions in scope at all. To accurately replicate VarLoc 25781fd87a68SDimitry Andric // LiveDebugValues, this means exploring all artificial successors too. 25791fd87a68SDimitry Andric // Perform a depth-first-search to enumerate those blocks. 2580fcaf7f86SDimitry Andric for (const auto *MBB : BlocksToExplore) { 25811fd87a68SDimitry Andric // Depth-first-search state: each node is a block and which successor 25821fd87a68SDimitry Andric // we're currently exploring. 25831fd87a68SDimitry Andric SmallVector<std::pair<const MachineBasicBlock *, 25841fd87a68SDimitry Andric MachineBasicBlock::const_succ_iterator>, 25851fd87a68SDimitry Andric 8> 25861fd87a68SDimitry Andric DFS; 25871fd87a68SDimitry Andric 25881fd87a68SDimitry Andric // Find any artificial successors not already tracked. 25891fd87a68SDimitry Andric for (auto *succ : MBB->successors()) { 25901fd87a68SDimitry Andric if (BlocksToExplore.count(succ)) 25911fd87a68SDimitry Andric continue; 25921fd87a68SDimitry Andric if (!ArtificialBlocks.count(succ)) 25931fd87a68SDimitry Andric continue; 25941fd87a68SDimitry Andric ToAdd.insert(succ); 25951fd87a68SDimitry Andric DFS.push_back({succ, succ->succ_begin()}); 25961fd87a68SDimitry Andric } 25971fd87a68SDimitry Andric 25981fd87a68SDimitry Andric // Search all those blocks, depth first. 25991fd87a68SDimitry Andric while (!DFS.empty()) { 26001fd87a68SDimitry Andric const MachineBasicBlock *CurBB = DFS.back().first; 26011fd87a68SDimitry Andric MachineBasicBlock::const_succ_iterator &CurSucc = DFS.back().second; 26021fd87a68SDimitry Andric // Walk back if we've explored this blocks successors to the end. 26031fd87a68SDimitry Andric if (CurSucc == CurBB->succ_end()) { 26041fd87a68SDimitry Andric DFS.pop_back(); 26051fd87a68SDimitry Andric continue; 26061fd87a68SDimitry Andric } 26071fd87a68SDimitry Andric 26081fd87a68SDimitry Andric // If the current successor is artificial and unexplored, descend into 26091fd87a68SDimitry Andric // it. 26101fd87a68SDimitry Andric if (!ToAdd.count(*CurSucc) && ArtificialBlocks.count(*CurSucc)) { 26111fd87a68SDimitry Andric ToAdd.insert(*CurSucc); 26121fd87a68SDimitry Andric DFS.push_back({*CurSucc, (*CurSucc)->succ_begin()}); 26131fd87a68SDimitry Andric continue; 26141fd87a68SDimitry Andric } 26151fd87a68SDimitry Andric 26161fd87a68SDimitry Andric ++CurSucc; 26171fd87a68SDimitry Andric } 26181fd87a68SDimitry Andric }; 26191fd87a68SDimitry Andric 26201fd87a68SDimitry Andric BlocksToExplore.insert(ToAdd.begin(), ToAdd.end()); 26211fd87a68SDimitry Andric } 26221fd87a68SDimitry Andric 26231fd87a68SDimitry Andric void InstrRefBasedLDV::buildVLocValueMap( 26241fd87a68SDimitry Andric const DILocation *DILoc, const SmallSet<DebugVariable, 4> &VarsWeCareAbout, 2625e8d8bef9SDimitry Andric SmallPtrSetImpl<MachineBasicBlock *> &AssignBlocks, LiveInsT &Output, 262681ad6265SDimitry Andric FuncValueTable &MOutLocs, FuncValueTable &MInLocs, 2627e8d8bef9SDimitry Andric SmallVectorImpl<VLocTracker> &AllTheVLocs) { 2628349cc55cSDimitry Andric // This method is much like buildMLocValueMap: but focuses on a single 2629e8d8bef9SDimitry Andric // LexicalScope at a time. Pick out a set of blocks and variables that are 2630e8d8bef9SDimitry Andric // to have their value assignments solved, then run our dataflow algorithm 2631e8d8bef9SDimitry Andric // until a fixedpoint is reached. 2632e8d8bef9SDimitry Andric std::priority_queue<unsigned int, std::vector<unsigned int>, 2633e8d8bef9SDimitry Andric std::greater<unsigned int>> 2634e8d8bef9SDimitry Andric Worklist, Pending; 2635e8d8bef9SDimitry Andric SmallPtrSet<MachineBasicBlock *, 16> OnWorklist, OnPending; 2636e8d8bef9SDimitry Andric 2637e8d8bef9SDimitry Andric // The set of blocks we'll be examining. 2638e8d8bef9SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; 2639e8d8bef9SDimitry Andric 2640e8d8bef9SDimitry Andric // The order in which to examine them (RPO). 2641e8d8bef9SDimitry Andric SmallVector<MachineBasicBlock *, 8> BlockOrders; 2642e8d8bef9SDimitry Andric 2643e8d8bef9SDimitry Andric // RPO ordering function. 2644e8d8bef9SDimitry Andric auto Cmp = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 2645e8d8bef9SDimitry Andric return BBToOrder[A] < BBToOrder[B]; 2646e8d8bef9SDimitry Andric }; 2647e8d8bef9SDimitry Andric 26481fd87a68SDimitry Andric getBlocksForScope(DILoc, BlocksToExplore, AssignBlocks); 2649e8d8bef9SDimitry Andric 2650e8d8bef9SDimitry Andric // Single block scope: not interesting! No propagation at all. Note that 2651e8d8bef9SDimitry Andric // this could probably go above ArtificialBlocks without damage, but 2652e8d8bef9SDimitry Andric // that then produces output differences from original-live-debug-values, 2653e8d8bef9SDimitry Andric // which propagates from a single block into many artificial ones. 2654e8d8bef9SDimitry Andric if (BlocksToExplore.size() == 1) 2655e8d8bef9SDimitry Andric return; 2656e8d8bef9SDimitry Andric 2657349cc55cSDimitry Andric // Convert a const set to a non-const set. LexicalScopes 2658349cc55cSDimitry Andric // getMachineBasicBlocks returns const MBB pointers, IDF wants mutable ones. 2659349cc55cSDimitry Andric // (Neither of them mutate anything). 2660349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 8> MutBlocksToExplore; 2661349cc55cSDimitry Andric for (const auto *MBB : BlocksToExplore) 2662349cc55cSDimitry Andric MutBlocksToExplore.insert(const_cast<MachineBasicBlock *>(MBB)); 2663349cc55cSDimitry Andric 2664e8d8bef9SDimitry Andric // Picks out relevants blocks RPO order and sort them. 2665fcaf7f86SDimitry Andric for (const auto *MBB : BlocksToExplore) 2666e8d8bef9SDimitry Andric BlockOrders.push_back(const_cast<MachineBasicBlock *>(MBB)); 2667e8d8bef9SDimitry Andric 2668e8d8bef9SDimitry Andric llvm::sort(BlockOrders, Cmp); 2669e8d8bef9SDimitry Andric unsigned NumBlocks = BlockOrders.size(); 2670e8d8bef9SDimitry Andric 2671e8d8bef9SDimitry Andric // Allocate some vectors for storing the live ins and live outs. Large. 2672349cc55cSDimitry Andric SmallVector<DbgValue, 32> LiveIns, LiveOuts; 2673349cc55cSDimitry Andric LiveIns.reserve(NumBlocks); 2674349cc55cSDimitry Andric LiveOuts.reserve(NumBlocks); 2675349cc55cSDimitry Andric 2676349cc55cSDimitry Andric // Initialize all values to start as NoVals. This signifies "it's live 2677349cc55cSDimitry Andric // through, but we don't know what it is". 2678349cc55cSDimitry Andric DbgValueProperties EmptyProperties(EmptyExpr, false); 2679349cc55cSDimitry Andric for (unsigned int I = 0; I < NumBlocks; ++I) { 2680349cc55cSDimitry Andric DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal); 2681349cc55cSDimitry Andric LiveIns.push_back(EmptyDbgValue); 2682349cc55cSDimitry Andric LiveOuts.push_back(EmptyDbgValue); 2683349cc55cSDimitry Andric } 2684e8d8bef9SDimitry Andric 2685e8d8bef9SDimitry Andric // Produce by-MBB indexes of live-in/live-outs, to ease lookup within 2686e8d8bef9SDimitry Andric // vlocJoin. 2687e8d8bef9SDimitry Andric LiveIdxT LiveOutIdx, LiveInIdx; 2688e8d8bef9SDimitry Andric LiveOutIdx.reserve(NumBlocks); 2689e8d8bef9SDimitry Andric LiveInIdx.reserve(NumBlocks); 2690e8d8bef9SDimitry Andric for (unsigned I = 0; I < NumBlocks; ++I) { 2691e8d8bef9SDimitry Andric LiveOutIdx[BlockOrders[I]] = &LiveOuts[I]; 2692e8d8bef9SDimitry Andric LiveInIdx[BlockOrders[I]] = &LiveIns[I]; 2693e8d8bef9SDimitry Andric } 2694e8d8bef9SDimitry Andric 2695349cc55cSDimitry Andric // Loop over each variable and place PHIs for it, then propagate values 2696349cc55cSDimitry Andric // between blocks. This keeps the locality of working on one lexical scope at 2697349cc55cSDimitry Andric // at time, but avoids re-processing variable values because some other 2698349cc55cSDimitry Andric // variable has been assigned. 2699fcaf7f86SDimitry Andric for (const auto &Var : VarsWeCareAbout) { 2700349cc55cSDimitry Andric // Re-initialize live-ins and live-outs, to clear the remains of previous 2701349cc55cSDimitry Andric // variables live-ins / live-outs. 2702349cc55cSDimitry Andric for (unsigned int I = 0; I < NumBlocks; ++I) { 2703349cc55cSDimitry Andric DbgValue EmptyDbgValue(I, EmptyProperties, DbgValue::NoVal); 2704349cc55cSDimitry Andric LiveIns[I] = EmptyDbgValue; 2705349cc55cSDimitry Andric LiveOuts[I] = EmptyDbgValue; 2706349cc55cSDimitry Andric } 2707349cc55cSDimitry Andric 2708349cc55cSDimitry Andric // Place PHIs for variable values, using the LLVM IDF calculator. 2709349cc55cSDimitry Andric // Collect the set of blocks where variables are def'd. 2710349cc55cSDimitry Andric SmallPtrSet<MachineBasicBlock *, 32> DefBlocks; 2711349cc55cSDimitry Andric for (const MachineBasicBlock *ExpMBB : BlocksToExplore) { 2712349cc55cSDimitry Andric auto &TransferFunc = AllTheVLocs[ExpMBB->getNumber()].Vars; 2713349cc55cSDimitry Andric if (TransferFunc.find(Var) != TransferFunc.end()) 2714349cc55cSDimitry Andric DefBlocks.insert(const_cast<MachineBasicBlock *>(ExpMBB)); 2715349cc55cSDimitry Andric } 2716349cc55cSDimitry Andric 2717349cc55cSDimitry Andric SmallVector<MachineBasicBlock *, 32> PHIBlocks; 2718349cc55cSDimitry Andric 27191fd87a68SDimitry Andric // Request the set of PHIs we should insert for this variable. If there's 27201fd87a68SDimitry Andric // only one value definition, things are very simple. 27211fd87a68SDimitry Andric if (DefBlocks.size() == 1) { 27221fd87a68SDimitry Andric placePHIsForSingleVarDefinition(MutBlocksToExplore, *DefBlocks.begin(), 27231fd87a68SDimitry Andric AllTheVLocs, Var, Output); 27241fd87a68SDimitry Andric continue; 27251fd87a68SDimitry Andric } 27261fd87a68SDimitry Andric 27271fd87a68SDimitry Andric // Otherwise: we need to place PHIs through SSA and propagate values. 2728349cc55cSDimitry Andric BlockPHIPlacement(MutBlocksToExplore, DefBlocks, PHIBlocks); 2729349cc55cSDimitry Andric 2730349cc55cSDimitry Andric // Insert PHIs into the per-block live-in tables for this variable. 2731349cc55cSDimitry Andric for (MachineBasicBlock *PHIMBB : PHIBlocks) { 2732349cc55cSDimitry Andric unsigned BlockNo = PHIMBB->getNumber(); 2733349cc55cSDimitry Andric DbgValue *LiveIn = LiveInIdx[PHIMBB]; 2734349cc55cSDimitry Andric *LiveIn = DbgValue(BlockNo, EmptyProperties, DbgValue::VPHI); 2735349cc55cSDimitry Andric } 2736349cc55cSDimitry Andric 2737e8d8bef9SDimitry Andric for (auto *MBB : BlockOrders) { 2738e8d8bef9SDimitry Andric Worklist.push(BBToOrder[MBB]); 2739e8d8bef9SDimitry Andric OnWorklist.insert(MBB); 2740e8d8bef9SDimitry Andric } 2741e8d8bef9SDimitry Andric 2742349cc55cSDimitry Andric // Iterate over all the blocks we selected, propagating the variables value. 2743349cc55cSDimitry Andric // This loop does two things: 2744349cc55cSDimitry Andric // * Eliminates un-necessary VPHIs in vlocJoin, 2745349cc55cSDimitry Andric // * Evaluates the blocks transfer function (i.e. variable assignments) and 2746349cc55cSDimitry Andric // stores the result to the blocks live-outs. 2747349cc55cSDimitry Andric // Always evaluate the transfer function on the first iteration, and when 2748349cc55cSDimitry Andric // the live-ins change thereafter. 2749e8d8bef9SDimitry Andric bool FirstTrip = true; 2750e8d8bef9SDimitry Andric while (!Worklist.empty() || !Pending.empty()) { 2751e8d8bef9SDimitry Andric while (!Worklist.empty()) { 2752e8d8bef9SDimitry Andric auto *MBB = OrderToBB[Worklist.top()]; 2753e8d8bef9SDimitry Andric CurBB = MBB->getNumber(); 2754e8d8bef9SDimitry Andric Worklist.pop(); 2755e8d8bef9SDimitry Andric 2756349cc55cSDimitry Andric auto LiveInsIt = LiveInIdx.find(MBB); 2757349cc55cSDimitry Andric assert(LiveInsIt != LiveInIdx.end()); 2758349cc55cSDimitry Andric DbgValue *LiveIn = LiveInsIt->second; 2759e8d8bef9SDimitry Andric 2760e8d8bef9SDimitry Andric // Join values from predecessors. Updates LiveInIdx, and writes output 2761e8d8bef9SDimitry Andric // into JoinedInLocs. 2762349cc55cSDimitry Andric bool InLocsChanged = 27634824e7fdSDimitry Andric vlocJoin(*MBB, LiveOutIdx, BlocksToExplore, *LiveIn); 2764e8d8bef9SDimitry Andric 2765349cc55cSDimitry Andric SmallVector<const MachineBasicBlock *, 8> Preds; 2766349cc55cSDimitry Andric for (const auto *Pred : MBB->predecessors()) 2767349cc55cSDimitry Andric Preds.push_back(Pred); 2768e8d8bef9SDimitry Andric 2769349cc55cSDimitry Andric // If this block's live-in value is a VPHI, try to pick a machine-value 2770349cc55cSDimitry Andric // for it. This makes the machine-value available and propagated 2771349cc55cSDimitry Andric // through all blocks by the time value propagation finishes. We can't 2772349cc55cSDimitry Andric // do this any earlier as it needs to read the block live-outs. 2773349cc55cSDimitry Andric if (LiveIn->Kind == DbgValue::VPHI && LiveIn->BlockNo == (int)CurBB) { 2774349cc55cSDimitry Andric // There's a small possibility that on a preceeding path, a VPHI is 2775349cc55cSDimitry Andric // eliminated and transitions from VPHI-with-location to 2776349cc55cSDimitry Andric // live-through-value. As a result, the selected location of any VPHI 2777349cc55cSDimitry Andric // might change, so we need to re-compute it on each iteration. 2778349cc55cSDimitry Andric Optional<ValueIDNum> ValueNum = 2779349cc55cSDimitry Andric pickVPHILoc(*MBB, Var, LiveOutIdx, MOutLocs, Preds); 2780e8d8bef9SDimitry Andric 2781349cc55cSDimitry Andric if (ValueNum) { 2782349cc55cSDimitry Andric InLocsChanged |= LiveIn->ID != *ValueNum; 2783349cc55cSDimitry Andric LiveIn->ID = *ValueNum; 2784349cc55cSDimitry Andric } 2785349cc55cSDimitry Andric } 2786e8d8bef9SDimitry Andric 2787349cc55cSDimitry Andric if (!InLocsChanged && !FirstTrip) 2788e8d8bef9SDimitry Andric continue; 2789e8d8bef9SDimitry Andric 2790349cc55cSDimitry Andric DbgValue *LiveOut = LiveOutIdx[MBB]; 2791349cc55cSDimitry Andric bool OLChanged = false; 2792349cc55cSDimitry Andric 2793e8d8bef9SDimitry Andric // Do transfer function. 2794e8d8bef9SDimitry Andric auto &VTracker = AllTheVLocs[MBB->getNumber()]; 2795349cc55cSDimitry Andric auto TransferIt = VTracker.Vars.find(Var); 2796349cc55cSDimitry Andric if (TransferIt != VTracker.Vars.end()) { 2797e8d8bef9SDimitry Andric // Erase on empty transfer (DBG_VALUE $noreg). 2798349cc55cSDimitry Andric if (TransferIt->second.Kind == DbgValue::Undef) { 2799349cc55cSDimitry Andric DbgValue NewVal(MBB->getNumber(), EmptyProperties, DbgValue::NoVal); 2800349cc55cSDimitry Andric if (*LiveOut != NewVal) { 2801349cc55cSDimitry Andric *LiveOut = NewVal; 2802349cc55cSDimitry Andric OLChanged = true; 2803349cc55cSDimitry Andric } 2804e8d8bef9SDimitry Andric } else { 2805e8d8bef9SDimitry Andric // Insert new variable value; or overwrite. 2806349cc55cSDimitry Andric if (*LiveOut != TransferIt->second) { 2807349cc55cSDimitry Andric *LiveOut = TransferIt->second; 2808349cc55cSDimitry Andric OLChanged = true; 2809e8d8bef9SDimitry Andric } 2810e8d8bef9SDimitry Andric } 2811349cc55cSDimitry Andric } else { 2812349cc55cSDimitry Andric // Just copy live-ins to live-outs, for anything not transferred. 2813349cc55cSDimitry Andric if (*LiveOut != *LiveIn) { 2814349cc55cSDimitry Andric *LiveOut = *LiveIn; 2815349cc55cSDimitry Andric OLChanged = true; 2816349cc55cSDimitry Andric } 2817e8d8bef9SDimitry Andric } 2818e8d8bef9SDimitry Andric 2819349cc55cSDimitry Andric // If no live-out value changed, there's no need to explore further. 2820e8d8bef9SDimitry Andric if (!OLChanged) 2821e8d8bef9SDimitry Andric continue; 2822e8d8bef9SDimitry Andric 2823e8d8bef9SDimitry Andric // We should visit all successors. Ensure we'll visit any non-backedge 2824e8d8bef9SDimitry Andric // successors during this dataflow iteration; book backedge successors 2825e8d8bef9SDimitry Andric // to be visited next time around. 2826fcaf7f86SDimitry Andric for (auto *s : MBB->successors()) { 2827e8d8bef9SDimitry Andric // Ignore out of scope / not-to-be-explored successors. 2828e8d8bef9SDimitry Andric if (LiveInIdx.find(s) == LiveInIdx.end()) 2829e8d8bef9SDimitry Andric continue; 2830e8d8bef9SDimitry Andric 2831e8d8bef9SDimitry Andric if (BBToOrder[s] > BBToOrder[MBB]) { 2832e8d8bef9SDimitry Andric if (OnWorklist.insert(s).second) 2833e8d8bef9SDimitry Andric Worklist.push(BBToOrder[s]); 2834e8d8bef9SDimitry Andric } else if (OnPending.insert(s).second && (FirstTrip || OLChanged)) { 2835e8d8bef9SDimitry Andric Pending.push(BBToOrder[s]); 2836e8d8bef9SDimitry Andric } 2837e8d8bef9SDimitry Andric } 2838e8d8bef9SDimitry Andric } 2839e8d8bef9SDimitry Andric Worklist.swap(Pending); 2840e8d8bef9SDimitry Andric std::swap(OnWorklist, OnPending); 2841e8d8bef9SDimitry Andric OnPending.clear(); 2842e8d8bef9SDimitry Andric assert(Pending.empty()); 2843e8d8bef9SDimitry Andric FirstTrip = false; 2844e8d8bef9SDimitry Andric } 2845e8d8bef9SDimitry Andric 2846349cc55cSDimitry Andric // Save live-ins to output vector. Ignore any that are still marked as being 2847349cc55cSDimitry Andric // VPHIs with no location -- those are variables that we know the value of, 2848349cc55cSDimitry Andric // but are not actually available in the register file. 2849e8d8bef9SDimitry Andric for (auto *MBB : BlockOrders) { 2850349cc55cSDimitry Andric DbgValue *BlockLiveIn = LiveInIdx[MBB]; 2851349cc55cSDimitry Andric if (BlockLiveIn->Kind == DbgValue::NoVal) 2852e8d8bef9SDimitry Andric continue; 2853349cc55cSDimitry Andric if (BlockLiveIn->Kind == DbgValue::VPHI && 2854349cc55cSDimitry Andric BlockLiveIn->ID == ValueIDNum::EmptyValue) 2855349cc55cSDimitry Andric continue; 2856349cc55cSDimitry Andric if (BlockLiveIn->Kind == DbgValue::VPHI) 2857349cc55cSDimitry Andric BlockLiveIn->Kind = DbgValue::Def; 28584824e7fdSDimitry Andric assert(BlockLiveIn->Properties.DIExpr->getFragmentInfo() == 28594824e7fdSDimitry Andric Var.getFragment() && "Fragment info missing during value prop"); 2860349cc55cSDimitry Andric Output[MBB->getNumber()].push_back(std::make_pair(Var, *BlockLiveIn)); 2861e8d8bef9SDimitry Andric } 2862349cc55cSDimitry Andric } // Per-variable loop. 2863e8d8bef9SDimitry Andric 2864e8d8bef9SDimitry Andric BlockOrders.clear(); 2865e8d8bef9SDimitry Andric BlocksToExplore.clear(); 2866e8d8bef9SDimitry Andric } 2867e8d8bef9SDimitry Andric 28681fd87a68SDimitry Andric void InstrRefBasedLDV::placePHIsForSingleVarDefinition( 28691fd87a68SDimitry Andric const SmallPtrSetImpl<MachineBasicBlock *> &InScopeBlocks, 28701fd87a68SDimitry Andric MachineBasicBlock *AssignMBB, SmallVectorImpl<VLocTracker> &AllTheVLocs, 28711fd87a68SDimitry Andric const DebugVariable &Var, LiveInsT &Output) { 28721fd87a68SDimitry Andric // If there is a single definition of the variable, then working out it's 28731fd87a68SDimitry Andric // value everywhere is very simple: it's every block dominated by the 28741fd87a68SDimitry Andric // definition. At the dominance frontier, the usual algorithm would: 28751fd87a68SDimitry Andric // * Place PHIs, 28761fd87a68SDimitry Andric // * Propagate values into them, 28771fd87a68SDimitry Andric // * Find there's no incoming variable value from the other incoming branches 28781fd87a68SDimitry Andric // of the dominance frontier, 28791fd87a68SDimitry Andric // * Specify there's no variable value in blocks past the frontier. 28801fd87a68SDimitry Andric // This is a common case, hence it's worth special-casing it. 28811fd87a68SDimitry Andric 28821fd87a68SDimitry Andric // Pick out the variables value from the block transfer function. 28831fd87a68SDimitry Andric VLocTracker &VLocs = AllTheVLocs[AssignMBB->getNumber()]; 28841fd87a68SDimitry Andric auto ValueIt = VLocs.Vars.find(Var); 28851fd87a68SDimitry Andric const DbgValue &Value = ValueIt->second; 28861fd87a68SDimitry Andric 2887d56accc7SDimitry Andric // If it's an explicit assignment of "undef", that means there is no location 2888d56accc7SDimitry Andric // anyway, anywhere. 2889d56accc7SDimitry Andric if (Value.Kind == DbgValue::Undef) 2890d56accc7SDimitry Andric return; 2891d56accc7SDimitry Andric 28921fd87a68SDimitry Andric // Assign the variable value to entry to each dominated block that's in scope. 28931fd87a68SDimitry Andric // Skip the definition block -- it's assigned the variable value in the middle 28941fd87a68SDimitry Andric // of the block somewhere. 28951fd87a68SDimitry Andric for (auto *ScopeBlock : InScopeBlocks) { 28961fd87a68SDimitry Andric if (!DomTree->properlyDominates(AssignMBB, ScopeBlock)) 28971fd87a68SDimitry Andric continue; 28981fd87a68SDimitry Andric 28991fd87a68SDimitry Andric Output[ScopeBlock->getNumber()].push_back({Var, Value}); 29001fd87a68SDimitry Andric } 29011fd87a68SDimitry Andric 29021fd87a68SDimitry Andric // All blocks that aren't dominated have no live-in value, thus no variable 29031fd87a68SDimitry Andric // value will be given to them. 29041fd87a68SDimitry Andric } 29051fd87a68SDimitry Andric 2906e8d8bef9SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2907e8d8bef9SDimitry Andric void InstrRefBasedLDV::dump_mloc_transfer( 2908e8d8bef9SDimitry Andric const MLocTransferMap &mloc_transfer) const { 2909fcaf7f86SDimitry Andric for (const auto &P : mloc_transfer) { 2910e8d8bef9SDimitry Andric std::string foo = MTracker->LocIdxToName(P.first); 2911e8d8bef9SDimitry Andric std::string bar = MTracker->IDAsString(P.second); 2912e8d8bef9SDimitry Andric dbgs() << "Loc " << foo << " --> " << bar << "\n"; 2913e8d8bef9SDimitry Andric } 2914e8d8bef9SDimitry Andric } 2915e8d8bef9SDimitry Andric #endif 2916e8d8bef9SDimitry Andric 2917e8d8bef9SDimitry Andric void InstrRefBasedLDV::initialSetup(MachineFunction &MF) { 2918e8d8bef9SDimitry Andric // Build some useful data structures. 2919349cc55cSDimitry Andric 2920349cc55cSDimitry Andric LLVMContext &Context = MF.getFunction().getContext(); 2921349cc55cSDimitry Andric EmptyExpr = DIExpression::get(Context, {}); 2922349cc55cSDimitry Andric 2923e8d8bef9SDimitry Andric auto hasNonArtificialLocation = [](const MachineInstr &MI) -> bool { 2924e8d8bef9SDimitry Andric if (const DebugLoc &DL = MI.getDebugLoc()) 2925e8d8bef9SDimitry Andric return DL.getLine() != 0; 2926e8d8bef9SDimitry Andric return false; 2927e8d8bef9SDimitry Andric }; 2928e8d8bef9SDimitry Andric // Collect a set of all the artificial blocks. 2929e8d8bef9SDimitry Andric for (auto &MBB : MF) 2930e8d8bef9SDimitry Andric if (none_of(MBB.instrs(), hasNonArtificialLocation)) 2931e8d8bef9SDimitry Andric ArtificialBlocks.insert(&MBB); 2932e8d8bef9SDimitry Andric 2933e8d8bef9SDimitry Andric // Compute mappings of block <=> RPO order. 2934e8d8bef9SDimitry Andric ReversePostOrderTraversal<MachineFunction *> RPOT(&MF); 2935e8d8bef9SDimitry Andric unsigned int RPONumber = 0; 2936fe6060f1SDimitry Andric for (MachineBasicBlock *MBB : RPOT) { 2937fe6060f1SDimitry Andric OrderToBB[RPONumber] = MBB; 2938fe6060f1SDimitry Andric BBToOrder[MBB] = RPONumber; 2939fe6060f1SDimitry Andric BBNumToRPO[MBB->getNumber()] = RPONumber; 2940e8d8bef9SDimitry Andric ++RPONumber; 2941e8d8bef9SDimitry Andric } 2942fe6060f1SDimitry Andric 2943fe6060f1SDimitry Andric // Order value substitutions by their "source" operand pair, for quick lookup. 2944fe6060f1SDimitry Andric llvm::sort(MF.DebugValueSubstitutions); 2945fe6060f1SDimitry Andric 2946fe6060f1SDimitry Andric #ifdef EXPENSIVE_CHECKS 2947fe6060f1SDimitry Andric // As an expensive check, test whether there are any duplicate substitution 2948fe6060f1SDimitry Andric // sources in the collection. 2949fe6060f1SDimitry Andric if (MF.DebugValueSubstitutions.size() > 2) { 2950fe6060f1SDimitry Andric for (auto It = MF.DebugValueSubstitutions.begin(); 2951fe6060f1SDimitry Andric It != std::prev(MF.DebugValueSubstitutions.end()); ++It) { 2952fe6060f1SDimitry Andric assert(It->Src != std::next(It)->Src && "Duplicate variable location " 2953fe6060f1SDimitry Andric "substitution seen"); 2954fe6060f1SDimitry Andric } 2955fe6060f1SDimitry Andric } 2956fe6060f1SDimitry Andric #endif 2957e8d8bef9SDimitry Andric } 2958e8d8bef9SDimitry Andric 2959d56accc7SDimitry Andric // Produce an "ejection map" for blocks, i.e., what's the highest-numbered 2960d56accc7SDimitry Andric // lexical scope it's used in. When exploring in DFS order and we pass that 2961d56accc7SDimitry Andric // scope, the block can be processed and any tracking information freed. 2962d56accc7SDimitry Andric void InstrRefBasedLDV::makeDepthFirstEjectionMap( 2963d56accc7SDimitry Andric SmallVectorImpl<unsigned> &EjectionMap, 2964d56accc7SDimitry Andric const ScopeToDILocT &ScopeToDILocation, 2965d56accc7SDimitry Andric ScopeToAssignBlocksT &ScopeToAssignBlocks) { 2966d56accc7SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; 2967d56accc7SDimitry Andric SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack; 2968d56accc7SDimitry Andric auto *TopScope = LS.getCurrentFunctionScope(); 2969d56accc7SDimitry Andric 2970d56accc7SDimitry Andric // Unlike lexical scope explorers, we explore in reverse order, to find the 2971d56accc7SDimitry Andric // "last" lexical scope used for each block early. 2972d56accc7SDimitry Andric WorkStack.push_back({TopScope, TopScope->getChildren().size() - 1}); 2973d56accc7SDimitry Andric 2974d56accc7SDimitry Andric while (!WorkStack.empty()) { 2975d56accc7SDimitry Andric auto &ScopePosition = WorkStack.back(); 2976d56accc7SDimitry Andric LexicalScope *WS = ScopePosition.first; 2977d56accc7SDimitry Andric ssize_t ChildNum = ScopePosition.second--; 2978d56accc7SDimitry Andric 2979d56accc7SDimitry Andric const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren(); 2980d56accc7SDimitry Andric if (ChildNum >= 0) { 2981d56accc7SDimitry Andric // If ChildNum is positive, there are remaining children to explore. 2982d56accc7SDimitry Andric // Push the child and its children-count onto the stack. 2983d56accc7SDimitry Andric auto &ChildScope = Children[ChildNum]; 2984d56accc7SDimitry Andric WorkStack.push_back( 2985d56accc7SDimitry Andric std::make_pair(ChildScope, ChildScope->getChildren().size() - 1)); 2986d56accc7SDimitry Andric } else { 2987d56accc7SDimitry Andric WorkStack.pop_back(); 2988d56accc7SDimitry Andric 2989d56accc7SDimitry Andric // We've explored all children and any later blocks: examine all blocks 2990d56accc7SDimitry Andric // in our scope. If they haven't yet had an ejection number set, then 2991d56accc7SDimitry Andric // this scope will be the last to use that block. 2992d56accc7SDimitry Andric auto DILocationIt = ScopeToDILocation.find(WS); 2993d56accc7SDimitry Andric if (DILocationIt != ScopeToDILocation.end()) { 2994d56accc7SDimitry Andric getBlocksForScope(DILocationIt->second, BlocksToExplore, 2995d56accc7SDimitry Andric ScopeToAssignBlocks.find(WS)->second); 2996fcaf7f86SDimitry Andric for (const auto *MBB : BlocksToExplore) { 2997d56accc7SDimitry Andric unsigned BBNum = MBB->getNumber(); 2998d56accc7SDimitry Andric if (EjectionMap[BBNum] == 0) 2999d56accc7SDimitry Andric EjectionMap[BBNum] = WS->getDFSOut(); 3000d56accc7SDimitry Andric } 3001d56accc7SDimitry Andric 3002d56accc7SDimitry Andric BlocksToExplore.clear(); 3003d56accc7SDimitry Andric } 3004d56accc7SDimitry Andric } 3005d56accc7SDimitry Andric } 3006d56accc7SDimitry Andric } 3007d56accc7SDimitry Andric 3008d56accc7SDimitry Andric bool InstrRefBasedLDV::depthFirstVLocAndEmit( 3009d56accc7SDimitry Andric unsigned MaxNumBlocks, const ScopeToDILocT &ScopeToDILocation, 3010d56accc7SDimitry Andric const ScopeToVarsT &ScopeToVars, ScopeToAssignBlocksT &ScopeToAssignBlocks, 301181ad6265SDimitry Andric LiveInsT &Output, FuncValueTable &MOutLocs, FuncValueTable &MInLocs, 3012d56accc7SDimitry Andric SmallVectorImpl<VLocTracker> &AllTheVLocs, MachineFunction &MF, 3013d56accc7SDimitry Andric DenseMap<DebugVariable, unsigned> &AllVarsNumbering, 3014d56accc7SDimitry Andric const TargetPassConfig &TPC) { 3015d56accc7SDimitry Andric TTracker = new TransferTracker(TII, MTracker, MF, *TRI, CalleeSavedRegs, TPC); 3016d56accc7SDimitry Andric unsigned NumLocs = MTracker->getNumLocs(); 3017d56accc7SDimitry Andric VTracker = nullptr; 3018d56accc7SDimitry Andric 3019d56accc7SDimitry Andric // No scopes? No variable locations. 302081ad6265SDimitry Andric if (!LS.getCurrentFunctionScope()) 3021d56accc7SDimitry Andric return false; 3022d56accc7SDimitry Andric 3023d56accc7SDimitry Andric // Build map from block number to the last scope that uses the block. 3024d56accc7SDimitry Andric SmallVector<unsigned, 16> EjectionMap; 3025d56accc7SDimitry Andric EjectionMap.resize(MaxNumBlocks, 0); 3026d56accc7SDimitry Andric makeDepthFirstEjectionMap(EjectionMap, ScopeToDILocation, 3027d56accc7SDimitry Andric ScopeToAssignBlocks); 3028d56accc7SDimitry Andric 3029d56accc7SDimitry Andric // Helper lambda for ejecting a block -- if nothing is going to use the block, 3030d56accc7SDimitry Andric // we can translate the variable location information into DBG_VALUEs and then 3031d56accc7SDimitry Andric // free all of InstrRefBasedLDV's data structures. 3032d56accc7SDimitry Andric auto EjectBlock = [&](MachineBasicBlock &MBB) -> void { 3033d56accc7SDimitry Andric unsigned BBNum = MBB.getNumber(); 3034d56accc7SDimitry Andric AllTheVLocs[BBNum].clear(); 3035d56accc7SDimitry Andric 3036d56accc7SDimitry Andric // Prime the transfer-tracker, and then step through all the block 3037d56accc7SDimitry Andric // instructions, installing transfers. 3038d56accc7SDimitry Andric MTracker->reset(); 3039d56accc7SDimitry Andric MTracker->loadFromArray(MInLocs[BBNum], BBNum); 3040d56accc7SDimitry Andric TTracker->loadInlocs(MBB, MInLocs[BBNum], Output[BBNum], NumLocs); 3041d56accc7SDimitry Andric 3042d56accc7SDimitry Andric CurBB = BBNum; 3043d56accc7SDimitry Andric CurInst = 1; 3044d56accc7SDimitry Andric for (auto &MI : MBB) { 304581ad6265SDimitry Andric process(MI, MOutLocs.get(), MInLocs.get()); 3046d56accc7SDimitry Andric TTracker->checkInstForNewValues(CurInst, MI.getIterator()); 3047d56accc7SDimitry Andric ++CurInst; 3048d56accc7SDimitry Andric } 3049d56accc7SDimitry Andric 3050d56accc7SDimitry Andric // Free machine-location tables for this block. 305181ad6265SDimitry Andric MInLocs[BBNum].reset(); 305281ad6265SDimitry Andric MOutLocs[BBNum].reset(); 3053d56accc7SDimitry Andric // We don't need live-in variable values for this block either. 3054d56accc7SDimitry Andric Output[BBNum].clear(); 3055d56accc7SDimitry Andric AllTheVLocs[BBNum].clear(); 3056d56accc7SDimitry Andric }; 3057d56accc7SDimitry Andric 3058d56accc7SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> BlocksToExplore; 3059d56accc7SDimitry Andric SmallVector<std::pair<LexicalScope *, ssize_t>, 4> WorkStack; 3060d56accc7SDimitry Andric WorkStack.push_back({LS.getCurrentFunctionScope(), 0}); 3061d56accc7SDimitry Andric unsigned HighestDFSIn = 0; 3062d56accc7SDimitry Andric 3063d56accc7SDimitry Andric // Proceed to explore in depth first order. 3064d56accc7SDimitry Andric while (!WorkStack.empty()) { 3065d56accc7SDimitry Andric auto &ScopePosition = WorkStack.back(); 3066d56accc7SDimitry Andric LexicalScope *WS = ScopePosition.first; 3067d56accc7SDimitry Andric ssize_t ChildNum = ScopePosition.second++; 3068d56accc7SDimitry Andric 3069d56accc7SDimitry Andric // We obesrve scopes with children twice here, once descending in, once 3070d56accc7SDimitry Andric // ascending out of the scope nest. Use HighestDFSIn as a ratchet to ensure 3071d56accc7SDimitry Andric // we don't process a scope twice. Additionally, ignore scopes that don't 3072d56accc7SDimitry Andric // have a DILocation -- by proxy, this means we never tracked any variable 3073d56accc7SDimitry Andric // assignments in that scope. 3074d56accc7SDimitry Andric auto DILocIt = ScopeToDILocation.find(WS); 3075d56accc7SDimitry Andric if (HighestDFSIn <= WS->getDFSIn() && DILocIt != ScopeToDILocation.end()) { 3076d56accc7SDimitry Andric const DILocation *DILoc = DILocIt->second; 3077d56accc7SDimitry Andric auto &VarsWeCareAbout = ScopeToVars.find(WS)->second; 3078d56accc7SDimitry Andric auto &BlocksInScope = ScopeToAssignBlocks.find(WS)->second; 3079d56accc7SDimitry Andric 3080d56accc7SDimitry Andric buildVLocValueMap(DILoc, VarsWeCareAbout, BlocksInScope, Output, MOutLocs, 3081d56accc7SDimitry Andric MInLocs, AllTheVLocs); 3082d56accc7SDimitry Andric } 3083d56accc7SDimitry Andric 3084d56accc7SDimitry Andric HighestDFSIn = std::max(HighestDFSIn, WS->getDFSIn()); 3085d56accc7SDimitry Andric 3086d56accc7SDimitry Andric // Descend into any scope nests. 3087d56accc7SDimitry Andric const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren(); 3088d56accc7SDimitry Andric if (ChildNum < (ssize_t)Children.size()) { 3089d56accc7SDimitry Andric // There are children to explore -- push onto stack and continue. 3090d56accc7SDimitry Andric auto &ChildScope = Children[ChildNum]; 3091d56accc7SDimitry Andric WorkStack.push_back(std::make_pair(ChildScope, 0)); 3092d56accc7SDimitry Andric } else { 3093d56accc7SDimitry Andric WorkStack.pop_back(); 3094d56accc7SDimitry Andric 3095d56accc7SDimitry Andric // We've explored a leaf, or have explored all the children of a scope. 3096d56accc7SDimitry Andric // Try to eject any blocks where this is the last scope it's relevant to. 3097d56accc7SDimitry Andric auto DILocationIt = ScopeToDILocation.find(WS); 3098d56accc7SDimitry Andric if (DILocationIt == ScopeToDILocation.end()) 3099d56accc7SDimitry Andric continue; 3100d56accc7SDimitry Andric 3101d56accc7SDimitry Andric getBlocksForScope(DILocationIt->second, BlocksToExplore, 3102d56accc7SDimitry Andric ScopeToAssignBlocks.find(WS)->second); 3103fcaf7f86SDimitry Andric for (const auto *MBB : BlocksToExplore) 3104d56accc7SDimitry Andric if (WS->getDFSOut() == EjectionMap[MBB->getNumber()]) 3105d56accc7SDimitry Andric EjectBlock(const_cast<MachineBasicBlock &>(*MBB)); 3106d56accc7SDimitry Andric 3107d56accc7SDimitry Andric BlocksToExplore.clear(); 3108d56accc7SDimitry Andric } 3109d56accc7SDimitry Andric } 3110d56accc7SDimitry Andric 3111d56accc7SDimitry Andric // Some artificial blocks may not have been ejected, meaning they're not 3112d56accc7SDimitry Andric // connected to an actual legitimate scope. This can technically happen 3113d56accc7SDimitry Andric // with things like the entry block. In theory, we shouldn't need to do 3114d56accc7SDimitry Andric // anything for such out-of-scope blocks, but for the sake of being similar 3115d56accc7SDimitry Andric // to VarLocBasedLDV, eject these too. 3116d56accc7SDimitry Andric for (auto *MBB : ArtificialBlocks) 3117d56accc7SDimitry Andric if (MOutLocs[MBB->getNumber()]) 3118d56accc7SDimitry Andric EjectBlock(*MBB); 3119d56accc7SDimitry Andric 3120d56accc7SDimitry Andric return emitTransfers(AllVarsNumbering); 3121d56accc7SDimitry Andric } 3122d56accc7SDimitry Andric 31231fd87a68SDimitry Andric bool InstrRefBasedLDV::emitTransfers( 31241fd87a68SDimitry Andric DenseMap<DebugVariable, unsigned> &AllVarsNumbering) { 31251fd87a68SDimitry Andric // Go through all the transfers recorded in the TransferTracker -- this is 31261fd87a68SDimitry Andric // both the live-ins to a block, and any movements of values that happen 31271fd87a68SDimitry Andric // in the middle. 31281fd87a68SDimitry Andric for (const auto &P : TTracker->Transfers) { 31291fd87a68SDimitry Andric // We have to insert DBG_VALUEs in a consistent order, otherwise they 31301fd87a68SDimitry Andric // appear in DWARF in different orders. Use the order that they appear 31311fd87a68SDimitry Andric // when walking through each block / each instruction, stored in 31321fd87a68SDimitry Andric // AllVarsNumbering. 31331fd87a68SDimitry Andric SmallVector<std::pair<unsigned, MachineInstr *>> Insts; 31341fd87a68SDimitry Andric for (MachineInstr *MI : P.Insts) { 31351fd87a68SDimitry Andric DebugVariable Var(MI->getDebugVariable(), MI->getDebugExpression(), 31361fd87a68SDimitry Andric MI->getDebugLoc()->getInlinedAt()); 31371fd87a68SDimitry Andric Insts.emplace_back(AllVarsNumbering.find(Var)->second, MI); 31381fd87a68SDimitry Andric } 3139*972a253aSDimitry Andric llvm::sort(Insts, llvm::less_first()); 31401fd87a68SDimitry Andric 31411fd87a68SDimitry Andric // Insert either before or after the designated point... 31421fd87a68SDimitry Andric if (P.MBB) { 31431fd87a68SDimitry Andric MachineBasicBlock &MBB = *P.MBB; 31441fd87a68SDimitry Andric for (const auto &Pair : Insts) 31451fd87a68SDimitry Andric MBB.insert(P.Pos, Pair.second); 31461fd87a68SDimitry Andric } else { 31471fd87a68SDimitry Andric // Terminators, like tail calls, can clobber things. Don't try and place 31481fd87a68SDimitry Andric // transfers after them. 31491fd87a68SDimitry Andric if (P.Pos->isTerminator()) 31501fd87a68SDimitry Andric continue; 31511fd87a68SDimitry Andric 31521fd87a68SDimitry Andric MachineBasicBlock &MBB = *P.Pos->getParent(); 31531fd87a68SDimitry Andric for (const auto &Pair : Insts) 31541fd87a68SDimitry Andric MBB.insertAfterBundle(P.Pos, Pair.second); 31551fd87a68SDimitry Andric } 31561fd87a68SDimitry Andric } 31571fd87a68SDimitry Andric 31581fd87a68SDimitry Andric return TTracker->Transfers.size() != 0; 31591fd87a68SDimitry Andric } 31601fd87a68SDimitry Andric 3161e8d8bef9SDimitry Andric /// Calculate the liveness information for the given machine function and 3162e8d8bef9SDimitry Andric /// extend ranges across basic blocks. 3163e8d8bef9SDimitry Andric bool InstrRefBasedLDV::ExtendRanges(MachineFunction &MF, 3164349cc55cSDimitry Andric MachineDominatorTree *DomTree, 3165349cc55cSDimitry Andric TargetPassConfig *TPC, 3166349cc55cSDimitry Andric unsigned InputBBLimit, 3167349cc55cSDimitry Andric unsigned InputDbgValLimit) { 3168e8d8bef9SDimitry Andric // No subprogram means this function contains no debuginfo. 3169e8d8bef9SDimitry Andric if (!MF.getFunction().getSubprogram()) 3170e8d8bef9SDimitry Andric return false; 3171e8d8bef9SDimitry Andric 3172e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "\nDebug Range Extension\n"); 3173e8d8bef9SDimitry Andric this->TPC = TPC; 3174e8d8bef9SDimitry Andric 3175349cc55cSDimitry Andric this->DomTree = DomTree; 3176e8d8bef9SDimitry Andric TRI = MF.getSubtarget().getRegisterInfo(); 3177349cc55cSDimitry Andric MRI = &MF.getRegInfo(); 3178e8d8bef9SDimitry Andric TII = MF.getSubtarget().getInstrInfo(); 3179e8d8bef9SDimitry Andric TFI = MF.getSubtarget().getFrameLowering(); 3180e8d8bef9SDimitry Andric TFI->getCalleeSaves(MF, CalleeSavedRegs); 3181fe6060f1SDimitry Andric MFI = &MF.getFrameInfo(); 3182e8d8bef9SDimitry Andric LS.initialize(MF); 3183e8d8bef9SDimitry Andric 31844824e7fdSDimitry Andric const auto &STI = MF.getSubtarget(); 31854824e7fdSDimitry Andric AdjustsStackInCalls = MFI->adjustsStack() && 31864824e7fdSDimitry Andric STI.getFrameLowering()->stackProbeFunctionModifiesSP(); 31874824e7fdSDimitry Andric if (AdjustsStackInCalls) 31884824e7fdSDimitry Andric StackProbeSymbolName = STI.getTargetLowering()->getStackProbeSymbolName(MF); 31894824e7fdSDimitry Andric 3190e8d8bef9SDimitry Andric MTracker = 3191e8d8bef9SDimitry Andric new MLocTracker(MF, *TII, *TRI, *MF.getSubtarget().getTargetLowering()); 3192e8d8bef9SDimitry Andric VTracker = nullptr; 3193e8d8bef9SDimitry Andric TTracker = nullptr; 3194e8d8bef9SDimitry Andric 3195e8d8bef9SDimitry Andric SmallVector<MLocTransferMap, 32> MLocTransfer; 3196e8d8bef9SDimitry Andric SmallVector<VLocTracker, 8> vlocs; 3197e8d8bef9SDimitry Andric LiveInsT SavedLiveIns; 3198e8d8bef9SDimitry Andric 3199e8d8bef9SDimitry Andric int MaxNumBlocks = -1; 3200e8d8bef9SDimitry Andric for (auto &MBB : MF) 3201e8d8bef9SDimitry Andric MaxNumBlocks = std::max(MBB.getNumber(), MaxNumBlocks); 3202e8d8bef9SDimitry Andric assert(MaxNumBlocks >= 0); 3203e8d8bef9SDimitry Andric ++MaxNumBlocks; 3204e8d8bef9SDimitry Andric 320581ad6265SDimitry Andric initialSetup(MF); 320681ad6265SDimitry Andric 3207e8d8bef9SDimitry Andric MLocTransfer.resize(MaxNumBlocks); 32084824e7fdSDimitry Andric vlocs.resize(MaxNumBlocks, VLocTracker(OverlapFragments, EmptyExpr)); 3209e8d8bef9SDimitry Andric SavedLiveIns.resize(MaxNumBlocks); 3210e8d8bef9SDimitry Andric 3211e8d8bef9SDimitry Andric produceMLocTransferFunction(MF, MLocTransfer, MaxNumBlocks); 3212e8d8bef9SDimitry Andric 3213e8d8bef9SDimitry Andric // Allocate and initialize two array-of-arrays for the live-in and live-out 3214e8d8bef9SDimitry Andric // machine values. The outer dimension is the block number; while the inner 3215e8d8bef9SDimitry Andric // dimension is a LocIdx from MLocTracker. 321681ad6265SDimitry Andric FuncValueTable MOutLocs = std::make_unique<ValueTable[]>(MaxNumBlocks); 321781ad6265SDimitry Andric FuncValueTable MInLocs = std::make_unique<ValueTable[]>(MaxNumBlocks); 3218e8d8bef9SDimitry Andric unsigned NumLocs = MTracker->getNumLocs(); 3219e8d8bef9SDimitry Andric for (int i = 0; i < MaxNumBlocks; ++i) { 3220349cc55cSDimitry Andric // These all auto-initialize to ValueIDNum::EmptyValue 322181ad6265SDimitry Andric MOutLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs); 322281ad6265SDimitry Andric MInLocs[i] = std::make_unique<ValueIDNum[]>(NumLocs); 3223e8d8bef9SDimitry Andric } 3224e8d8bef9SDimitry Andric 3225e8d8bef9SDimitry Andric // Solve the machine value dataflow problem using the MLocTransfer function, 3226e8d8bef9SDimitry Andric // storing the computed live-ins / live-outs into the array-of-arrays. We use 3227e8d8bef9SDimitry Andric // both live-ins and live-outs for decision making in the variable value 3228e8d8bef9SDimitry Andric // dataflow problem. 3229349cc55cSDimitry Andric buildMLocValueMap(MF, MInLocs, MOutLocs, MLocTransfer); 3230e8d8bef9SDimitry Andric 3231fe6060f1SDimitry Andric // Patch up debug phi numbers, turning unknown block-live-in values into 3232fe6060f1SDimitry Andric // either live-through machine values, or PHIs. 3233fe6060f1SDimitry Andric for (auto &DBG_PHI : DebugPHINumToValue) { 3234fe6060f1SDimitry Andric // Identify unresolved block-live-ins. 323581ad6265SDimitry Andric if (!DBG_PHI.ValueRead) 323681ad6265SDimitry Andric continue; 323781ad6265SDimitry Andric 323881ad6265SDimitry Andric ValueIDNum &Num = *DBG_PHI.ValueRead; 3239fe6060f1SDimitry Andric if (!Num.isPHI()) 3240fe6060f1SDimitry Andric continue; 3241fe6060f1SDimitry Andric 3242fe6060f1SDimitry Andric unsigned BlockNo = Num.getBlock(); 3243fe6060f1SDimitry Andric LocIdx LocNo = Num.getLoc(); 3244fe6060f1SDimitry Andric Num = MInLocs[BlockNo][LocNo.asU64()]; 3245fe6060f1SDimitry Andric } 3246fe6060f1SDimitry Andric // Later, we'll be looking up ranges of instruction numbers. 3247fe6060f1SDimitry Andric llvm::sort(DebugPHINumToValue); 3248fe6060f1SDimitry Andric 3249e8d8bef9SDimitry Andric // Walk back through each block / instruction, collecting DBG_VALUE 3250e8d8bef9SDimitry Andric // instructions and recording what machine value their operands refer to. 3251e8d8bef9SDimitry Andric for (auto &OrderPair : OrderToBB) { 3252e8d8bef9SDimitry Andric MachineBasicBlock &MBB = *OrderPair.second; 3253e8d8bef9SDimitry Andric CurBB = MBB.getNumber(); 3254e8d8bef9SDimitry Andric VTracker = &vlocs[CurBB]; 3255e8d8bef9SDimitry Andric VTracker->MBB = &MBB; 3256e8d8bef9SDimitry Andric MTracker->loadFromArray(MInLocs[CurBB], CurBB); 3257e8d8bef9SDimitry Andric CurInst = 1; 3258e8d8bef9SDimitry Andric for (auto &MI : MBB) { 325981ad6265SDimitry Andric process(MI, MOutLocs.get(), MInLocs.get()); 3260e8d8bef9SDimitry Andric ++CurInst; 3261e8d8bef9SDimitry Andric } 3262e8d8bef9SDimitry Andric MTracker->reset(); 3263e8d8bef9SDimitry Andric } 3264e8d8bef9SDimitry Andric 3265e8d8bef9SDimitry Andric // Number all variables in the order that they appear, to be used as a stable 3266e8d8bef9SDimitry Andric // insertion order later. 3267e8d8bef9SDimitry Andric DenseMap<DebugVariable, unsigned> AllVarsNumbering; 3268e8d8bef9SDimitry Andric 3269e8d8bef9SDimitry Andric // Map from one LexicalScope to all the variables in that scope. 32701fd87a68SDimitry Andric ScopeToVarsT ScopeToVars; 3271e8d8bef9SDimitry Andric 32721fd87a68SDimitry Andric // Map from One lexical scope to all blocks where assignments happen for 32731fd87a68SDimitry Andric // that scope. 32741fd87a68SDimitry Andric ScopeToAssignBlocksT ScopeToAssignBlocks; 3275e8d8bef9SDimitry Andric 32761fd87a68SDimitry Andric // Store map of DILocations that describes scopes. 32771fd87a68SDimitry Andric ScopeToDILocT ScopeToDILocation; 3278e8d8bef9SDimitry Andric 3279e8d8bef9SDimitry Andric // To mirror old LiveDebugValues, enumerate variables in RPOT order. Otherwise 3280e8d8bef9SDimitry Andric // the order is unimportant, it just has to be stable. 3281349cc55cSDimitry Andric unsigned VarAssignCount = 0; 3282e8d8bef9SDimitry Andric for (unsigned int I = 0; I < OrderToBB.size(); ++I) { 3283e8d8bef9SDimitry Andric auto *MBB = OrderToBB[I]; 3284e8d8bef9SDimitry Andric auto *VTracker = &vlocs[MBB->getNumber()]; 3285e8d8bef9SDimitry Andric // Collect each variable with a DBG_VALUE in this block. 3286e8d8bef9SDimitry Andric for (auto &idx : VTracker->Vars) { 3287e8d8bef9SDimitry Andric const auto &Var = idx.first; 3288e8d8bef9SDimitry Andric const DILocation *ScopeLoc = VTracker->Scopes[Var]; 3289e8d8bef9SDimitry Andric assert(ScopeLoc != nullptr); 3290e8d8bef9SDimitry Andric auto *Scope = LS.findLexicalScope(ScopeLoc); 3291e8d8bef9SDimitry Andric 3292e8d8bef9SDimitry Andric // No insts in scope -> shouldn't have been recorded. 3293e8d8bef9SDimitry Andric assert(Scope != nullptr); 3294e8d8bef9SDimitry Andric 3295e8d8bef9SDimitry Andric AllVarsNumbering.insert(std::make_pair(Var, AllVarsNumbering.size())); 3296e8d8bef9SDimitry Andric ScopeToVars[Scope].insert(Var); 32971fd87a68SDimitry Andric ScopeToAssignBlocks[Scope].insert(VTracker->MBB); 3298e8d8bef9SDimitry Andric ScopeToDILocation[Scope] = ScopeLoc; 3299349cc55cSDimitry Andric ++VarAssignCount; 3300e8d8bef9SDimitry Andric } 3301e8d8bef9SDimitry Andric } 3302e8d8bef9SDimitry Andric 3303349cc55cSDimitry Andric bool Changed = false; 3304349cc55cSDimitry Andric 3305349cc55cSDimitry Andric // If we have an extremely large number of variable assignments and blocks, 3306349cc55cSDimitry Andric // bail out at this point. We've burnt some time doing analysis already, 3307349cc55cSDimitry Andric // however we should cut our losses. 3308349cc55cSDimitry Andric if ((unsigned)MaxNumBlocks > InputBBLimit && 3309349cc55cSDimitry Andric VarAssignCount > InputDbgValLimit) { 3310349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Disabling InstrRefBasedLDV: " << MF.getName() 3311349cc55cSDimitry Andric << " has " << MaxNumBlocks << " basic blocks and " 3312349cc55cSDimitry Andric << VarAssignCount 3313349cc55cSDimitry Andric << " variable assignments, exceeding limits.\n"); 3314d56accc7SDimitry Andric } else { 3315d56accc7SDimitry Andric // Optionally, solve the variable value problem and emit to blocks by using 3316d56accc7SDimitry Andric // a lexical-scope-depth search. It should be functionally identical to 3317d56accc7SDimitry Andric // the "else" block of this condition. 3318d56accc7SDimitry Andric Changed = depthFirstVLocAndEmit( 3319d56accc7SDimitry Andric MaxNumBlocks, ScopeToDILocation, ScopeToVars, ScopeToAssignBlocks, 3320d56accc7SDimitry Andric SavedLiveIns, MOutLocs, MInLocs, vlocs, MF, AllVarsNumbering, *TPC); 3321d56accc7SDimitry Andric } 3322d56accc7SDimitry Andric 3323e8d8bef9SDimitry Andric delete MTracker; 3324e8d8bef9SDimitry Andric delete TTracker; 3325e8d8bef9SDimitry Andric MTracker = nullptr; 3326e8d8bef9SDimitry Andric VTracker = nullptr; 3327e8d8bef9SDimitry Andric TTracker = nullptr; 3328e8d8bef9SDimitry Andric 3329e8d8bef9SDimitry Andric ArtificialBlocks.clear(); 3330e8d8bef9SDimitry Andric OrderToBB.clear(); 3331e8d8bef9SDimitry Andric BBToOrder.clear(); 3332e8d8bef9SDimitry Andric BBNumToRPO.clear(); 3333e8d8bef9SDimitry Andric DebugInstrNumToInstr.clear(); 3334fe6060f1SDimitry Andric DebugPHINumToValue.clear(); 33354824e7fdSDimitry Andric OverlapFragments.clear(); 33364824e7fdSDimitry Andric SeenFragments.clear(); 3337d56accc7SDimitry Andric SeenDbgPHIs.clear(); 3338e8d8bef9SDimitry Andric 3339e8d8bef9SDimitry Andric return Changed; 3340e8d8bef9SDimitry Andric } 3341e8d8bef9SDimitry Andric 3342e8d8bef9SDimitry Andric LDVImpl *llvm::makeInstrRefBasedLiveDebugValues() { 3343e8d8bef9SDimitry Andric return new InstrRefBasedLDV(); 3344e8d8bef9SDimitry Andric } 3345fe6060f1SDimitry Andric 3346fe6060f1SDimitry Andric namespace { 3347fe6060f1SDimitry Andric class LDVSSABlock; 3348fe6060f1SDimitry Andric class LDVSSAUpdater; 3349fe6060f1SDimitry Andric 3350fe6060f1SDimitry Andric // Pick a type to identify incoming block values as we construct SSA. We 3351fe6060f1SDimitry Andric // can't use anything more robust than an integer unfortunately, as SSAUpdater 3352fe6060f1SDimitry Andric // expects to zero-initialize the type. 3353fe6060f1SDimitry Andric typedef uint64_t BlockValueNum; 3354fe6060f1SDimitry Andric 3355fe6060f1SDimitry Andric /// Represents an SSA PHI node for the SSA updater class. Contains the block 3356fe6060f1SDimitry Andric /// this PHI is in, the value number it would have, and the expected incoming 3357fe6060f1SDimitry Andric /// values from parent blocks. 3358fe6060f1SDimitry Andric class LDVSSAPhi { 3359fe6060f1SDimitry Andric public: 3360fe6060f1SDimitry Andric SmallVector<std::pair<LDVSSABlock *, BlockValueNum>, 4> IncomingValues; 3361fe6060f1SDimitry Andric LDVSSABlock *ParentBlock; 3362fe6060f1SDimitry Andric BlockValueNum PHIValNum; 3363fe6060f1SDimitry Andric LDVSSAPhi(BlockValueNum PHIValNum, LDVSSABlock *ParentBlock) 3364fe6060f1SDimitry Andric : ParentBlock(ParentBlock), PHIValNum(PHIValNum) {} 3365fe6060f1SDimitry Andric 3366fe6060f1SDimitry Andric LDVSSABlock *getParent() { return ParentBlock; } 3367fe6060f1SDimitry Andric }; 3368fe6060f1SDimitry Andric 3369fe6060f1SDimitry Andric /// Thin wrapper around a block predecessor iterator. Only difference from a 3370fe6060f1SDimitry Andric /// normal block iterator is that it dereferences to an LDVSSABlock. 3371fe6060f1SDimitry Andric class LDVSSABlockIterator { 3372fe6060f1SDimitry Andric public: 3373fe6060f1SDimitry Andric MachineBasicBlock::pred_iterator PredIt; 3374fe6060f1SDimitry Andric LDVSSAUpdater &Updater; 3375fe6060f1SDimitry Andric 3376fe6060f1SDimitry Andric LDVSSABlockIterator(MachineBasicBlock::pred_iterator PredIt, 3377fe6060f1SDimitry Andric LDVSSAUpdater &Updater) 3378fe6060f1SDimitry Andric : PredIt(PredIt), Updater(Updater) {} 3379fe6060f1SDimitry Andric 3380fe6060f1SDimitry Andric bool operator!=(const LDVSSABlockIterator &OtherIt) const { 3381fe6060f1SDimitry Andric return OtherIt.PredIt != PredIt; 3382fe6060f1SDimitry Andric } 3383fe6060f1SDimitry Andric 3384fe6060f1SDimitry Andric LDVSSABlockIterator &operator++() { 3385fe6060f1SDimitry Andric ++PredIt; 3386fe6060f1SDimitry Andric return *this; 3387fe6060f1SDimitry Andric } 3388fe6060f1SDimitry Andric 3389fe6060f1SDimitry Andric LDVSSABlock *operator*(); 3390fe6060f1SDimitry Andric }; 3391fe6060f1SDimitry Andric 3392fe6060f1SDimitry Andric /// Thin wrapper around a block for SSA Updater interface. Necessary because 3393fe6060f1SDimitry Andric /// we need to track the PHI value(s) that we may have observed as necessary 3394fe6060f1SDimitry Andric /// in this block. 3395fe6060f1SDimitry Andric class LDVSSABlock { 3396fe6060f1SDimitry Andric public: 3397fe6060f1SDimitry Andric MachineBasicBlock &BB; 3398fe6060f1SDimitry Andric LDVSSAUpdater &Updater; 3399fe6060f1SDimitry Andric using PHIListT = SmallVector<LDVSSAPhi, 1>; 3400fe6060f1SDimitry Andric /// List of PHIs in this block. There should only ever be one. 3401fe6060f1SDimitry Andric PHIListT PHIList; 3402fe6060f1SDimitry Andric 3403fe6060f1SDimitry Andric LDVSSABlock(MachineBasicBlock &BB, LDVSSAUpdater &Updater) 3404fe6060f1SDimitry Andric : BB(BB), Updater(Updater) {} 3405fe6060f1SDimitry Andric 3406fe6060f1SDimitry Andric LDVSSABlockIterator succ_begin() { 3407fe6060f1SDimitry Andric return LDVSSABlockIterator(BB.succ_begin(), Updater); 3408fe6060f1SDimitry Andric } 3409fe6060f1SDimitry Andric 3410fe6060f1SDimitry Andric LDVSSABlockIterator succ_end() { 3411fe6060f1SDimitry Andric return LDVSSABlockIterator(BB.succ_end(), Updater); 3412fe6060f1SDimitry Andric } 3413fe6060f1SDimitry Andric 3414fe6060f1SDimitry Andric /// SSAUpdater has requested a PHI: create that within this block record. 3415fe6060f1SDimitry Andric LDVSSAPhi *newPHI(BlockValueNum Value) { 3416fe6060f1SDimitry Andric PHIList.emplace_back(Value, this); 3417fe6060f1SDimitry Andric return &PHIList.back(); 3418fe6060f1SDimitry Andric } 3419fe6060f1SDimitry Andric 3420fe6060f1SDimitry Andric /// SSAUpdater wishes to know what PHIs already exist in this block. 3421fe6060f1SDimitry Andric PHIListT &phis() { return PHIList; } 3422fe6060f1SDimitry Andric }; 3423fe6060f1SDimitry Andric 3424fe6060f1SDimitry Andric /// Utility class for the SSAUpdater interface: tracks blocks, PHIs and values 3425fe6060f1SDimitry Andric /// while SSAUpdater is exploring the CFG. It's passed as a handle / baton to 3426fe6060f1SDimitry Andric // SSAUpdaterTraits<LDVSSAUpdater>. 3427fe6060f1SDimitry Andric class LDVSSAUpdater { 3428fe6060f1SDimitry Andric public: 3429fe6060f1SDimitry Andric /// Map of value numbers to PHI records. 3430fe6060f1SDimitry Andric DenseMap<BlockValueNum, LDVSSAPhi *> PHIs; 3431fe6060f1SDimitry Andric /// Map of which blocks generate Undef values -- blocks that are not 3432fe6060f1SDimitry Andric /// dominated by any Def. 3433fe6060f1SDimitry Andric DenseMap<MachineBasicBlock *, BlockValueNum> UndefMap; 3434fe6060f1SDimitry Andric /// Map of machine blocks to our own records of them. 3435fe6060f1SDimitry Andric DenseMap<MachineBasicBlock *, LDVSSABlock *> BlockMap; 3436fe6060f1SDimitry Andric /// Machine location where any PHI must occur. 3437fe6060f1SDimitry Andric LocIdx Loc; 3438fe6060f1SDimitry Andric /// Table of live-in machine value numbers for blocks / locations. 343981ad6265SDimitry Andric const ValueTable *MLiveIns; 3440fe6060f1SDimitry Andric 344181ad6265SDimitry Andric LDVSSAUpdater(LocIdx L, const ValueTable *MLiveIns) 344281ad6265SDimitry Andric : Loc(L), MLiveIns(MLiveIns) {} 3443fe6060f1SDimitry Andric 3444fe6060f1SDimitry Andric void reset() { 3445fe6060f1SDimitry Andric for (auto &Block : BlockMap) 3446fe6060f1SDimitry Andric delete Block.second; 3447fe6060f1SDimitry Andric 3448fe6060f1SDimitry Andric PHIs.clear(); 3449fe6060f1SDimitry Andric UndefMap.clear(); 3450fe6060f1SDimitry Andric BlockMap.clear(); 3451fe6060f1SDimitry Andric } 3452fe6060f1SDimitry Andric 3453fe6060f1SDimitry Andric ~LDVSSAUpdater() { reset(); } 3454fe6060f1SDimitry Andric 3455fe6060f1SDimitry Andric /// For a given MBB, create a wrapper block for it. Stores it in the 3456fe6060f1SDimitry Andric /// LDVSSAUpdater block map. 3457fe6060f1SDimitry Andric LDVSSABlock *getSSALDVBlock(MachineBasicBlock *BB) { 3458fe6060f1SDimitry Andric auto it = BlockMap.find(BB); 3459fe6060f1SDimitry Andric if (it == BlockMap.end()) { 3460fe6060f1SDimitry Andric BlockMap[BB] = new LDVSSABlock(*BB, *this); 3461fe6060f1SDimitry Andric it = BlockMap.find(BB); 3462fe6060f1SDimitry Andric } 3463fe6060f1SDimitry Andric return it->second; 3464fe6060f1SDimitry Andric } 3465fe6060f1SDimitry Andric 3466fe6060f1SDimitry Andric /// Find the live-in value number for the given block. Looks up the value at 3467fe6060f1SDimitry Andric /// the PHI location on entry. 3468fe6060f1SDimitry Andric BlockValueNum getValue(LDVSSABlock *LDVBB) { 3469fe6060f1SDimitry Andric return MLiveIns[LDVBB->BB.getNumber()][Loc.asU64()].asU64(); 3470fe6060f1SDimitry Andric } 3471fe6060f1SDimitry Andric }; 3472fe6060f1SDimitry Andric 3473fe6060f1SDimitry Andric LDVSSABlock *LDVSSABlockIterator::operator*() { 3474fe6060f1SDimitry Andric return Updater.getSSALDVBlock(*PredIt); 3475fe6060f1SDimitry Andric } 3476fe6060f1SDimitry Andric 3477fe6060f1SDimitry Andric #ifndef NDEBUG 3478fe6060f1SDimitry Andric 3479fe6060f1SDimitry Andric raw_ostream &operator<<(raw_ostream &out, const LDVSSAPhi &PHI) { 3480fe6060f1SDimitry Andric out << "SSALDVPHI " << PHI.PHIValNum; 3481fe6060f1SDimitry Andric return out; 3482fe6060f1SDimitry Andric } 3483fe6060f1SDimitry Andric 3484fe6060f1SDimitry Andric #endif 3485fe6060f1SDimitry Andric 3486fe6060f1SDimitry Andric } // namespace 3487fe6060f1SDimitry Andric 3488fe6060f1SDimitry Andric namespace llvm { 3489fe6060f1SDimitry Andric 3490fe6060f1SDimitry Andric /// Template specialization to give SSAUpdater access to CFG and value 3491fe6060f1SDimitry Andric /// information. SSAUpdater calls methods in these traits, passing in the 3492fe6060f1SDimitry Andric /// LDVSSAUpdater object, to learn about blocks and the values they define. 3493fe6060f1SDimitry Andric /// It also provides methods to create PHI nodes and track them. 3494fe6060f1SDimitry Andric template <> class SSAUpdaterTraits<LDVSSAUpdater> { 3495fe6060f1SDimitry Andric public: 3496fe6060f1SDimitry Andric using BlkT = LDVSSABlock; 3497fe6060f1SDimitry Andric using ValT = BlockValueNum; 3498fe6060f1SDimitry Andric using PhiT = LDVSSAPhi; 3499fe6060f1SDimitry Andric using BlkSucc_iterator = LDVSSABlockIterator; 3500fe6060f1SDimitry Andric 3501fe6060f1SDimitry Andric // Methods to access block successors -- dereferencing to our wrapper class. 3502fe6060f1SDimitry Andric static BlkSucc_iterator BlkSucc_begin(BlkT *BB) { return BB->succ_begin(); } 3503fe6060f1SDimitry Andric static BlkSucc_iterator BlkSucc_end(BlkT *BB) { return BB->succ_end(); } 3504fe6060f1SDimitry Andric 3505fe6060f1SDimitry Andric /// Iterator for PHI operands. 3506fe6060f1SDimitry Andric class PHI_iterator { 3507fe6060f1SDimitry Andric private: 3508fe6060f1SDimitry Andric LDVSSAPhi *PHI; 3509fe6060f1SDimitry Andric unsigned Idx; 3510fe6060f1SDimitry Andric 3511fe6060f1SDimitry Andric public: 3512fe6060f1SDimitry Andric explicit PHI_iterator(LDVSSAPhi *P) // begin iterator 3513fe6060f1SDimitry Andric : PHI(P), Idx(0) {} 3514fe6060f1SDimitry Andric PHI_iterator(LDVSSAPhi *P, bool) // end iterator 3515fe6060f1SDimitry Andric : PHI(P), Idx(PHI->IncomingValues.size()) {} 3516fe6060f1SDimitry Andric 3517fe6060f1SDimitry Andric PHI_iterator &operator++() { 3518fe6060f1SDimitry Andric Idx++; 3519fe6060f1SDimitry Andric return *this; 3520fe6060f1SDimitry Andric } 3521fe6060f1SDimitry Andric bool operator==(const PHI_iterator &X) const { return Idx == X.Idx; } 3522fe6060f1SDimitry Andric bool operator!=(const PHI_iterator &X) const { return !operator==(X); } 3523fe6060f1SDimitry Andric 3524fe6060f1SDimitry Andric BlockValueNum getIncomingValue() { return PHI->IncomingValues[Idx].second; } 3525fe6060f1SDimitry Andric 3526fe6060f1SDimitry Andric LDVSSABlock *getIncomingBlock() { return PHI->IncomingValues[Idx].first; } 3527fe6060f1SDimitry Andric }; 3528fe6060f1SDimitry Andric 3529fe6060f1SDimitry Andric static inline PHI_iterator PHI_begin(PhiT *PHI) { return PHI_iterator(PHI); } 3530fe6060f1SDimitry Andric 3531fe6060f1SDimitry Andric static inline PHI_iterator PHI_end(PhiT *PHI) { 3532fe6060f1SDimitry Andric return PHI_iterator(PHI, true); 3533fe6060f1SDimitry Andric } 3534fe6060f1SDimitry Andric 3535fe6060f1SDimitry Andric /// FindPredecessorBlocks - Put the predecessors of BB into the Preds 3536fe6060f1SDimitry Andric /// vector. 3537fe6060f1SDimitry Andric static void FindPredecessorBlocks(LDVSSABlock *BB, 3538fe6060f1SDimitry Andric SmallVectorImpl<LDVSSABlock *> *Preds) { 3539349cc55cSDimitry Andric for (MachineBasicBlock *Pred : BB->BB.predecessors()) 3540349cc55cSDimitry Andric Preds->push_back(BB->Updater.getSSALDVBlock(Pred)); 3541fe6060f1SDimitry Andric } 3542fe6060f1SDimitry Andric 3543fe6060f1SDimitry Andric /// GetUndefVal - Normally creates an IMPLICIT_DEF instruction with a new 3544fe6060f1SDimitry Andric /// register. For LiveDebugValues, represents a block identified as not having 3545fe6060f1SDimitry Andric /// any DBG_PHI predecessors. 3546fe6060f1SDimitry Andric static BlockValueNum GetUndefVal(LDVSSABlock *BB, LDVSSAUpdater *Updater) { 3547fe6060f1SDimitry Andric // Create a value number for this block -- it needs to be unique and in the 3548fe6060f1SDimitry Andric // "undef" collection, so that we know it's not real. Use a number 3549fe6060f1SDimitry Andric // representing a PHI into this block. 3550fe6060f1SDimitry Andric BlockValueNum Num = ValueIDNum(BB->BB.getNumber(), 0, Updater->Loc).asU64(); 3551fe6060f1SDimitry Andric Updater->UndefMap[&BB->BB] = Num; 3552fe6060f1SDimitry Andric return Num; 3553fe6060f1SDimitry Andric } 3554fe6060f1SDimitry Andric 3555fe6060f1SDimitry Andric /// CreateEmptyPHI - Create a (representation of a) PHI in the given block. 3556fe6060f1SDimitry Andric /// SSAUpdater will populate it with information about incoming values. The 3557fe6060f1SDimitry Andric /// value number of this PHI is whatever the machine value number problem 3558fe6060f1SDimitry Andric /// solution determined it to be. This includes non-phi values if SSAUpdater 3559fe6060f1SDimitry Andric /// tries to create a PHI where the incoming values are identical. 3560fe6060f1SDimitry Andric static BlockValueNum CreateEmptyPHI(LDVSSABlock *BB, unsigned NumPreds, 3561fe6060f1SDimitry Andric LDVSSAUpdater *Updater) { 3562fe6060f1SDimitry Andric BlockValueNum PHIValNum = Updater->getValue(BB); 3563fe6060f1SDimitry Andric LDVSSAPhi *PHI = BB->newPHI(PHIValNum); 3564fe6060f1SDimitry Andric Updater->PHIs[PHIValNum] = PHI; 3565fe6060f1SDimitry Andric return PHIValNum; 3566fe6060f1SDimitry Andric } 3567fe6060f1SDimitry Andric 3568fe6060f1SDimitry Andric /// AddPHIOperand - Add the specified value as an operand of the PHI for 3569fe6060f1SDimitry Andric /// the specified predecessor block. 3570fe6060f1SDimitry Andric static void AddPHIOperand(LDVSSAPhi *PHI, BlockValueNum Val, LDVSSABlock *Pred) { 3571fe6060f1SDimitry Andric PHI->IncomingValues.push_back(std::make_pair(Pred, Val)); 3572fe6060f1SDimitry Andric } 3573fe6060f1SDimitry Andric 3574fe6060f1SDimitry Andric /// ValueIsPHI - Check if the instruction that defines the specified value 3575fe6060f1SDimitry Andric /// is a PHI instruction. 3576fe6060f1SDimitry Andric static LDVSSAPhi *ValueIsPHI(BlockValueNum Val, LDVSSAUpdater *Updater) { 3577fe6060f1SDimitry Andric auto PHIIt = Updater->PHIs.find(Val); 3578fe6060f1SDimitry Andric if (PHIIt == Updater->PHIs.end()) 3579fe6060f1SDimitry Andric return nullptr; 3580fe6060f1SDimitry Andric return PHIIt->second; 3581fe6060f1SDimitry Andric } 3582fe6060f1SDimitry Andric 3583fe6060f1SDimitry Andric /// ValueIsNewPHI - Like ValueIsPHI but also check if the PHI has no source 3584fe6060f1SDimitry Andric /// operands, i.e., it was just added. 3585fe6060f1SDimitry Andric static LDVSSAPhi *ValueIsNewPHI(BlockValueNum Val, LDVSSAUpdater *Updater) { 3586fe6060f1SDimitry Andric LDVSSAPhi *PHI = ValueIsPHI(Val, Updater); 3587fe6060f1SDimitry Andric if (PHI && PHI->IncomingValues.size() == 0) 3588fe6060f1SDimitry Andric return PHI; 3589fe6060f1SDimitry Andric return nullptr; 3590fe6060f1SDimitry Andric } 3591fe6060f1SDimitry Andric 3592fe6060f1SDimitry Andric /// GetPHIValue - For the specified PHI instruction, return the value 3593fe6060f1SDimitry Andric /// that it defines. 3594fe6060f1SDimitry Andric static BlockValueNum GetPHIValue(LDVSSAPhi *PHI) { return PHI->PHIValNum; } 3595fe6060f1SDimitry Andric }; 3596fe6060f1SDimitry Andric 3597fe6060f1SDimitry Andric } // end namespace llvm 3598fe6060f1SDimitry Andric 359981ad6265SDimitry Andric Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIs( 360081ad6265SDimitry Andric MachineFunction &MF, const ValueTable *MLiveOuts, 360181ad6265SDimitry Andric const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) { 360281ad6265SDimitry Andric assert(MLiveOuts && MLiveIns && 360381ad6265SDimitry Andric "Tried to resolve DBG_PHI before location " 360481ad6265SDimitry Andric "tables allocated?"); 360581ad6265SDimitry Andric 3606d56accc7SDimitry Andric // This function will be called twice per DBG_INSTR_REF, and might end up 3607d56accc7SDimitry Andric // computing lots of SSA information: memoize it. 3608d56accc7SDimitry Andric auto SeenDbgPHIIt = SeenDbgPHIs.find(&Here); 3609d56accc7SDimitry Andric if (SeenDbgPHIIt != SeenDbgPHIs.end()) 3610d56accc7SDimitry Andric return SeenDbgPHIIt->second; 3611d56accc7SDimitry Andric 3612d56accc7SDimitry Andric Optional<ValueIDNum> Result = 3613d56accc7SDimitry Andric resolveDbgPHIsImpl(MF, MLiveOuts, MLiveIns, Here, InstrNum); 3614d56accc7SDimitry Andric SeenDbgPHIs.insert({&Here, Result}); 3615d56accc7SDimitry Andric return Result; 3616d56accc7SDimitry Andric } 3617d56accc7SDimitry Andric 3618d56accc7SDimitry Andric Optional<ValueIDNum> InstrRefBasedLDV::resolveDbgPHIsImpl( 361981ad6265SDimitry Andric MachineFunction &MF, const ValueTable *MLiveOuts, 362081ad6265SDimitry Andric const ValueTable *MLiveIns, MachineInstr &Here, uint64_t InstrNum) { 3621fe6060f1SDimitry Andric // Pick out records of DBG_PHI instructions that have been observed. If there 3622fe6060f1SDimitry Andric // are none, then we cannot compute a value number. 3623fe6060f1SDimitry Andric auto RangePair = std::equal_range(DebugPHINumToValue.begin(), 3624fe6060f1SDimitry Andric DebugPHINumToValue.end(), InstrNum); 3625fe6060f1SDimitry Andric auto LowerIt = RangePair.first; 3626fe6060f1SDimitry Andric auto UpperIt = RangePair.second; 3627fe6060f1SDimitry Andric 3628fe6060f1SDimitry Andric // No DBG_PHI means there can be no location. 3629fe6060f1SDimitry Andric if (LowerIt == UpperIt) 3630fe6060f1SDimitry Andric return None; 3631fe6060f1SDimitry Andric 363281ad6265SDimitry Andric // If any DBG_PHIs referred to a location we didn't understand, don't try to 363381ad6265SDimitry Andric // compute a value. There might be scenarios where we could recover a value 363481ad6265SDimitry Andric // for some range of DBG_INSTR_REFs, but at this point we can have high 363581ad6265SDimitry Andric // confidence that we've seen a bug. 363681ad6265SDimitry Andric auto DBGPHIRange = make_range(LowerIt, UpperIt); 363781ad6265SDimitry Andric for (const DebugPHIRecord &DBG_PHI : DBGPHIRange) 363881ad6265SDimitry Andric if (!DBG_PHI.ValueRead) 363981ad6265SDimitry Andric return None; 364081ad6265SDimitry Andric 3641fe6060f1SDimitry Andric // If there's only one DBG_PHI, then that is our value number. 3642fe6060f1SDimitry Andric if (std::distance(LowerIt, UpperIt) == 1) 364381ad6265SDimitry Andric return *LowerIt->ValueRead; 3644fe6060f1SDimitry Andric 3645fe6060f1SDimitry Andric // Pick out the location (physreg, slot) where any PHIs must occur. It's 3646fe6060f1SDimitry Andric // technically possible for us to merge values in different registers in each 3647fe6060f1SDimitry Andric // block, but highly unlikely that LLVM will generate such code after register 3648fe6060f1SDimitry Andric // allocation. 364981ad6265SDimitry Andric LocIdx Loc = *LowerIt->ReadLoc; 3650fe6060f1SDimitry Andric 3651fe6060f1SDimitry Andric // We have several DBG_PHIs, and a use position (the Here inst). All each 3652fe6060f1SDimitry Andric // DBG_PHI does is identify a value at a program position. We can treat each 3653fe6060f1SDimitry Andric // DBG_PHI like it's a Def of a value, and the use position is a Use of a 3654fe6060f1SDimitry Andric // value, just like SSA. We use the bulk-standard LLVM SSA updater class to 3655fe6060f1SDimitry Andric // determine which Def is used at the Use, and any PHIs that happen along 3656fe6060f1SDimitry Andric // the way. 3657fe6060f1SDimitry Andric // Adapted LLVM SSA Updater: 3658fe6060f1SDimitry Andric LDVSSAUpdater Updater(Loc, MLiveIns); 3659fe6060f1SDimitry Andric // Map of which Def or PHI is the current value in each block. 3660fe6060f1SDimitry Andric DenseMap<LDVSSABlock *, BlockValueNum> AvailableValues; 3661fe6060f1SDimitry Andric // Set of PHIs that we have created along the way. 3662fe6060f1SDimitry Andric SmallVector<LDVSSAPhi *, 8> CreatedPHIs; 3663fe6060f1SDimitry Andric 3664fe6060f1SDimitry Andric // Each existing DBG_PHI is a Def'd value under this model. Record these Defs 3665fe6060f1SDimitry Andric // for the SSAUpdater. 3666fe6060f1SDimitry Andric for (const auto &DBG_PHI : DBGPHIRange) { 3667fe6060f1SDimitry Andric LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB); 366881ad6265SDimitry Andric const ValueIDNum &Num = *DBG_PHI.ValueRead; 3669fe6060f1SDimitry Andric AvailableValues.insert(std::make_pair(Block, Num.asU64())); 3670fe6060f1SDimitry Andric } 3671fe6060f1SDimitry Andric 3672fe6060f1SDimitry Andric LDVSSABlock *HereBlock = Updater.getSSALDVBlock(Here.getParent()); 3673fe6060f1SDimitry Andric const auto &AvailIt = AvailableValues.find(HereBlock); 3674fe6060f1SDimitry Andric if (AvailIt != AvailableValues.end()) { 3675fe6060f1SDimitry Andric // Actually, we already know what the value is -- the Use is in the same 3676fe6060f1SDimitry Andric // block as the Def. 3677fe6060f1SDimitry Andric return ValueIDNum::fromU64(AvailIt->second); 3678fe6060f1SDimitry Andric } 3679fe6060f1SDimitry Andric 3680fe6060f1SDimitry Andric // Otherwise, we must use the SSA Updater. It will identify the value number 3681fe6060f1SDimitry Andric // that we are to use, and the PHIs that must happen along the way. 3682fe6060f1SDimitry Andric SSAUpdaterImpl<LDVSSAUpdater> Impl(&Updater, &AvailableValues, &CreatedPHIs); 3683fe6060f1SDimitry Andric BlockValueNum ResultInt = Impl.GetValue(Updater.getSSALDVBlock(Here.getParent())); 3684fe6060f1SDimitry Andric ValueIDNum Result = ValueIDNum::fromU64(ResultInt); 3685fe6060f1SDimitry Andric 3686fe6060f1SDimitry Andric // We have the number for a PHI, or possibly live-through value, to be used 3687fe6060f1SDimitry Andric // at this Use. There are a number of things we have to check about it though: 3688fe6060f1SDimitry Andric // * Does any PHI use an 'Undef' (like an IMPLICIT_DEF) value? If so, this 3689fe6060f1SDimitry Andric // Use was not completely dominated by DBG_PHIs and we should abort. 3690fe6060f1SDimitry Andric // * Are the Defs or PHIs clobbered in a block? SSAUpdater isn't aware that 3691fe6060f1SDimitry Andric // we've left SSA form. Validate that the inputs to each PHI are the 3692fe6060f1SDimitry Andric // expected values. 3693fe6060f1SDimitry Andric // * Is a PHI we've created actually a merging of values, or are all the 3694fe6060f1SDimitry Andric // predecessor values the same, leading to a non-PHI machine value number? 3695fe6060f1SDimitry Andric // (SSAUpdater doesn't know that either). Remap validated PHIs into the 3696fe6060f1SDimitry Andric // the ValidatedValues collection below to sort this out. 3697fe6060f1SDimitry Andric DenseMap<LDVSSABlock *, ValueIDNum> ValidatedValues; 3698fe6060f1SDimitry Andric 3699fe6060f1SDimitry Andric // Define all the input DBG_PHI values in ValidatedValues. 3700fe6060f1SDimitry Andric for (const auto &DBG_PHI : DBGPHIRange) { 3701fe6060f1SDimitry Andric LDVSSABlock *Block = Updater.getSSALDVBlock(DBG_PHI.MBB); 370281ad6265SDimitry Andric const ValueIDNum &Num = *DBG_PHI.ValueRead; 3703fe6060f1SDimitry Andric ValidatedValues.insert(std::make_pair(Block, Num)); 3704fe6060f1SDimitry Andric } 3705fe6060f1SDimitry Andric 3706fe6060f1SDimitry Andric // Sort PHIs to validate into RPO-order. 3707fe6060f1SDimitry Andric SmallVector<LDVSSAPhi *, 8> SortedPHIs; 3708fe6060f1SDimitry Andric for (auto &PHI : CreatedPHIs) 3709fe6060f1SDimitry Andric SortedPHIs.push_back(PHI); 3710fe6060f1SDimitry Andric 3711fcaf7f86SDimitry Andric llvm::sort(SortedPHIs, [&](LDVSSAPhi *A, LDVSSAPhi *B) { 3712fe6060f1SDimitry Andric return BBToOrder[&A->getParent()->BB] < BBToOrder[&B->getParent()->BB]; 3713fe6060f1SDimitry Andric }); 3714fe6060f1SDimitry Andric 3715fe6060f1SDimitry Andric for (auto &PHI : SortedPHIs) { 3716fe6060f1SDimitry Andric ValueIDNum ThisBlockValueNum = 3717fe6060f1SDimitry Andric MLiveIns[PHI->ParentBlock->BB.getNumber()][Loc.asU64()]; 3718fe6060f1SDimitry Andric 3719fe6060f1SDimitry Andric // Are all these things actually defined? 3720fe6060f1SDimitry Andric for (auto &PHIIt : PHI->IncomingValues) { 3721fe6060f1SDimitry Andric // Any undef input means DBG_PHIs didn't dominate the use point. 3722fe6060f1SDimitry Andric if (Updater.UndefMap.find(&PHIIt.first->BB) != Updater.UndefMap.end()) 3723fe6060f1SDimitry Andric return None; 3724fe6060f1SDimitry Andric 3725fe6060f1SDimitry Andric ValueIDNum ValueToCheck; 372681ad6265SDimitry Andric const ValueTable &BlockLiveOuts = MLiveOuts[PHIIt.first->BB.getNumber()]; 3727fe6060f1SDimitry Andric 3728fe6060f1SDimitry Andric auto VVal = ValidatedValues.find(PHIIt.first); 3729fe6060f1SDimitry Andric if (VVal == ValidatedValues.end()) { 3730fe6060f1SDimitry Andric // We cross a loop, and this is a backedge. LLVMs tail duplication 3731fe6060f1SDimitry Andric // happens so late that DBG_PHI instructions should not be able to 3732fe6060f1SDimitry Andric // migrate into loops -- meaning we can only be live-through this 3733fe6060f1SDimitry Andric // loop. 3734fe6060f1SDimitry Andric ValueToCheck = ThisBlockValueNum; 3735fe6060f1SDimitry Andric } else { 3736fe6060f1SDimitry Andric // Does the block have as a live-out, in the location we're examining, 3737fe6060f1SDimitry Andric // the value that we expect? If not, it's been moved or clobbered. 3738fe6060f1SDimitry Andric ValueToCheck = VVal->second; 3739fe6060f1SDimitry Andric } 3740fe6060f1SDimitry Andric 3741fe6060f1SDimitry Andric if (BlockLiveOuts[Loc.asU64()] != ValueToCheck) 3742fe6060f1SDimitry Andric return None; 3743fe6060f1SDimitry Andric } 3744fe6060f1SDimitry Andric 3745fe6060f1SDimitry Andric // Record this value as validated. 3746fe6060f1SDimitry Andric ValidatedValues.insert({PHI->ParentBlock, ThisBlockValueNum}); 3747fe6060f1SDimitry Andric } 3748fe6060f1SDimitry Andric 3749fe6060f1SDimitry Andric // All the PHIs are valid: we can return what the SSAUpdater said our value 3750fe6060f1SDimitry Andric // number was. 3751fe6060f1SDimitry Andric return Result; 3752fe6060f1SDimitry Andric } 3753