]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/LiveDebugVariables.cpp
Merge ^/head r311132 through r311305.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / CodeGen / LiveDebugVariables.cpp
1 //===- LiveDebugVariables.cpp - Tracking debug info variables -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LiveDebugVariables analysis.
11 //
12 // Remove all DBG_VALUE instructions referencing virtual registers and replace
13 // them with a data structure tracking where live user variables are kept - in a
14 // virtual register or in a stack slot.
15 //
16 // Allow the data structure to be updated during register allocation when values
17 // are moved between registers and stack slots. Finally emit new DBG_VALUE
18 // instructions after register allocation is complete.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "LiveDebugVariables.h"
23 #include "llvm/ADT/IntervalMap.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
26 #include "llvm/CodeGen/MachineDominators.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/CodeGen/VirtRegMap.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/Metadata.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
43 #include <memory>
44 #include <utility>
45
46 using namespace llvm;
47
48 #define DEBUG_TYPE "livedebug"
49
50 static cl::opt<bool>
51 EnableLDV("live-debug-variables", cl::init(true),
52           cl::desc("Enable the live debug variables pass"), cl::Hidden);
53
54 STATISTIC(NumInsertedDebugValues, "Number of DBG_VALUEs inserted");
55 char LiveDebugVariables::ID = 0;
56
57 INITIALIZE_PASS_BEGIN(LiveDebugVariables, "livedebugvars",
58                 "Debug Variable Analysis", false, false)
59 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
60 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
61 INITIALIZE_PASS_END(LiveDebugVariables, "livedebugvars",
62                 "Debug Variable Analysis", false, false)
63
64 void LiveDebugVariables::getAnalysisUsage(AnalysisUsage &AU) const {
65   AU.addRequired<MachineDominatorTree>();
66   AU.addRequiredTransitive<LiveIntervals>();
67   AU.setPreservesAll();
68   MachineFunctionPass::getAnalysisUsage(AU);
69 }
70
71 LiveDebugVariables::LiveDebugVariables() : MachineFunctionPass(ID), pImpl(nullptr) {
72   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
73 }
74
75 /// LocMap - Map of where a user value is live, and its location.
76 typedef IntervalMap<SlotIndex, unsigned, 4> LocMap;
77
78 /// UserValue - A user value is a part of a debug info user variable.
79 ///
80 /// A DBG_VALUE instruction notes that (a sub-register of) a virtual register
81 /// holds part of a user variable. The part is identified by a byte offset.
82 ///
83 /// UserValues are grouped into equivalence classes for easier searching. Two
84 /// user values are related if they refer to the same variable, or if they are
85 /// held by the same virtual register. The equivalence class is the transitive
86 /// closure of that relation.
87 namespace {
88 class LDVImpl;
89 class UserValue {
90   const MDNode *Variable;   ///< The debug info variable we are part of.
91   const MDNode *Expression; ///< Any complex address expression.
92   unsigned offset;        ///< Byte offset into variable.
93   bool IsIndirect;        ///< true if this is a register-indirect+offset value.
94   DebugLoc dl;            ///< The debug location for the variable. This is
95                           ///< used by dwarf writer to find lexical scope.
96   UserValue *leader;      ///< Equivalence class leader.
97   UserValue *next;        ///< Next value in equivalence class, or null.
98
99   /// Numbered locations referenced by locmap.
100   SmallVector<MachineOperand, 4> locations;
101
102   /// Map of slot indices where this value is live.
103   LocMap locInts;
104
105   /// coalesceLocation - After LocNo was changed, check if it has become
106   /// identical to another location, and coalesce them. This may cause LocNo or
107   /// a later location to be erased, but no earlier location will be erased.
108   void coalesceLocation(unsigned LocNo);
109
110   /// insertDebugValue - Insert a DBG_VALUE into MBB at Idx for LocNo.
111   void insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx, unsigned LocNo,
112                         LiveIntervals &LIS, const TargetInstrInfo &TII);
113
114   /// splitLocation - Replace OldLocNo ranges with NewRegs ranges where NewRegs
115   /// is live. Returns true if any changes were made.
116   bool splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
117                      LiveIntervals &LIS);
118
119 public:
120   /// UserValue - Create a new UserValue.
121   UserValue(const MDNode *var, const MDNode *expr, unsigned o, bool i,
122             DebugLoc L, LocMap::Allocator &alloc)
123       : Variable(var), Expression(expr), offset(o), IsIndirect(i),
124         dl(std::move(L)), leader(this), next(nullptr), locInts(alloc) {}
125
126   /// getLeader - Get the leader of this value's equivalence class.
127   UserValue *getLeader() {
128     UserValue *l = leader;
129     while (l != l->leader)
130       l = l->leader;
131     return leader = l;
132   }
133
134   /// getNext - Return the next UserValue in the equivalence class.
135   UserValue *getNext() const { return next; }
136
137   /// match - Does this UserValue match the parameters?
138   bool match(const MDNode *Var, const MDNode *Expr, const DILocation *IA,
139              unsigned Offset, bool indirect) const {
140     return Var == Variable && Expr == Expression && dl->getInlinedAt() == IA &&
141            Offset == offset && indirect == IsIndirect;
142   }
143
144   /// merge - Merge equivalence classes.
145   static UserValue *merge(UserValue *L1, UserValue *L2) {
146     L2 = L2->getLeader();
147     if (!L1)
148       return L2;
149     L1 = L1->getLeader();
150     if (L1 == L2)
151       return L1;
152     // Splice L2 before L1's members.
153     UserValue *End = L2;
154     while (End->next) {
155       End->leader = L1;
156       End = End->next;
157     }
158     End->leader = L1;
159     End->next = L1->next;
160     L1->next = L2;
161     return L1;
162   }
163
164   /// getLocationNo - Return the location number that matches Loc.
165   unsigned getLocationNo(const MachineOperand &LocMO) {
166     if (LocMO.isReg()) {
167       if (LocMO.getReg() == 0)
168         return ~0u;
169       // For register locations we dont care about use/def and other flags.
170       for (unsigned i = 0, e = locations.size(); i != e; ++i)
171         if (locations[i].isReg() &&
172             locations[i].getReg() == LocMO.getReg() &&
173             locations[i].getSubReg() == LocMO.getSubReg())
174           return i;
175     } else
176       for (unsigned i = 0, e = locations.size(); i != e; ++i)
177         if (LocMO.isIdenticalTo(locations[i]))
178           return i;
179     locations.push_back(LocMO);
180     // We are storing a MachineOperand outside a MachineInstr.
181     locations.back().clearParent();
182     // Don't store def operands.
183     if (locations.back().isReg())
184       locations.back().setIsUse();
185     return locations.size() - 1;
186   }
187
188   /// mapVirtRegs - Ensure that all virtual register locations are mapped.
189   void mapVirtRegs(LDVImpl *LDV);
190
191   /// addDef - Add a definition point to this value.
192   void addDef(SlotIndex Idx, const MachineOperand &LocMO) {
193     // Add a singular (Idx,Idx) -> Loc mapping.
194     LocMap::iterator I = locInts.find(Idx);
195     if (!I.valid() || I.start() != Idx)
196       I.insert(Idx, Idx.getNextSlot(), getLocationNo(LocMO));
197     else
198       // A later DBG_VALUE at the same SlotIndex overrides the old location.
199       I.setValue(getLocationNo(LocMO));
200   }
201
202   /// extendDef - Extend the current definition as far as possible down.
203   /// Stop when meeting an existing def or when leaving the live
204   /// range of VNI.
205   /// End points where VNI is no longer live are added to Kills.
206   /// @param Idx   Starting point for the definition.
207   /// @param LocNo Location number to propagate.
208   /// @param LR    Restrict liveness to where LR has the value VNI. May be null.
209   /// @param VNI   When LR is not null, this is the value to restrict to.
210   /// @param Kills Append end points of VNI's live range to Kills.
211   /// @param LIS   Live intervals analysis.
212   void extendDef(SlotIndex Idx, unsigned LocNo,
213                  LiveRange *LR, const VNInfo *VNI,
214                  SmallVectorImpl<SlotIndex> *Kills,
215                  LiveIntervals &LIS);
216
217   /// addDefsFromCopies - The value in LI/LocNo may be copies to other
218   /// registers. Determine if any of the copies are available at the kill
219   /// points, and add defs if possible.
220   /// @param LI      Scan for copies of the value in LI->reg.
221   /// @param LocNo   Location number of LI->reg.
222   /// @param Kills   Points where the range of LocNo could be extended.
223   /// @param NewDefs Append (Idx, LocNo) of inserted defs here.
224   void addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
225                       const SmallVectorImpl<SlotIndex> &Kills,
226                       SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
227                       MachineRegisterInfo &MRI,
228                       LiveIntervals &LIS);
229
230   /// computeIntervals - Compute the live intervals of all locations after
231   /// collecting all their def points.
232   void computeIntervals(MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
233                         LiveIntervals &LIS);
234
235   /// splitRegister - Replace OldReg ranges with NewRegs ranges where NewRegs is
236   /// live. Returns true if any changes were made.
237   bool splitRegister(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
238                      LiveIntervals &LIS);
239
240   /// rewriteLocations - Rewrite virtual register locations according to the
241   /// provided virtual register map.
242   void rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI);
243
244   /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
245   void emitDebugValues(VirtRegMap *VRM,
246                        LiveIntervals &LIS, const TargetInstrInfo &TRI);
247
248   /// getDebugLoc - Return DebugLoc of this UserValue.
249   DebugLoc getDebugLoc() { return dl;}
250   void print(raw_ostream &, const TargetRegisterInfo *);
251 };
252 } // namespace
253
254 /// LDVImpl - Implementation of the LiveDebugVariables pass.
255 namespace {
256 class LDVImpl {
257   LiveDebugVariables &pass;
258   LocMap::Allocator allocator;
259   MachineFunction *MF;
260   LiveIntervals *LIS;
261   const TargetRegisterInfo *TRI;
262
263   /// Whether emitDebugValues is called.
264   bool EmitDone;
265   /// Whether the machine function is modified during the pass.
266   bool ModifiedMF;
267
268   /// userValues - All allocated UserValue instances.
269   SmallVector<std::unique_ptr<UserValue>, 8> userValues;
270
271   /// Map virtual register to eq class leader.
272   typedef DenseMap<unsigned, UserValue*> VRMap;
273   VRMap virtRegToEqClass;
274
275   /// Map user variable to eq class leader.
276   typedef DenseMap<const MDNode *, UserValue*> UVMap;
277   UVMap userVarMap;
278
279   /// getUserValue - Find or create a UserValue.
280   UserValue *getUserValue(const MDNode *Var, const MDNode *Expr,
281                           unsigned Offset, bool IsIndirect, const DebugLoc &DL);
282
283   /// lookupVirtReg - Find the EC leader for VirtReg or null.
284   UserValue *lookupVirtReg(unsigned VirtReg);
285
286   /// handleDebugValue - Add DBG_VALUE instruction to our maps.
287   /// @param MI  DBG_VALUE instruction
288   /// @param Idx Last valid SLotIndex before instruction.
289   /// @return    True if the DBG_VALUE instruction should be deleted.
290   bool handleDebugValue(MachineInstr &MI, SlotIndex Idx);
291
292   /// collectDebugValues - Collect and erase all DBG_VALUE instructions, adding
293   /// a UserValue def for each instruction.
294   /// @param mf MachineFunction to be scanned.
295   /// @return True if any debug values were found.
296   bool collectDebugValues(MachineFunction &mf);
297
298   /// computeIntervals - Compute the live intervals of all user values after
299   /// collecting all their def points.
300   void computeIntervals();
301
302 public:
303   LDVImpl(LiveDebugVariables *ps)
304       : pass(*ps), MF(nullptr), EmitDone(false), ModifiedMF(false) {}
305   bool runOnMachineFunction(MachineFunction &mf);
306
307   /// clear - Release all memory.
308   void clear() {
309     MF = nullptr;
310     userValues.clear();
311     virtRegToEqClass.clear();
312     userVarMap.clear();
313     // Make sure we call emitDebugValues if the machine function was modified.
314     assert((!ModifiedMF || EmitDone) &&
315            "Dbg values are not emitted in LDV");
316     EmitDone = false;
317     ModifiedMF = false;
318   }
319
320   /// mapVirtReg - Map virtual register to an equivalence class.
321   void mapVirtReg(unsigned VirtReg, UserValue *EC);
322
323   /// splitRegister -  Replace all references to OldReg with NewRegs.
324   void splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs);
325
326   /// emitDebugValues - Recreate DBG_VALUE instruction from data structures.
327   void emitDebugValues(VirtRegMap *VRM);
328
329   void print(raw_ostream&);
330 };
331 } // namespace
332
333 static void printDebugLoc(const DebugLoc &DL, raw_ostream &CommentOS,
334                           const LLVMContext &Ctx) {
335   if (!DL)
336     return;
337
338   auto *Scope = cast<DIScope>(DL.getScope());
339   // Omit the directory, because it's likely to be long and uninteresting.
340   CommentOS << Scope->getFilename();
341   CommentOS << ':' << DL.getLine();
342   if (DL.getCol() != 0)
343     CommentOS << ':' << DL.getCol();
344
345   DebugLoc InlinedAtDL = DL.getInlinedAt();
346   if (!InlinedAtDL)
347     return;
348
349   CommentOS << " @[ ";
350   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
351   CommentOS << " ]";
352 }
353
354 static void printExtendedName(raw_ostream &OS, const DILocalVariable *V,
355                               const DILocation *DL) {
356   const LLVMContext &Ctx = V->getContext();
357   StringRef Res = V->getName();
358   if (!Res.empty())
359     OS << Res << "," << V->getLine();
360   if (auto *InlinedAt = DL->getInlinedAt()) {
361     if (DebugLoc InlinedAtDL = InlinedAt) {
362       OS << " @[";
363       printDebugLoc(InlinedAtDL, OS, Ctx);
364       OS << "]";
365     }
366   }
367 }
368
369 void UserValue::print(raw_ostream &OS, const TargetRegisterInfo *TRI) {
370   auto *DV = cast<DILocalVariable>(Variable);
371   OS << "!\"";
372   printExtendedName(OS, DV, dl);
373
374   OS << "\"\t";
375   if (offset)
376     OS << '+' << offset;
377   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I) {
378     OS << " [" << I.start() << ';' << I.stop() << "):";
379     if (I.value() == ~0u)
380       OS << "undef";
381     else
382       OS << I.value();
383   }
384   for (unsigned i = 0, e = locations.size(); i != e; ++i) {
385     OS << " Loc" << i << '=';
386     locations[i].print(OS, TRI);
387   }
388   OS << '\n';
389 }
390
391 void LDVImpl::print(raw_ostream &OS) {
392   OS << "********** DEBUG VARIABLES **********\n";
393   for (unsigned i = 0, e = userValues.size(); i != e; ++i)
394     userValues[i]->print(OS, TRI);
395 }
396
397 void UserValue::coalesceLocation(unsigned LocNo) {
398   unsigned KeepLoc = 0;
399   for (unsigned e = locations.size(); KeepLoc != e; ++KeepLoc) {
400     if (KeepLoc == LocNo)
401       continue;
402     if (locations[KeepLoc].isIdenticalTo(locations[LocNo]))
403       break;
404   }
405   // No matches.
406   if (KeepLoc == locations.size())
407     return;
408
409   // Keep the smaller location, erase the larger one.
410   unsigned EraseLoc = LocNo;
411   if (KeepLoc > EraseLoc)
412     std::swap(KeepLoc, EraseLoc);
413   locations.erase(locations.begin() + EraseLoc);
414
415   // Rewrite values.
416   for (LocMap::iterator I = locInts.begin(); I.valid(); ++I) {
417     unsigned v = I.value();
418     if (v == EraseLoc)
419       I.setValue(KeepLoc);      // Coalesce when possible.
420     else if (v > EraseLoc)
421       I.setValueUnchecked(v-1); // Avoid coalescing with untransformed values.
422   }
423 }
424
425 void UserValue::mapVirtRegs(LDVImpl *LDV) {
426   for (unsigned i = 0, e = locations.size(); i != e; ++i)
427     if (locations[i].isReg() &&
428         TargetRegisterInfo::isVirtualRegister(locations[i].getReg()))
429       LDV->mapVirtReg(locations[i].getReg(), this);
430 }
431
432 UserValue *LDVImpl::getUserValue(const MDNode *Var, const MDNode *Expr,
433                                  unsigned Offset, bool IsIndirect,
434                                  const DebugLoc &DL) {
435   UserValue *&Leader = userVarMap[Var];
436   if (Leader) {
437     UserValue *UV = Leader->getLeader();
438     Leader = UV;
439     for (; UV; UV = UV->getNext())
440       if (UV->match(Var, Expr, DL->getInlinedAt(), Offset, IsIndirect))
441         return UV;
442   }
443
444   userValues.push_back(
445       make_unique<UserValue>(Var, Expr, Offset, IsIndirect, DL, allocator));
446   UserValue *UV = userValues.back().get();
447   Leader = UserValue::merge(Leader, UV);
448   return UV;
449 }
450
451 void LDVImpl::mapVirtReg(unsigned VirtReg, UserValue *EC) {
452   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) && "Only map VirtRegs");
453   UserValue *&Leader = virtRegToEqClass[VirtReg];
454   Leader = UserValue::merge(Leader, EC);
455 }
456
457 UserValue *LDVImpl::lookupVirtReg(unsigned VirtReg) {
458   if (UserValue *UV = virtRegToEqClass.lookup(VirtReg))
459     return UV->getLeader();
460   return nullptr;
461 }
462
463 bool LDVImpl::handleDebugValue(MachineInstr &MI, SlotIndex Idx) {
464   // DBG_VALUE loc, offset, variable
465   if (MI.getNumOperands() != 4 ||
466       !(MI.getOperand(1).isReg() || MI.getOperand(1).isImm()) ||
467       !MI.getOperand(2).isMetadata()) {
468     DEBUG(dbgs() << "Can't handle " << MI);
469     return false;
470   }
471
472   // Get or create the UserValue for (variable,offset).
473   bool IsIndirect = MI.isIndirectDebugValue();
474   unsigned Offset = IsIndirect ? MI.getOperand(1).getImm() : 0;
475   const MDNode *Var = MI.getDebugVariable();
476   const MDNode *Expr = MI.getDebugExpression();
477   //here.
478   UserValue *UV = getUserValue(Var, Expr, Offset, IsIndirect, MI.getDebugLoc());
479   UV->addDef(Idx, MI.getOperand(0));
480   return true;
481 }
482
483 bool LDVImpl::collectDebugValues(MachineFunction &mf) {
484   bool Changed = false;
485   for (MachineFunction::iterator MFI = mf.begin(), MFE = mf.end(); MFI != MFE;
486        ++MFI) {
487     MachineBasicBlock *MBB = &*MFI;
488     for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
489          MBBI != MBBE;) {
490       if (!MBBI->isDebugValue()) {
491         ++MBBI;
492         continue;
493       }
494       // DBG_VALUE has no slot index, use the previous instruction instead.
495       SlotIndex Idx =
496           MBBI == MBB->begin()
497               ? LIS->getMBBStartIdx(MBB)
498               : LIS->getInstructionIndex(*std::prev(MBBI)).getRegSlot();
499       // Handle consecutive DBG_VALUE instructions with the same slot index.
500       do {
501         if (handleDebugValue(*MBBI, Idx)) {
502           MBBI = MBB->erase(MBBI);
503           Changed = true;
504         } else
505           ++MBBI;
506       } while (MBBI != MBBE && MBBI->isDebugValue());
507     }
508   }
509   return Changed;
510 }
511
512 /// We only propagate DBG_VALUES locally here. LiveDebugValues performs a
513 /// data-flow analysis to propagate them beyond basic block boundaries.
514 void UserValue::extendDef(SlotIndex Idx, unsigned LocNo, LiveRange *LR,
515                           const VNInfo *VNI, SmallVectorImpl<SlotIndex> *Kills,
516                           LiveIntervals &LIS) {
517   SlotIndex Start = Idx;
518   MachineBasicBlock *MBB = LIS.getMBBFromIndex(Start);
519   SlotIndex Stop = LIS.getMBBEndIdx(MBB);
520   LocMap::iterator I = locInts.find(Start);
521
522   // Limit to VNI's live range.
523   bool ToEnd = true;
524   if (LR && VNI) {
525     LiveInterval::Segment *Segment = LR->getSegmentContaining(Start);
526     if (!Segment || Segment->valno != VNI) {
527       if (Kills)
528         Kills->push_back(Start);
529       return;
530     }
531     if (Segment->end < Stop) {
532       Stop = Segment->end;
533       ToEnd = false;
534     }
535   }
536
537   // There could already be a short def at Start.
538   if (I.valid() && I.start() <= Start) {
539     // Stop when meeting a different location or an already extended interval.
540     Start = Start.getNextSlot();
541     if (I.value() != LocNo || I.stop() != Start)
542       return;
543     // This is a one-slot placeholder. Just skip it.
544     ++I;
545   }
546
547   // Limited by the next def.
548   if (I.valid() && I.start() < Stop) {
549     Stop = I.start();
550     ToEnd = false;
551   }
552   // Limited by VNI's live range.
553   else if (!ToEnd && Kills)
554     Kills->push_back(Stop);
555
556   if (Start < Stop)
557     I.insert(Start, Stop, LocNo);
558 }
559
560 void
561 UserValue::addDefsFromCopies(LiveInterval *LI, unsigned LocNo,
562                       const SmallVectorImpl<SlotIndex> &Kills,
563                       SmallVectorImpl<std::pair<SlotIndex, unsigned> > &NewDefs,
564                       MachineRegisterInfo &MRI, LiveIntervals &LIS) {
565   if (Kills.empty())
566     return;
567   // Don't track copies from physregs, there are too many uses.
568   if (!TargetRegisterInfo::isVirtualRegister(LI->reg))
569     return;
570
571   // Collect all the (vreg, valno) pairs that are copies of LI.
572   SmallVector<std::pair<LiveInterval*, const VNInfo*>, 8> CopyValues;
573   for (MachineOperand &MO : MRI.use_nodbg_operands(LI->reg)) {
574     MachineInstr *MI = MO.getParent();
575     // Copies of the full value.
576     if (MO.getSubReg() || !MI->isCopy())
577       continue;
578     unsigned DstReg = MI->getOperand(0).getReg();
579
580     // Don't follow copies to physregs. These are usually setting up call
581     // arguments, and the argument registers are always call clobbered. We are
582     // better off in the source register which could be a callee-saved register,
583     // or it could be spilled.
584     if (!TargetRegisterInfo::isVirtualRegister(DstReg))
585       continue;
586
587     // Is LocNo extended to reach this copy? If not, another def may be blocking
588     // it, or we are looking at a wrong value of LI.
589     SlotIndex Idx = LIS.getInstructionIndex(*MI);
590     LocMap::iterator I = locInts.find(Idx.getRegSlot(true));
591     if (!I.valid() || I.value() != LocNo)
592       continue;
593
594     if (!LIS.hasInterval(DstReg))
595       continue;
596     LiveInterval *DstLI = &LIS.getInterval(DstReg);
597     const VNInfo *DstVNI = DstLI->getVNInfoAt(Idx.getRegSlot());
598     assert(DstVNI && DstVNI->def == Idx.getRegSlot() && "Bad copy value");
599     CopyValues.push_back(std::make_pair(DstLI, DstVNI));
600   }
601
602   if (CopyValues.empty())
603     return;
604
605   DEBUG(dbgs() << "Got " << CopyValues.size() << " copies of " << *LI << '\n');
606
607   // Try to add defs of the copied values for each kill point.
608   for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
609     SlotIndex Idx = Kills[i];
610     for (unsigned j = 0, e = CopyValues.size(); j != e; ++j) {
611       LiveInterval *DstLI = CopyValues[j].first;
612       const VNInfo *DstVNI = CopyValues[j].second;
613       if (DstLI->getVNInfoAt(Idx) != DstVNI)
614         continue;
615       // Check that there isn't already a def at Idx
616       LocMap::iterator I = locInts.find(Idx);
617       if (I.valid() && I.start() <= Idx)
618         continue;
619       DEBUG(dbgs() << "Kill at " << Idx << " covered by valno #"
620                    << DstVNI->id << " in " << *DstLI << '\n');
621       MachineInstr *CopyMI = LIS.getInstructionFromIndex(DstVNI->def);
622       assert(CopyMI && CopyMI->isCopy() && "Bad copy value");
623       unsigned LocNo = getLocationNo(CopyMI->getOperand(0));
624       I.insert(Idx, Idx.getNextSlot(), LocNo);
625       NewDefs.push_back(std::make_pair(Idx, LocNo));
626       break;
627     }
628   }
629 }
630
631 void
632 UserValue::computeIntervals(MachineRegisterInfo &MRI,
633                             const TargetRegisterInfo &TRI,
634                             LiveIntervals &LIS) {
635   SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
636
637   // Collect all defs to be extended (Skipping undefs).
638   for (LocMap::const_iterator I = locInts.begin(); I.valid(); ++I)
639     if (I.value() != ~0u)
640       Defs.push_back(std::make_pair(I.start(), I.value()));
641
642   // Extend all defs, and possibly add new ones along the way.
643   for (unsigned i = 0; i != Defs.size(); ++i) {
644     SlotIndex Idx = Defs[i].first;
645     unsigned LocNo = Defs[i].second;
646     const MachineOperand &Loc = locations[LocNo];
647
648     if (!Loc.isReg()) {
649       extendDef(Idx, LocNo, nullptr, nullptr, nullptr, LIS);
650       continue;
651     }
652
653     // Register locations are constrained to where the register value is live.
654     if (TargetRegisterInfo::isVirtualRegister(Loc.getReg())) {
655       LiveInterval *LI = nullptr;
656       const VNInfo *VNI = nullptr;
657       if (LIS.hasInterval(Loc.getReg())) {
658         LI = &LIS.getInterval(Loc.getReg());
659         VNI = LI->getVNInfoAt(Idx);
660       }
661       SmallVector<SlotIndex, 16> Kills;
662       extendDef(Idx, LocNo, LI, VNI, &Kills, LIS);
663       if (LI)
664         addDefsFromCopies(LI, LocNo, Kills, Defs, MRI, LIS);
665       continue;
666     }
667
668     // For physregs, use the live range of the first regunit as a guide.
669     unsigned Unit = *MCRegUnitIterator(Loc.getReg(), &TRI);
670     LiveRange *LR = &LIS.getRegUnit(Unit);
671     const VNInfo *VNI = LR->getVNInfoAt(Idx);
672     // Don't track copies from physregs, it is too expensive.
673     extendDef(Idx, LocNo, LR, VNI, nullptr, LIS);
674   }
675
676   // Finally, erase all the undefs.
677   for (LocMap::iterator I = locInts.begin(); I.valid();)
678     if (I.value() == ~0u)
679       I.erase();
680     else
681       ++I;
682 }
683
684 void LDVImpl::computeIntervals() {
685   for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
686     userValues[i]->computeIntervals(MF->getRegInfo(), *TRI, *LIS);
687     userValues[i]->mapVirtRegs(this);
688   }
689 }
690
691 bool LDVImpl::runOnMachineFunction(MachineFunction &mf) {
692   clear();
693   MF = &mf;
694   LIS = &pass.getAnalysis<LiveIntervals>();
695   TRI = mf.getSubtarget().getRegisterInfo();
696   DEBUG(dbgs() << "********** COMPUTING LIVE DEBUG VARIABLES: "
697                << mf.getName() << " **********\n");
698
699   bool Changed = collectDebugValues(mf);
700   computeIntervals();
701   DEBUG(print(dbgs()));
702   ModifiedMF = Changed;
703   return Changed;
704 }
705
706 static void removeDebugValues(MachineFunction &mf) {
707   for (MachineBasicBlock &MBB : mf) {
708     for (auto MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ) {
709       if (!MBBI->isDebugValue()) {
710         ++MBBI;
711         continue;
712       }
713       MBBI = MBB.erase(MBBI);
714     }
715   }
716 }
717
718 bool LiveDebugVariables::runOnMachineFunction(MachineFunction &mf) {
719   if (!EnableLDV)
720     return false;
721   if (!mf.getFunction()->getSubprogram()) {
722     removeDebugValues(mf);
723     return false;
724   }
725   if (!pImpl)
726     pImpl = new LDVImpl(this);
727   return static_cast<LDVImpl*>(pImpl)->runOnMachineFunction(mf);
728 }
729
730 void LiveDebugVariables::releaseMemory() {
731   if (pImpl)
732     static_cast<LDVImpl*>(pImpl)->clear();
733 }
734
735 LiveDebugVariables::~LiveDebugVariables() {
736   if (pImpl)
737     delete static_cast<LDVImpl*>(pImpl);
738 }
739
740 //===----------------------------------------------------------------------===//
741 //                           Live Range Splitting
742 //===----------------------------------------------------------------------===//
743
744 bool
745 UserValue::splitLocation(unsigned OldLocNo, ArrayRef<unsigned> NewRegs,
746                          LiveIntervals& LIS) {
747   DEBUG({
748     dbgs() << "Splitting Loc" << OldLocNo << '\t';
749     print(dbgs(), nullptr);
750   });
751   bool DidChange = false;
752   LocMap::iterator LocMapI;
753   LocMapI.setMap(locInts);
754   for (unsigned i = 0; i != NewRegs.size(); ++i) {
755     LiveInterval *LI = &LIS.getInterval(NewRegs[i]);
756     if (LI->empty())
757       continue;
758
759     // Don't allocate the new LocNo until it is needed.
760     unsigned NewLocNo = ~0u;
761
762     // Iterate over the overlaps between locInts and LI.
763     LocMapI.find(LI->beginIndex());
764     if (!LocMapI.valid())
765       continue;
766     LiveInterval::iterator LII = LI->advanceTo(LI->begin(), LocMapI.start());
767     LiveInterval::iterator LIE = LI->end();
768     while (LocMapI.valid() && LII != LIE) {
769       // At this point, we know that LocMapI.stop() > LII->start.
770       LII = LI->advanceTo(LII, LocMapI.start());
771       if (LII == LIE)
772         break;
773
774       // Now LII->end > LocMapI.start(). Do we have an overlap?
775       if (LocMapI.value() == OldLocNo && LII->start < LocMapI.stop()) {
776         // Overlapping correct location. Allocate NewLocNo now.
777         if (NewLocNo == ~0u) {
778           MachineOperand MO = MachineOperand::CreateReg(LI->reg, false);
779           MO.setSubReg(locations[OldLocNo].getSubReg());
780           NewLocNo = getLocationNo(MO);
781           DidChange = true;
782         }
783
784         SlotIndex LStart = LocMapI.start();
785         SlotIndex LStop  = LocMapI.stop();
786
787         // Trim LocMapI down to the LII overlap.
788         if (LStart < LII->start)
789           LocMapI.setStartUnchecked(LII->start);
790         if (LStop > LII->end)
791           LocMapI.setStopUnchecked(LII->end);
792
793         // Change the value in the overlap. This may trigger coalescing.
794         LocMapI.setValue(NewLocNo);
795
796         // Re-insert any removed OldLocNo ranges.
797         if (LStart < LocMapI.start()) {
798           LocMapI.insert(LStart, LocMapI.start(), OldLocNo);
799           ++LocMapI;
800           assert(LocMapI.valid() && "Unexpected coalescing");
801         }
802         if (LStop > LocMapI.stop()) {
803           ++LocMapI;
804           LocMapI.insert(LII->end, LStop, OldLocNo);
805           --LocMapI;
806         }
807       }
808
809       // Advance to the next overlap.
810       if (LII->end < LocMapI.stop()) {
811         if (++LII == LIE)
812           break;
813         LocMapI.advanceTo(LII->start);
814       } else {
815         ++LocMapI;
816         if (!LocMapI.valid())
817           break;
818         LII = LI->advanceTo(LII, LocMapI.start());
819       }
820     }
821   }
822
823   // Finally, remove any remaining OldLocNo intervals and OldLocNo itself.
824   locations.erase(locations.begin() + OldLocNo);
825   LocMapI.goToBegin();
826   while (LocMapI.valid()) {
827     unsigned v = LocMapI.value();
828     if (v == OldLocNo) {
829       DEBUG(dbgs() << "Erasing [" << LocMapI.start() << ';'
830                    << LocMapI.stop() << ")\n");
831       LocMapI.erase();
832     } else {
833       if (v > OldLocNo)
834         LocMapI.setValueUnchecked(v-1);
835       ++LocMapI;
836     }
837   }
838
839   DEBUG({dbgs() << "Split result: \t"; print(dbgs(), nullptr);});
840   return DidChange;
841 }
842
843 bool
844 UserValue::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs,
845                          LiveIntervals &LIS) {
846   bool DidChange = false;
847   // Split locations referring to OldReg. Iterate backwards so splitLocation can
848   // safely erase unused locations.
849   for (unsigned i = locations.size(); i ; --i) {
850     unsigned LocNo = i-1;
851     const MachineOperand *Loc = &locations[LocNo];
852     if (!Loc->isReg() || Loc->getReg() != OldReg)
853       continue;
854     DidChange |= splitLocation(LocNo, NewRegs, LIS);
855   }
856   return DidChange;
857 }
858
859 void LDVImpl::splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs) {
860   bool DidChange = false;
861   for (UserValue *UV = lookupVirtReg(OldReg); UV; UV = UV->getNext())
862     DidChange |= UV->splitRegister(OldReg, NewRegs, *LIS);
863
864   if (!DidChange)
865     return;
866
867   // Map all of the new virtual registers.
868   UserValue *UV = lookupVirtReg(OldReg);
869   for (unsigned i = 0; i != NewRegs.size(); ++i)
870     mapVirtReg(NewRegs[i], UV);
871 }
872
873 void LiveDebugVariables::
874 splitRegister(unsigned OldReg, ArrayRef<unsigned> NewRegs, LiveIntervals &LIS) {
875   if (pImpl)
876     static_cast<LDVImpl*>(pImpl)->splitRegister(OldReg, NewRegs);
877 }
878
879 void
880 UserValue::rewriteLocations(VirtRegMap &VRM, const TargetRegisterInfo &TRI) {
881   // Iterate over locations in reverse makes it easier to handle coalescing.
882   for (unsigned i = locations.size(); i ; --i) {
883     unsigned LocNo = i-1;
884     MachineOperand &Loc = locations[LocNo];
885     // Only virtual registers are rewritten.
886     if (!Loc.isReg() || !Loc.getReg() ||
887         !TargetRegisterInfo::isVirtualRegister(Loc.getReg()))
888       continue;
889     unsigned VirtReg = Loc.getReg();
890     if (VRM.isAssignedReg(VirtReg) &&
891         TargetRegisterInfo::isPhysicalRegister(VRM.getPhys(VirtReg))) {
892       // This can create a %noreg operand in rare cases when the sub-register
893       // index is no longer available. That means the user value is in a
894       // non-existent sub-register, and %noreg is exactly what we want.
895       Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
896     } else if (VRM.getStackSlot(VirtReg) != VirtRegMap::NO_STACK_SLOT) {
897       // FIXME: Translate SubIdx to a stackslot offset.
898       Loc = MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
899     } else {
900       Loc.setReg(0);
901       Loc.setSubReg(0);
902     }
903     coalesceLocation(LocNo);
904   }
905 }
906
907 /// findInsertLocation - Find an iterator for inserting a DBG_VALUE
908 /// instruction.
909 static MachineBasicBlock::iterator
910 findInsertLocation(MachineBasicBlock *MBB, SlotIndex Idx,
911                    LiveIntervals &LIS) {
912   SlotIndex Start = LIS.getMBBStartIdx(MBB);
913   Idx = Idx.getBaseIndex();
914
915   // Try to find an insert location by going backwards from Idx.
916   MachineInstr *MI;
917   while (!(MI = LIS.getInstructionFromIndex(Idx))) {
918     // We've reached the beginning of MBB.
919     if (Idx == Start) {
920       MachineBasicBlock::iterator I = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
921       return I;
922     }
923     Idx = Idx.getPrevIndex();
924   }
925
926   // Don't insert anything after the first terminator, though.
927   return MI->isTerminator() ? MBB->getFirstTerminator() :
928                               std::next(MachineBasicBlock::iterator(MI));
929 }
930
931 void UserValue::insertDebugValue(MachineBasicBlock *MBB, SlotIndex Idx,
932                                  unsigned LocNo,
933                                  LiveIntervals &LIS,
934                                  const TargetInstrInfo &TII) {
935   MachineBasicBlock::iterator I = findInsertLocation(MBB, Idx, LIS);
936   MachineOperand &Loc = locations[LocNo];
937   ++NumInsertedDebugValues;
938
939   assert(cast<DILocalVariable>(Variable)
940              ->isValidLocationForIntrinsic(getDebugLoc()) &&
941          "Expected inlined-at fields to agree");
942   if (Loc.isReg())
943     BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE),
944             IsIndirect, Loc.getReg(), offset, Variable, Expression);
945   else
946     BuildMI(*MBB, I, getDebugLoc(), TII.get(TargetOpcode::DBG_VALUE))
947         .addOperand(Loc)
948         .addImm(offset)
949         .addMetadata(Variable)
950         .addMetadata(Expression);
951 }
952
953 void UserValue::emitDebugValues(VirtRegMap *VRM, LiveIntervals &LIS,
954                                 const TargetInstrInfo &TII) {
955   MachineFunction::iterator MFEnd = VRM->getMachineFunction().end();
956
957   for (LocMap::const_iterator I = locInts.begin(); I.valid();) {
958     SlotIndex Start = I.start();
959     SlotIndex Stop = I.stop();
960     unsigned LocNo = I.value();
961     DEBUG(dbgs() << "\t[" << Start << ';' << Stop << "):" << LocNo);
962     MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start)->getIterator();
963     SlotIndex MBBEnd = LIS.getMBBEndIdx(&*MBB);
964
965     DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
966     insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
967     // This interval may span multiple basic blocks.
968     // Insert a DBG_VALUE into each one.
969     while(Stop > MBBEnd) {
970       // Move to the next block.
971       Start = MBBEnd;
972       if (++MBB == MFEnd)
973         break;
974       MBBEnd = LIS.getMBBEndIdx(&*MBB);
975       DEBUG(dbgs() << " BB#" << MBB->getNumber() << '-' << MBBEnd);
976       insertDebugValue(&*MBB, Start, LocNo, LIS, TII);
977     }
978     DEBUG(dbgs() << '\n');
979     if (MBB == MFEnd)
980       break;
981
982     ++I;
983   }
984 }
985
986 void LDVImpl::emitDebugValues(VirtRegMap *VRM) {
987   DEBUG(dbgs() << "********** EMITTING LIVE DEBUG VARIABLES **********\n");
988   if (!MF)
989     return;
990   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
991   for (unsigned i = 0, e = userValues.size(); i != e; ++i) {
992     DEBUG(userValues[i]->print(dbgs(), TRI));
993     userValues[i]->rewriteLocations(*VRM, *TRI);
994     userValues[i]->emitDebugValues(VRM, *LIS, *TII);
995   }
996   EmitDone = true;
997 }
998
999 void LiveDebugVariables::emitDebugValues(VirtRegMap *VRM) {
1000   if (pImpl)
1001     static_cast<LDVImpl*>(pImpl)->emitDebugValues(VRM);
1002 }
1003
1004 bool LiveDebugVariables::doInitialization(Module &M) {
1005   return Pass::doInitialization(M);
1006 }
1007
1008 #ifndef NDEBUG
1009 LLVM_DUMP_METHOD void LiveDebugVariables::dump() {
1010   if (pImpl)
1011     static_cast<LDVImpl*>(pImpl)->print(dbgs());
1012 }
1013 #endif