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