11adeeabbSDaniel Sanders //===- MachineDebugify.cpp - Attach synthetic debug info to everything ----===//
21adeeabbSDaniel Sanders //
31adeeabbSDaniel Sanders // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
41adeeabbSDaniel Sanders // See https://llvm.org/LICENSE.txt for license information.
51adeeabbSDaniel Sanders // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
61adeeabbSDaniel Sanders //
71adeeabbSDaniel Sanders //===----------------------------------------------------------------------===//
81adeeabbSDaniel Sanders ///
91adeeabbSDaniel Sanders /// \file This pass attaches synthetic debug info to everything. It can be used
10*a852ee19SNico Weber /// to create targeted tests for debug info preservation, or test for CodeGen
11*a852ee19SNico Weber /// differences with vs. without debug info.
121adeeabbSDaniel Sanders ///
131adeeabbSDaniel Sanders /// This isn't intended to have feature parity with Debugify.
141adeeabbSDaniel Sanders //===----------------------------------------------------------------------===//
151adeeabbSDaniel Sanders 
16*a852ee19SNico Weber #include "llvm/ADT/DenseMap.h"
17*a852ee19SNico Weber #include "llvm/ADT/SmallVector.h"
181adeeabbSDaniel Sanders #include "llvm/CodeGen/MachineFunctionPass.h"
19*a852ee19SNico Weber #include "llvm/CodeGen/MachineInstrBuilder.h"
201adeeabbSDaniel Sanders #include "llvm/CodeGen/MachineModuleInfo.h"
211adeeabbSDaniel Sanders #include "llvm/CodeGen/Passes.h"
22*a852ee19SNico Weber #include "llvm/CodeGen/TargetInstrInfo.h"
23*a852ee19SNico Weber #include "llvm/CodeGen/TargetSubtargetInfo.h"
241adeeabbSDaniel Sanders #include "llvm/IR/DIBuilder.h"
251adeeabbSDaniel Sanders #include "llvm/IR/DebugInfo.h"
26*a852ee19SNico Weber #include "llvm/IR/IntrinsicInst.h"
271adeeabbSDaniel Sanders #include "llvm/InitializePasses.h"
281adeeabbSDaniel Sanders #include "llvm/Transforms/Utils/Debugify.h"
291adeeabbSDaniel Sanders 
301adeeabbSDaniel Sanders #define DEBUG_TYPE "mir-debugify"
311adeeabbSDaniel Sanders 
321adeeabbSDaniel Sanders using namespace llvm;
331adeeabbSDaniel Sanders 
341adeeabbSDaniel Sanders namespace {
351adeeabbSDaniel Sanders bool applyDebugifyMetadataToMachineFunction(MachineModuleInfo &MMI,
361adeeabbSDaniel Sanders                                             DIBuilder &DIB, Function &F) {
3714ad8dc0SDaniel Sanders   MachineFunction *MaybeMF = MMI.getMachineFunction(F);
3814ad8dc0SDaniel Sanders   if (!MaybeMF)
3914ad8dc0SDaniel Sanders     return false;
4014ad8dc0SDaniel Sanders   MachineFunction &MF = *MaybeMF;
41*a852ee19SNico Weber   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
421adeeabbSDaniel Sanders 
431adeeabbSDaniel Sanders   DISubprogram *SP = F.getSubprogram();
441adeeabbSDaniel Sanders   assert(SP && "IR Debugify just created it?");
451adeeabbSDaniel Sanders 
46*a852ee19SNico Weber   Module &M = *F.getParent();
47*a852ee19SNico Weber   LLVMContext &Ctx = M.getContext();
48841f9c93SNico Weber 
49*a852ee19SNico Weber   unsigned NextLine = SP->getLine();
501adeeabbSDaniel Sanders   for (MachineBasicBlock &MBB : MF) {
511adeeabbSDaniel Sanders     for (MachineInstr &MI : MBB) {
521adeeabbSDaniel Sanders       // This will likely emit line numbers beyond the end of the imagined
531adeeabbSDaniel Sanders       // source function and into subsequent ones. We don't do anything about
541adeeabbSDaniel Sanders       // that as it doesn't really matter to the compiler where the line is in
551adeeabbSDaniel Sanders       // the imaginary source code.
561adeeabbSDaniel Sanders       MI.setDebugLoc(DILocation::get(Ctx, NextLine++, 1, SP));
571adeeabbSDaniel Sanders     }
581adeeabbSDaniel Sanders   }
591adeeabbSDaniel Sanders 
60*a852ee19SNico Weber   // Find local variables defined by debugify. No attempt is made to match up
61*a852ee19SNico Weber   // MIR-level regs to the 'correct' IR-level variables: there isn't a simple
62*a852ee19SNico Weber   // way to do that, and it isn't necessary to find interesting CodeGen bugs.
63*a852ee19SNico Weber   // Instead, simply keep track of one variable per line. Later, we can insert
64*a852ee19SNico Weber   // DBG_VALUE insts that point to these local variables. Emitting DBG_VALUEs
65*a852ee19SNico Weber   // which cover a wide range of lines can help stress the debug info passes:
66*a852ee19SNico Weber   // if we can't do that, fall back to using the local variable which precedes
67*a852ee19SNico Weber   // all the others.
68*a852ee19SNico Weber   Function *DbgValF = M.getFunction("llvm.dbg.value");
69*a852ee19SNico Weber   DbgValueInst *EarliestDVI = nullptr;
70*a852ee19SNico Weber   DenseMap<unsigned, DILocalVariable *> Line2Var;
71*a852ee19SNico Weber   DIExpression *Expr = nullptr;
72*a852ee19SNico Weber   if (DbgValF) {
73*a852ee19SNico Weber     for (const Use &U : DbgValF->uses()) {
74*a852ee19SNico Weber       auto *DVI = dyn_cast<DbgValueInst>(U.getUser());
75*a852ee19SNico Weber       if (!DVI || DVI->getFunction() != &F)
76*a852ee19SNico Weber         continue;
77*a852ee19SNico Weber       unsigned Line = DVI->getDebugLoc().getLine();
78*a852ee19SNico Weber       assert(Line != 0 && "debugify should not insert line 0 locations");
79*a852ee19SNico Weber       Line2Var[Line] = DVI->getVariable();
80*a852ee19SNico Weber       if (!EarliestDVI || Line < EarliestDVI->getDebugLoc().getLine())
81*a852ee19SNico Weber         EarliestDVI = DVI;
82*a852ee19SNico Weber       Expr = DVI->getExpression();
83*a852ee19SNico Weber     }
84*a852ee19SNico Weber   }
85*a852ee19SNico Weber   if (Line2Var.empty())
86*a852ee19SNico Weber     return true;
87*a852ee19SNico Weber 
88*a852ee19SNico Weber   // Now, try to insert a DBG_VALUE instruction after each real instruction.
89*a852ee19SNico Weber   // Do this by introducing debug uses of each register definition. If that is
90*a852ee19SNico Weber   // not possible (e.g. we have a phi or a meta instruction), emit a constant.
91*a852ee19SNico Weber   uint64_t NextImm = 0;
92*a852ee19SNico Weber   const MCInstrDesc &DbgValDesc = TII.get(TargetOpcode::DBG_VALUE);
93*a852ee19SNico Weber   for (MachineBasicBlock &MBB : MF) {
94*a852ee19SNico Weber     MachineBasicBlock::iterator FirstNonPHIIt = MBB.getFirstNonPHI();
95*a852ee19SNico Weber     for (auto I = MBB.begin(), E = MBB.end(); I != E; ) {
96*a852ee19SNico Weber       MachineInstr &MI = *I;
97*a852ee19SNico Weber       ++I;
98*a852ee19SNico Weber 
99*a852ee19SNico Weber       // `I` may point to a DBG_VALUE created in the previous loop iteration.
100*a852ee19SNico Weber       if (MI.isDebugInstr())
101*a852ee19SNico Weber         continue;
102*a852ee19SNico Weber 
103*a852ee19SNico Weber       // It's not allowed to insert DBG_VALUEs after a terminator.
104*a852ee19SNico Weber       if (MI.isTerminator())
105*a852ee19SNico Weber         continue;
106*a852ee19SNico Weber 
107*a852ee19SNico Weber       // Find a suitable insertion point for the DBG_VALUE.
108*a852ee19SNico Weber       auto InsertBeforeIt = MI.isPHI() ? FirstNonPHIIt : I;
109*a852ee19SNico Weber 
110*a852ee19SNico Weber       // Find a suitable local variable for the DBG_VALUE.
111*a852ee19SNico Weber       unsigned Line = MI.getDebugLoc().getLine();
112*a852ee19SNico Weber       if (!Line2Var.count(Line))
113*a852ee19SNico Weber         Line = EarliestDVI->getDebugLoc().getLine();
114*a852ee19SNico Weber       DILocalVariable *LocalVar = Line2Var[Line];
115*a852ee19SNico Weber       assert(LocalVar && "No variable for current line?");
116*a852ee19SNico Weber 
117*a852ee19SNico Weber       // Emit DBG_VALUEs for register definitions.
118*a852ee19SNico Weber       SmallVector<MachineOperand *, 4> RegDefs;
119*a852ee19SNico Weber       for (MachineOperand &MO : MI.operands())
120*a852ee19SNico Weber         if (MO.isReg() && MO.isDef() && MO.getReg())
121*a852ee19SNico Weber           RegDefs.push_back(&MO);
122*a852ee19SNico Weber       for (MachineOperand *MO : RegDefs)
123*a852ee19SNico Weber         BuildMI(MBB, InsertBeforeIt, MI.getDebugLoc(), DbgValDesc,
124*a852ee19SNico Weber                 /*IsIndirect=*/false, *MO, LocalVar, Expr);
125*a852ee19SNico Weber 
126*a852ee19SNico Weber       // OK, failing that, emit a constant DBG_VALUE.
127*a852ee19SNico Weber       if (RegDefs.empty()) {
128*a852ee19SNico Weber         auto ImmOp = MachineOperand::CreateImm(NextImm++);
129*a852ee19SNico Weber         BuildMI(MBB, InsertBeforeIt, MI.getDebugLoc(), DbgValDesc,
130*a852ee19SNico Weber                 /*IsIndirect=*/false, ImmOp, LocalVar, Expr);
131*a852ee19SNico Weber       }
132*a852ee19SNico Weber     }
133*a852ee19SNico Weber   }
134*a852ee19SNico Weber 
1351adeeabbSDaniel Sanders   return true;
1361adeeabbSDaniel Sanders }
1371adeeabbSDaniel Sanders 
1381adeeabbSDaniel Sanders /// ModulePass for attaching synthetic debug info to everything, used with the
1391adeeabbSDaniel Sanders /// legacy module pass manager.
1401adeeabbSDaniel Sanders struct DebugifyMachineModule : public ModulePass {
1411adeeabbSDaniel Sanders   bool runOnModule(Module &M) override {
1421adeeabbSDaniel Sanders     MachineModuleInfo &MMI =
1431adeeabbSDaniel Sanders         getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
1441adeeabbSDaniel Sanders     return applyDebugifyMetadata(
1451adeeabbSDaniel Sanders         M, M.functions(),
1461adeeabbSDaniel Sanders         "ModuleDebugify: ", [&](DIBuilder &DIB, Function &F) -> bool {
1471adeeabbSDaniel Sanders           return applyDebugifyMetadataToMachineFunction(MMI, DIB, F);
1481adeeabbSDaniel Sanders         });
1491adeeabbSDaniel Sanders   }
1501adeeabbSDaniel Sanders 
1511adeeabbSDaniel Sanders   DebugifyMachineModule() : ModulePass(ID) {}
1521adeeabbSDaniel Sanders 
1531adeeabbSDaniel Sanders   void getAnalysisUsage(AnalysisUsage &AU) const override {
1541adeeabbSDaniel Sanders     AU.addRequired<MachineModuleInfoWrapperPass>();
1551adeeabbSDaniel Sanders     AU.addPreserved<MachineModuleInfoWrapperPass>();
156f71350f0SDaniel Sanders     AU.setPreservesCFG();
1571adeeabbSDaniel Sanders   }
1581adeeabbSDaniel Sanders 
1591adeeabbSDaniel Sanders   static char ID; // Pass identification.
1601adeeabbSDaniel Sanders };
1611adeeabbSDaniel Sanders char DebugifyMachineModule::ID = 0;
1621adeeabbSDaniel Sanders 
1631adeeabbSDaniel Sanders } // end anonymous namespace
1641adeeabbSDaniel Sanders 
1651adeeabbSDaniel Sanders INITIALIZE_PASS_BEGIN(DebugifyMachineModule, DEBUG_TYPE,
1661adeeabbSDaniel Sanders                       "Machine Debugify Module", false, false)
1671adeeabbSDaniel Sanders INITIALIZE_PASS_END(DebugifyMachineModule, DEBUG_TYPE,
1681adeeabbSDaniel Sanders                     "Machine Debugify Module", false, false)
1691adeeabbSDaniel Sanders 
170f71350f0SDaniel Sanders ModulePass *llvm::createDebugifyMachineModulePass() {
1711adeeabbSDaniel Sanders   return new DebugifyMachineModule();
1721adeeabbSDaniel Sanders }
173