24cfb361a9f65e564a5ca6b3dd9f9f9a1c291486
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DbgValueHistoryCalculator.cpp
1 //===-- llvm/CodeGen/AsmPrinter/DbgValueHistoryCalculator.cpp -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "DbgValueHistoryCalculator.h"
11 #include "llvm/ADT/BitVector.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/CodeGen/MachineBasicBlock.h"
14 #include "llvm/CodeGen/MachineFunction.h"
15 #include "llvm/IR/DebugInfo.h"
16 #include "llvm/Support/Debug.h"
17 #include "llvm/Support/raw_ostream.h"
18 #include "llvm/Target/TargetRegisterInfo.h"
19 #include <algorithm>
20 #include <map>
21 using namespace llvm;
22
23 #define DEBUG_TYPE "dwarfdebug"
24
25 // \brief If @MI is a DBG_VALUE with debug value described by a
26 // defined register, returns the number of this register.
27 // In the other case, returns 0.
28 static unsigned isDescribedByReg(const MachineInstr &MI) {
29   assert(MI.isDebugValue());
30   assert(MI.getNumOperands() == 4);
31   // If location of variable is described using a register (directly or
32   // indirecltly), this register is always a first operand.
33   return MI.getOperand(0).isReg() ? MI.getOperand(0).getReg() : 0;
34 }
35
36 void DbgValueHistoryMap::startInstrRange(const MDNode *Var,
37                                          const MachineInstr &MI) {
38   // Instruction range should start with a DBG_VALUE instruction for the
39   // variable.
40   assert(MI.isDebugValue() && "not a DBG_VALUE");
41   auto &Ranges = VarInstrRanges[Var];
42   if (!Ranges.empty() && Ranges.back().second == nullptr &&
43       Ranges.back().first->isIdenticalTo(&MI)) {
44     DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
45                  << "\t" << Ranges.back().first << "\t" << MI << "\n");
46     return;
47   }
48   Ranges.push_back(std::make_pair(&MI, nullptr));
49 }
50
51 void DbgValueHistoryMap::endInstrRange(const MDNode *Var,
52                                        const MachineInstr &MI) {
53   auto &Ranges = VarInstrRanges[Var];
54   // Verify that the current instruction range is not yet closed.
55   assert(!Ranges.empty() && Ranges.back().second == nullptr);
56   // For now, instruction ranges are not allowed to cross basic block
57   // boundaries.
58   assert(Ranges.back().first->getParent() == MI.getParent());
59   Ranges.back().second = &MI;
60 }
61
62 unsigned DbgValueHistoryMap::getRegisterForVar(const MDNode *Var) const {
63   const auto &I = VarInstrRanges.find(Var);
64   if (I == VarInstrRanges.end())
65     return 0;
66   const auto &Ranges = I->second;
67   if (Ranges.empty() || Ranges.back().second != nullptr)
68     return 0;
69   return isDescribedByReg(*Ranges.back().first);
70 }
71
72 namespace {
73 // Maps physreg numbers to the variables they describe.
74 typedef std::map<unsigned, SmallVector<const MDNode *, 1>> RegDescribedVarsMap;
75 }
76
77 // \brief Claim that @Var is not described by @RegNo anymore.
78 static void dropRegDescribedVar(RegDescribedVarsMap &RegVars,
79                                 unsigned RegNo, const MDNode *Var) {
80   const auto &I = RegVars.find(RegNo);
81   assert(RegNo != 0U && I != RegVars.end());
82   auto &VarSet = I->second;
83   const auto &VarPos = std::find(VarSet.begin(), VarSet.end(), Var);
84   assert(VarPos != VarSet.end());
85   VarSet.erase(VarPos);
86   // Don't keep empty sets in a map to keep it as small as possible.
87   if (VarSet.empty())
88     RegVars.erase(I);
89 }
90
91 // \brief Claim that @Var is now described by @RegNo.
92 static void addRegDescribedVar(RegDescribedVarsMap &RegVars,
93                                unsigned RegNo, const MDNode *Var) {
94   assert(RegNo != 0U);
95   auto &VarSet = RegVars[RegNo];
96   assert(std::find(VarSet.begin(), VarSet.end(), Var) == VarSet.end());
97   VarSet.push_back(Var);
98 }
99
100 // \brief Terminate the location range for variables described by register at
101 // @I by inserting @ClobberingInstr to their history.
102 static void clobberRegisterUses(RegDescribedVarsMap &RegVars,
103                                 RegDescribedVarsMap::iterator I,
104                                 DbgValueHistoryMap &HistMap,
105                                 const MachineInstr &ClobberingInstr) {
106   // Iterate over all variables described by this register and add this
107   // instruction to their history, clobbering it.
108   for (const auto &Var : I->second)
109     HistMap.endInstrRange(Var, ClobberingInstr);
110   RegVars.erase(I);
111 }
112
113 // \brief Terminate the location range for variables described by register
114 // @RegNo by inserting @ClobberingInstr to their history.
115 static void clobberRegisterUses(RegDescribedVarsMap &RegVars, unsigned RegNo,
116                                 DbgValueHistoryMap &HistMap,
117                                 const MachineInstr &ClobberingInstr) {
118   const auto &I = RegVars.find(RegNo);
119   if (I == RegVars.end())
120     return;
121   clobberRegisterUses(RegVars, I, HistMap, ClobberingInstr);
122 }
123
124 // \brief Collect all registers clobbered by @MI and apply the functor
125 // @Func to their RegNo.
126 // @Func should be a functor with a void(unsigned) signature. We're
127 // not using std::function here for performance reasons. It has a
128 // small but measurable impact. By using a functor instead of a
129 // std::set& here, we can avoid the overhead of constructing
130 // temporaries in calculateDbgValueHistory, which has a significant
131 // performance impact.
132 template<typename Callable>
133 static void applyToClobberedRegisters(const MachineInstr &MI,
134                                       const TargetRegisterInfo *TRI,
135                                       Callable Func) {
136   for (const MachineOperand &MO : MI.operands()) {
137     if (!MO.isReg() || !MO.isDef() || !MO.getReg())
138       continue;
139     for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI)
140       Func(*AI);
141   }
142 }
143
144 // \brief Returns the first instruction in @MBB which corresponds to
145 // the function epilogue, or nullptr if @MBB doesn't contain an epilogue.
146 static const MachineInstr *getFirstEpilogueInst(const MachineBasicBlock &MBB) {
147   auto LastMI = MBB.getLastNonDebugInstr();
148   if (LastMI == MBB.end() || !LastMI->isReturn())
149     return nullptr;
150   // Assume that epilogue starts with instruction having the same debug location
151   // as the return instruction.
152   DebugLoc LastLoc = LastMI->getDebugLoc();
153   auto Res = LastMI;
154   for (MachineBasicBlock::const_reverse_iterator I(std::next(LastMI)),
155        E = MBB.rend();
156        I != E; ++I) {
157     if (I->getDebugLoc() != LastLoc)
158       return Res;
159     Res = &*I;
160   }
161   // If all instructions have the same debug location, assume whole MBB is
162   // an epilogue.
163   return MBB.begin();
164 }
165
166 // \brief Collect registers that are modified in the function body (their
167 // contents is changed outside of the prologue and epilogue).
168 static void collectChangingRegs(const MachineFunction *MF,
169                                 const TargetRegisterInfo *TRI,
170                                 BitVector &Regs) {
171   for (const auto &MBB : *MF) {
172     auto FirstEpilogueInst = getFirstEpilogueInst(MBB);
173
174     for (const auto &MI : MBB) {
175       if (&MI == FirstEpilogueInst)
176         break;
177       if (!MI.getFlag(MachineInstr::FrameSetup))
178         applyToClobberedRegisters(MI, TRI, [&](unsigned r) { Regs.set(r); });
179     }
180   }
181 }
182
183 void llvm::calculateDbgValueHistory(const MachineFunction *MF,
184                                     const TargetRegisterInfo *TRI,
185                                     DbgValueHistoryMap &Result) {
186   BitVector ChangingRegs(TRI->getNumRegs());
187   collectChangingRegs(MF, TRI, ChangingRegs);
188
189   RegDescribedVarsMap RegVars;
190   for (const auto &MBB : *MF) {
191     for (const auto &MI : MBB) {
192       if (!MI.isDebugValue()) {
193         // Not a DBG_VALUE instruction. It may clobber registers which describe
194         // some variables.
195         applyToClobberedRegisters(MI, TRI, [&](unsigned RegNo) {
196           if (ChangingRegs.test(RegNo))
197             clobberRegisterUses(RegVars, RegNo, Result, MI);
198         });
199         continue;
200       }
201
202       assert(MI.getNumOperands() > 1 && "Invalid DBG_VALUE instruction!");
203       // Use the base variable (without any DW_OP_piece expressions)
204       // as index into History. The full variables including the
205       // piece expressions are attached to the MI.
206       DIVariable Var = MI.getDebugVariable();
207       assert(Var->isValidLocationForIntrinsic(MI.getDebugLoc()) &&
208              "Expected inlined-at fields to agree");
209
210       if (unsigned PrevReg = Result.getRegisterForVar(Var))
211         dropRegDescribedVar(RegVars, PrevReg, Var);
212
213       Result.startInstrRange(Var, MI);
214
215       if (unsigned NewReg = isDescribedByReg(MI))
216         addRegDescribedVar(RegVars, NewReg, Var);
217     }
218
219     // Make sure locations for register-described variables are valid only
220     // until the end of the basic block (unless it's the last basic block, in
221     // which case let their liveness run off to the end of the function).
222     if (!MBB.empty() && &MBB != &MF->back()) {
223       for (auto I = RegVars.begin(), E = RegVars.end(); I != E;) {
224         auto CurElem = I++; // CurElem can be erased below.
225         if (ChangingRegs.test(CurElem->first))
226           clobberRegisterUses(RegVars, CurElem, Result, MBB.back());
227       }
228     }
229   }
230 }