1//===- ExecutionDepsFix.cpp - Fix execution dependecy issues ----*- C++ -*-===//
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 contains the execution dependency fix pass.
11//
12// Some X86 SSE instructions like mov, and, or, xor are available in different
13// variants for different operand types. These variant instructions are
14// equivalent, but on Nehalem and newer cpus there is extra latency
15// transferring data between integer and floating point domains.  ARM cores
16// have similar issues when they are configured with both VFP and NEON
17// pipelines.
18//
19// This pass changes the variant instructions to minimize domain crossings.
20//
21//===----------------------------------------------------------------------===//
22
23#include "llvm/CodeGen/Passes.h"
24#include "llvm/ADT/PostOrderIterator.h"
25#include "llvm/ADT/iterator_range.h"
26#include "llvm/CodeGen/LivePhysRegs.h"
27#include "llvm/CodeGen/MachineFunctionPass.h"
28#include "llvm/CodeGen/MachineRegisterInfo.h"
29#include "llvm/Support/Allocator.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/raw_ostream.h"
32#include "llvm/Target/TargetInstrInfo.h"
33#include "llvm/Target/TargetSubtargetInfo.h"
34
35using namespace llvm;
36
37#define DEBUG_TYPE "execution-fix"
38
39/// A DomainValue is a bit like LiveIntervals' ValNo, but it also keeps track
40/// of execution domains.
41///
42/// An open DomainValue represents a set of instructions that can still switch
43/// execution domain. Multiple registers may refer to the same open
44/// DomainValue - they will eventually be collapsed to the same execution
45/// domain.
46///
47/// A collapsed DomainValue represents a single register that has been forced
48/// into one of more execution domains. There is a separate collapsed
49/// DomainValue for each register, but it may contain multiple execution
50/// domains. A register value is initially created in a single execution
51/// domain, but if we were forced to pay the penalty of a domain crossing, we
52/// keep track of the fact that the register is now available in multiple
53/// domains.
54namespace {
55struct DomainValue {
56  // Basic reference counting.
57  unsigned Refs;
58
59  // Bitmask of available domains. For an open DomainValue, it is the still
60  // possible domains for collapsing. For a collapsed DomainValue it is the
61  // domains where the register is available for free.
62  unsigned AvailableDomains;
63
64  // Pointer to the next DomainValue in a chain.  When two DomainValues are
65  // merged, Victim.Next is set to point to Victor, so old DomainValue
66  // references can be updated by following the chain.
67  DomainValue *Next;
68
69  // Twiddleable instructions using or defining these registers.
70  SmallVector<MachineInstr*, 8> Instrs;
71
72  // A collapsed DomainValue has no instructions to twiddle - it simply keeps
73  // track of the domains where the registers are already available.
74  bool isCollapsed() const { return Instrs.empty(); }
75
76  // Is domain available?
77  bool hasDomain(unsigned domain) const {
78    assert(domain <
79               static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
80           "undefined behavior");
81    return AvailableDomains & (1u << domain);
82  }
83
84  // Mark domain as available.
85  void addDomain(unsigned domain) {
86    AvailableDomains |= 1u << domain;
87  }
88
89  // Restrict to a single domain available.
90  void setSingleDomain(unsigned domain) {
91    AvailableDomains = 1u << domain;
92  }
93
94  // Return bitmask of domains that are available and in mask.
95  unsigned getCommonDomains(unsigned mask) const {
96    return AvailableDomains & mask;
97  }
98
99  // First domain available.
100  unsigned getFirstDomain() const {
101    return countTrailingZeros(AvailableDomains);
102  }
103
104  DomainValue() : Refs(0) { clear(); }
105
106  // Clear this DomainValue and point to next which has all its data.
107  void clear() {
108    AvailableDomains = 0;
109    Next = nullptr;
110    Instrs.clear();
111  }
112};
113}
114
115namespace {
116/// Information about a live register.
117struct LiveReg {
118  /// Value currently in this register, or NULL when no value is being tracked.
119  /// This counts as a DomainValue reference.
120  DomainValue *Value;
121
122  /// Instruction that defined this register, relative to the beginning of the
123  /// current basic block.  When a LiveReg is used to represent a live-out
124  /// register, this value is relative to the end of the basic block, so it
125  /// will be a negative number.
126  int Def;
127};
128} // anonymous namespace
129
130namespace {
131class ExeDepsFix : public MachineFunctionPass {
132  static char ID;
133  SpecificBumpPtrAllocator<DomainValue> Allocator;
134  SmallVector<DomainValue*,16> Avail;
135
136  const TargetRegisterClass *const RC;
137  MachineFunction *MF;
138  const TargetInstrInfo *TII;
139  const TargetRegisterInfo *TRI;
140  std::vector<SmallVector<int, 1>> AliasMap;
141  const unsigned NumRegs;
142  LiveReg *LiveRegs;
143  typedef DenseMap<MachineBasicBlock*, LiveReg*> LiveOutMap;
144  LiveOutMap LiveOuts;
145
146  /// List of undefined register reads in this block in forward order.
147  std::vector<std::pair<MachineInstr*, unsigned> > UndefReads;
148
149  /// Storage for register unit liveness.
150  LivePhysRegs LiveRegSet;
151
152  /// Current instruction number.
153  /// The first instruction in each basic block is 0.
154  int CurInstr;
155
156  /// True when the current block has a predecessor that hasn't been visited
157  /// yet.
158  bool SeenUnknownBackEdge;
159
160public:
161  ExeDepsFix(const TargetRegisterClass *rc)
162    : MachineFunctionPass(ID), RC(rc), NumRegs(RC->getNumRegs()) {}
163
164  void getAnalysisUsage(AnalysisUsage &AU) const override {
165    AU.setPreservesAll();
166    MachineFunctionPass::getAnalysisUsage(AU);
167  }
168
169  bool runOnMachineFunction(MachineFunction &MF) override;
170
171  MachineFunctionProperties getRequiredProperties() const override {
172    return MachineFunctionProperties().set(
173        MachineFunctionProperties::Property::AllVRegsAllocated);
174  }
175
176  const char *getPassName() const override {
177    return "Execution dependency fix";
178  }
179
180private:
181  iterator_range<SmallVectorImpl<int>::const_iterator>
182  regIndices(unsigned Reg) const;
183
184  // DomainValue allocation.
185  DomainValue *alloc(int domain = -1);
186  DomainValue *retain(DomainValue *DV) {
187    if (DV) ++DV->Refs;
188    return DV;
189  }
190  void release(DomainValue*);
191  DomainValue *resolve(DomainValue*&);
192
193  // LiveRegs manipulations.
194  void setLiveReg(int rx, DomainValue *DV);
195  void kill(int rx);
196  void force(int rx, unsigned domain);
197  void collapse(DomainValue *dv, unsigned domain);
198  bool merge(DomainValue *A, DomainValue *B);
199
200  void enterBasicBlock(MachineBasicBlock*);
201  void leaveBasicBlock(MachineBasicBlock*);
202  void visitInstr(MachineInstr*);
203  void processDefs(MachineInstr*, bool Kill);
204  void visitSoftInstr(MachineInstr*, unsigned mask);
205  void visitHardInstr(MachineInstr*, unsigned domain);
206  bool shouldBreakDependence(MachineInstr*, unsigned OpIdx, unsigned Pref);
207  void processUndefReads(MachineBasicBlock*);
208};
209}
210
211char ExeDepsFix::ID = 0;
212
213/// Translate TRI register number to a list of indices into our smaller tables
214/// of interesting registers.
215iterator_range<SmallVectorImpl<int>::const_iterator>
216ExeDepsFix::regIndices(unsigned Reg) const {
217  assert(Reg < AliasMap.size() && "Invalid register");
218  const auto &Entry = AliasMap[Reg];
219  return make_range(Entry.begin(), Entry.end());
220}
221
222DomainValue *ExeDepsFix::alloc(int domain) {
223  DomainValue *dv = Avail.empty() ?
224                      new(Allocator.Allocate()) DomainValue :
225                      Avail.pop_back_val();
226  if (domain >= 0)
227    dv->addDomain(domain);
228  assert(dv->Refs == 0 && "Reference count wasn't cleared");
229  assert(!dv->Next && "Chained DomainValue shouldn't have been recycled");
230  return dv;
231}
232
233/// Release a reference to DV.  When the last reference is released,
234/// collapse if needed.
235void ExeDepsFix::release(DomainValue *DV) {
236  while (DV) {
237    assert(DV->Refs && "Bad DomainValue");
238    if (--DV->Refs)
239      return;
240
241    // There are no more DV references. Collapse any contained instructions.
242    if (DV->AvailableDomains && !DV->isCollapsed())
243      collapse(DV, DV->getFirstDomain());
244
245    DomainValue *Next = DV->Next;
246    DV->clear();
247    Avail.push_back(DV);
248    // Also release the next DomainValue in the chain.
249    DV = Next;
250  }
251}
252
253/// Follow the chain of dead DomainValues until a live DomainValue is reached.
254/// Update the referenced pointer when necessary.
255DomainValue *ExeDepsFix::resolve(DomainValue *&DVRef) {
256  DomainValue *DV = DVRef;
257  if (!DV || !DV->Next)
258    return DV;
259
260  // DV has a chain. Find the end.
261  do DV = DV->Next;
262  while (DV->Next);
263
264  // Update DVRef to point to DV.
265  retain(DV);
266  release(DVRef);
267  DVRef = DV;
268  return DV;
269}
270
271/// Set LiveRegs[rx] = dv, updating reference counts.
272void ExeDepsFix::setLiveReg(int rx, DomainValue *dv) {
273  assert(unsigned(rx) < NumRegs && "Invalid index");
274  assert(LiveRegs && "Must enter basic block first.");
275
276  if (LiveRegs[rx].Value == dv)
277    return;
278  if (LiveRegs[rx].Value)
279    release(LiveRegs[rx].Value);
280  LiveRegs[rx].Value = retain(dv);
281}
282
283// Kill register rx, recycle or collapse any DomainValue.
284void ExeDepsFix::kill(int rx) {
285  assert(unsigned(rx) < NumRegs && "Invalid index");
286  assert(LiveRegs && "Must enter basic block first.");
287  if (!LiveRegs[rx].Value)
288    return;
289
290  release(LiveRegs[rx].Value);
291  LiveRegs[rx].Value = nullptr;
292}
293
294/// Force register rx into domain.
295void ExeDepsFix::force(int rx, unsigned domain) {
296  assert(unsigned(rx) < NumRegs && "Invalid index");
297  assert(LiveRegs && "Must enter basic block first.");
298  if (DomainValue *dv = LiveRegs[rx].Value) {
299    if (dv->isCollapsed())
300      dv->addDomain(domain);
301    else if (dv->hasDomain(domain))
302      collapse(dv, domain);
303    else {
304      // This is an incompatible open DomainValue. Collapse it to whatever and
305      // force the new value into domain. This costs a domain crossing.
306      collapse(dv, dv->getFirstDomain());
307      assert(LiveRegs[rx].Value && "Not live after collapse?");
308      LiveRegs[rx].Value->addDomain(domain);
309    }
310  } else {
311    // Set up basic collapsed DomainValue.
312    setLiveReg(rx, alloc(domain));
313  }
314}
315
316/// Collapse open DomainValue into given domain. If there are multiple
317/// registers using dv, they each get a unique collapsed DomainValue.
318void ExeDepsFix::collapse(DomainValue *dv, unsigned domain) {
319  assert(dv->hasDomain(domain) && "Cannot collapse");
320
321  // Collapse all the instructions.
322  while (!dv->Instrs.empty())
323    TII->setExecutionDomain(*dv->Instrs.pop_back_val(), domain);
324  dv->setSingleDomain(domain);
325
326  // If there are multiple users, give them new, unique DomainValues.
327  if (LiveRegs && dv->Refs > 1)
328    for (unsigned rx = 0; rx != NumRegs; ++rx)
329      if (LiveRegs[rx].Value == dv)
330        setLiveReg(rx, alloc(domain));
331}
332
333/// All instructions and registers in B are moved to A, and B is released.
334bool ExeDepsFix::merge(DomainValue *A, DomainValue *B) {
335  assert(!A->isCollapsed() && "Cannot merge into collapsed");
336  assert(!B->isCollapsed() && "Cannot merge from collapsed");
337  if (A == B)
338    return true;
339  // Restrict to the domains that A and B have in common.
340  unsigned common = A->getCommonDomains(B->AvailableDomains);
341  if (!common)
342    return false;
343  A->AvailableDomains = common;
344  A->Instrs.append(B->Instrs.begin(), B->Instrs.end());
345
346  // Clear the old DomainValue so we won't try to swizzle instructions twice.
347  B->clear();
348  // All uses of B are referred to A.
349  B->Next = retain(A);
350
351  for (unsigned rx = 0; rx != NumRegs; ++rx) {
352    assert(LiveRegs && "no space allocated for live registers");
353    if (LiveRegs[rx].Value == B)
354      setLiveReg(rx, A);
355  }
356  return true;
357}
358
359/// Set up LiveRegs by merging predecessor live-out values.
360void ExeDepsFix::enterBasicBlock(MachineBasicBlock *MBB) {
361  // Detect back-edges from predecessors we haven't processed yet.
362  SeenUnknownBackEdge = false;
363
364  // Reset instruction counter in each basic block.
365  CurInstr = 0;
366
367  // Set up UndefReads to track undefined register reads.
368  UndefReads.clear();
369  LiveRegSet.clear();
370
371  // Set up LiveRegs to represent registers entering MBB.
372  if (!LiveRegs)
373    LiveRegs = new LiveReg[NumRegs];
374
375  // Default values are 'nothing happened a long time ago'.
376  for (unsigned rx = 0; rx != NumRegs; ++rx) {
377    LiveRegs[rx].Value = nullptr;
378    LiveRegs[rx].Def = -(1 << 20);
379  }
380
381  // This is the entry block.
382  if (MBB->pred_empty()) {
383    for (const auto &LI : MBB->liveins()) {
384      for (int rx : regIndices(LI.PhysReg)) {
385        // Treat function live-ins as if they were defined just before the first
386        // instruction.  Usually, function arguments are set up immediately
387        // before the call.
388        LiveRegs[rx].Def = -1;
389      }
390    }
391    DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": entry\n");
392    return;
393  }
394
395  // Try to coalesce live-out registers from predecessors.
396  for (MachineBasicBlock::const_pred_iterator pi = MBB->pred_begin(),
397       pe = MBB->pred_end(); pi != pe; ++pi) {
398    LiveOutMap::const_iterator fi = LiveOuts.find(*pi);
399    if (fi == LiveOuts.end()) {
400      SeenUnknownBackEdge = true;
401      continue;
402    }
403    assert(fi->second && "Can't have NULL entries");
404
405    for (unsigned rx = 0; rx != NumRegs; ++rx) {
406      // Use the most recent predecessor def for each register.
407      LiveRegs[rx].Def = std::max(LiveRegs[rx].Def, fi->second[rx].Def);
408
409      DomainValue *pdv = resolve(fi->second[rx].Value);
410      if (!pdv)
411        continue;
412      if (!LiveRegs[rx].Value) {
413        setLiveReg(rx, pdv);
414        continue;
415      }
416
417      // We have a live DomainValue from more than one predecessor.
418      if (LiveRegs[rx].Value->isCollapsed()) {
419        // We are already collapsed, but predecessor is not. Force it.
420        unsigned Domain = LiveRegs[rx].Value->getFirstDomain();
421        if (!pdv->isCollapsed() && pdv->hasDomain(Domain))
422          collapse(pdv, Domain);
423        continue;
424      }
425
426      // Currently open, merge in predecessor.
427      if (!pdv->isCollapsed())
428        merge(LiveRegs[rx].Value, pdv);
429      else
430        force(rx, pdv->getFirstDomain());
431    }
432  }
433  DEBUG(dbgs() << "BB#" << MBB->getNumber()
434        << (SeenUnknownBackEdge ? ": incomplete\n" : ": all preds known\n"));
435}
436
437void ExeDepsFix::leaveBasicBlock(MachineBasicBlock *MBB) {
438  assert(LiveRegs && "Must enter basic block first.");
439  // Save live registers at end of MBB - used by enterBasicBlock().
440  // Also use LiveOuts as a visited set to detect back-edges.
441  bool First = LiveOuts.insert(std::make_pair(MBB, LiveRegs)).second;
442
443  if (First) {
444    // LiveRegs was inserted in LiveOuts.  Adjust all defs to be relative to
445    // the end of this block instead of the beginning.
446    for (unsigned i = 0, e = NumRegs; i != e; ++i)
447      LiveRegs[i].Def -= CurInstr;
448  } else {
449    // Insertion failed, this must be the second pass.
450    // Release all the DomainValues instead of keeping them.
451    for (unsigned i = 0, e = NumRegs; i != e; ++i)
452      release(LiveRegs[i].Value);
453    delete[] LiveRegs;
454  }
455  LiveRegs = nullptr;
456}
457
458void ExeDepsFix::visitInstr(MachineInstr *MI) {
459  if (MI->isDebugValue())
460    return;
461
462  // Update instructions with explicit execution domains.
463  std::pair<uint16_t, uint16_t> DomP = TII->getExecutionDomain(*MI);
464  if (DomP.first) {
465    if (DomP.second)
466      visitSoftInstr(MI, DomP.second);
467    else
468      visitHardInstr(MI, DomP.first);
469  }
470
471  // Process defs to track register ages, and kill values clobbered by generic
472  // instructions.
473  processDefs(MI, !DomP.first);
474}
475
476/// \brief Return true to if it makes sense to break dependence on a partial def
477/// or undef use.
478bool ExeDepsFix::shouldBreakDependence(MachineInstr *MI, unsigned OpIdx,
479                                       unsigned Pref) {
480  unsigned reg = MI->getOperand(OpIdx).getReg();
481  for (int rx : regIndices(reg)) {
482    unsigned Clearance = CurInstr - LiveRegs[rx].Def;
483    DEBUG(dbgs() << "Clearance: " << Clearance << ", want " << Pref);
484
485    if (Pref > Clearance) {
486      DEBUG(dbgs() << ": Break dependency.\n");
487      continue;
488    }
489    // The current clearance seems OK, but we may be ignoring a def from a
490    // back-edge.
491    if (!SeenUnknownBackEdge || Pref <= unsigned(CurInstr)) {
492      DEBUG(dbgs() << ": OK .\n");
493      return false;
494    }
495    // A def from an unprocessed back-edge may make us break this dependency.
496    DEBUG(dbgs() << ": Wait for back-edge to resolve.\n");
497    return false;
498  }
499  return true;
500}
501
502// Update def-ages for registers defined by MI.
503// If Kill is set, also kill off DomainValues clobbered by the defs.
504//
505// Also break dependencies on partial defs and undef uses.
506void ExeDepsFix::processDefs(MachineInstr *MI, bool Kill) {
507  assert(!MI->isDebugValue() && "Won't process debug values");
508
509  // Break dependence on undef uses. Do this before updating LiveRegs below.
510  unsigned OpNum;
511  unsigned Pref = TII->getUndefRegClearance(*MI, OpNum, TRI);
512  if (Pref) {
513    if (shouldBreakDependence(MI, OpNum, Pref))
514      UndefReads.push_back(std::make_pair(MI, OpNum));
515  }
516  const MCInstrDesc &MCID = MI->getDesc();
517  for (unsigned i = 0,
518         e = MI->isVariadic() ? MI->getNumOperands() : MCID.getNumDefs();
519         i != e; ++i) {
520    MachineOperand &MO = MI->getOperand(i);
521    if (!MO.isReg())
522      continue;
523    if (MO.isImplicit())
524      break;
525    if (MO.isUse())
526      continue;
527    for (int rx : regIndices(MO.getReg())) {
528      // This instruction explicitly defines rx.
529      DEBUG(dbgs() << TRI->getName(RC->getRegister(rx)) << ":\t" << CurInstr
530                   << '\t' << *MI);
531
532      // Check clearance before partial register updates.
533      // Call breakDependence before setting LiveRegs[rx].Def.
534      unsigned Pref = TII->getPartialRegUpdateClearance(*MI, i, TRI);
535      if (Pref && shouldBreakDependence(MI, i, Pref))
536        TII->breakPartialRegDependency(*MI, i, TRI);
537
538      // How many instructions since rx was last written?
539      LiveRegs[rx].Def = CurInstr;
540
541      // Kill off domains redefined by generic instructions.
542      if (Kill)
543        kill(rx);
544    }
545  }
546  ++CurInstr;
547}
548
549/// \break Break false dependencies on undefined register reads.
550///
551/// Walk the block backward computing precise liveness. This is expensive, so we
552/// only do it on demand. Note that the occurrence of undefined register reads
553/// that should be broken is very rare, but when they occur we may have many in
554/// a single block.
555void ExeDepsFix::processUndefReads(MachineBasicBlock *MBB) {
556  if (UndefReads.empty())
557    return;
558
559  // Collect this block's live out register units.
560  LiveRegSet.init(TRI);
561  // We do not need to care about pristine registers as they are just preserved
562  // but not actually used in the function.
563  LiveRegSet.addLiveOutsNoPristines(*MBB);
564
565  MachineInstr *UndefMI = UndefReads.back().first;
566  unsigned OpIdx = UndefReads.back().second;
567
568  for (MachineInstr &I : make_range(MBB->rbegin(), MBB->rend())) {
569    // Update liveness, including the current instruction's defs.
570    LiveRegSet.stepBackward(I);
571
572    if (UndefMI == &I) {
573      if (!LiveRegSet.contains(UndefMI->getOperand(OpIdx).getReg()))
574        TII->breakPartialRegDependency(*UndefMI, OpIdx, TRI);
575
576      UndefReads.pop_back();
577      if (UndefReads.empty())
578        return;
579
580      UndefMI = UndefReads.back().first;
581      OpIdx = UndefReads.back().second;
582    }
583  }
584}
585
586// A hard instruction only works in one domain. All input registers will be
587// forced into that domain.
588void ExeDepsFix::visitHardInstr(MachineInstr *mi, unsigned domain) {
589  // Collapse all uses.
590  for (unsigned i = mi->getDesc().getNumDefs(),
591                e = mi->getDesc().getNumOperands(); i != e; ++i) {
592    MachineOperand &mo = mi->getOperand(i);
593    if (!mo.isReg()) continue;
594    for (int rx : regIndices(mo.getReg())) {
595      force(rx, domain);
596    }
597  }
598
599  // Kill all defs and force them.
600  for (unsigned i = 0, e = mi->getDesc().getNumDefs(); i != e; ++i) {
601    MachineOperand &mo = mi->getOperand(i);
602    if (!mo.isReg()) continue;
603    for (int rx : regIndices(mo.getReg())) {
604      kill(rx);
605      force(rx, domain);
606    }
607  }
608}
609
610// A soft instruction can be changed to work in other domains given by mask.
611void ExeDepsFix::visitSoftInstr(MachineInstr *mi, unsigned mask) {
612  // Bitmask of available domains for this instruction after taking collapsed
613  // operands into account.
614  unsigned available = mask;
615
616  // Scan the explicit use operands for incoming domains.
617  SmallVector<int, 4> used;
618  if (LiveRegs)
619    for (unsigned i = mi->getDesc().getNumDefs(),
620                  e = mi->getDesc().getNumOperands(); i != e; ++i) {
621      MachineOperand &mo = mi->getOperand(i);
622      if (!mo.isReg()) continue;
623      for (int rx : regIndices(mo.getReg())) {
624        DomainValue *dv = LiveRegs[rx].Value;
625        if (dv == nullptr)
626          continue;
627        // Bitmask of domains that dv and available have in common.
628        unsigned common = dv->getCommonDomains(available);
629        // Is it possible to use this collapsed register for free?
630        if (dv->isCollapsed()) {
631          // Restrict available domains to the ones in common with the operand.
632          // If there are no common domains, we must pay the cross-domain
633          // penalty for this operand.
634          if (common) available = common;
635        } else if (common)
636          // Open DomainValue is compatible, save it for merging.
637          used.push_back(rx);
638        else
639          // Open DomainValue is not compatible with instruction. It is useless
640          // now.
641          kill(rx);
642      }
643    }
644
645  // If the collapsed operands force a single domain, propagate the collapse.
646  if (isPowerOf2_32(available)) {
647    unsigned domain = countTrailingZeros(available);
648    TII->setExecutionDomain(*mi, domain);
649    visitHardInstr(mi, domain);
650    return;
651  }
652
653  // Kill off any remaining uses that don't match available, and build a list of
654  // incoming DomainValues that we want to merge.
655  SmallVector<LiveReg, 4> Regs;
656  for (SmallVectorImpl<int>::iterator i=used.begin(), e=used.end(); i!=e; ++i) {
657    int rx = *i;
658    assert(LiveRegs && "no space allocated for live registers");
659    const LiveReg &LR = LiveRegs[rx];
660    // This useless DomainValue could have been missed above.
661    if (!LR.Value->getCommonDomains(available)) {
662      kill(rx);
663      continue;
664    }
665    // Sorted insertion.
666    bool Inserted = false;
667    for (SmallVectorImpl<LiveReg>::iterator i = Regs.begin(), e = Regs.end();
668           i != e && !Inserted; ++i) {
669      if (LR.Def < i->Def) {
670        Inserted = true;
671        Regs.insert(i, LR);
672      }
673    }
674    if (!Inserted)
675      Regs.push_back(LR);
676  }
677
678  // doms are now sorted in order of appearance. Try to merge them all, giving
679  // priority to the latest ones.
680  DomainValue *dv = nullptr;
681  while (!Regs.empty()) {
682    if (!dv) {
683      dv = Regs.pop_back_val().Value;
684      // Force the first dv to match the current instruction.
685      dv->AvailableDomains = dv->getCommonDomains(available);
686      assert(dv->AvailableDomains && "Domain should have been filtered");
687      continue;
688    }
689
690    DomainValue *Latest = Regs.pop_back_val().Value;
691    // Skip already merged values.
692    if (Latest == dv || Latest->Next)
693      continue;
694    if (merge(dv, Latest))
695      continue;
696
697    // If latest didn't merge, it is useless now. Kill all registers using it.
698    for (int i : used) {
699      assert(LiveRegs && "no space allocated for live registers");
700      if (LiveRegs[i].Value == Latest)
701        kill(i);
702    }
703  }
704
705  // dv is the DomainValue we are going to use for this instruction.
706  if (!dv) {
707    dv = alloc();
708    dv->AvailableDomains = available;
709  }
710  dv->Instrs.push_back(mi);
711
712  // Finally set all defs and non-collapsed uses to dv. We must iterate through
713  // all the operators, including imp-def ones.
714  for (MachineInstr::mop_iterator ii = mi->operands_begin(),
715                                  ee = mi->operands_end();
716                                  ii != ee; ++ii) {
717    MachineOperand &mo = *ii;
718    if (!mo.isReg()) continue;
719    for (int rx : regIndices(mo.getReg())) {
720      if (!LiveRegs[rx].Value || (mo.isDef() && LiveRegs[rx].Value != dv)) {
721        kill(rx);
722        setLiveReg(rx, dv);
723      }
724    }
725  }
726}
727
728bool ExeDepsFix::runOnMachineFunction(MachineFunction &mf) {
729  if (skipFunction(*mf.getFunction()))
730    return false;
731  MF = &mf;
732  TII = MF->getSubtarget().getInstrInfo();
733  TRI = MF->getSubtarget().getRegisterInfo();
734  LiveRegs = nullptr;
735  assert(NumRegs == RC->getNumRegs() && "Bad regclass");
736
737  DEBUG(dbgs() << "********** FIX EXECUTION DEPENDENCIES: "
738               << TRI->getRegClassName(RC) << " **********\n");
739
740  // If no relevant registers are used in the function, we can skip it
741  // completely.
742  bool anyregs = false;
743  const MachineRegisterInfo &MRI = mf.getRegInfo();
744  for (unsigned Reg : *RC) {
745    if (MRI.isPhysRegUsed(Reg)) {
746      anyregs = true;
747      break;
748    }
749  }
750  if (!anyregs) return false;
751
752  // Initialize the AliasMap on the first use.
753  if (AliasMap.empty()) {
754    // Given a PhysReg, AliasMap[PhysReg] returns a list of indices into RC and
755    // therefore the LiveRegs array.
756    AliasMap.resize(TRI->getNumRegs());
757    for (unsigned i = 0, e = RC->getNumRegs(); i != e; ++i)
758      for (MCRegAliasIterator AI(RC->getRegister(i), TRI, true);
759           AI.isValid(); ++AI)
760        AliasMap[*AI].push_back(i);
761  }
762
763  MachineBasicBlock *Entry = &*MF->begin();
764  ReversePostOrderTraversal<MachineBasicBlock*> RPOT(Entry);
765  SmallVector<MachineBasicBlock*, 16> Loops;
766  for (ReversePostOrderTraversal<MachineBasicBlock*>::rpo_iterator
767         MBBI = RPOT.begin(), MBBE = RPOT.end(); MBBI != MBBE; ++MBBI) {
768    MachineBasicBlock *MBB = *MBBI;
769    enterBasicBlock(MBB);
770    if (SeenUnknownBackEdge)
771      Loops.push_back(MBB);
772    for (MachineInstr &MI : *MBB)
773      visitInstr(&MI);
774    processUndefReads(MBB);
775    leaveBasicBlock(MBB);
776  }
777
778  // Visit all the loop blocks again in order to merge DomainValues from
779  // back-edges.
780  for (MachineBasicBlock *MBB : Loops) {
781    enterBasicBlock(MBB);
782    for (MachineInstr &MI : *MBB)
783      if (!MI.isDebugValue())
784        processDefs(&MI, false);
785    processUndefReads(MBB);
786    leaveBasicBlock(MBB);
787  }
788
789  // Clear the LiveOuts vectors and collapse any remaining DomainValues.
790  for (ReversePostOrderTraversal<MachineBasicBlock*>::rpo_iterator
791         MBBI = RPOT.begin(), MBBE = RPOT.end(); MBBI != MBBE; ++MBBI) {
792    LiveOutMap::const_iterator FI = LiveOuts.find(*MBBI);
793    if (FI == LiveOuts.end() || !FI->second)
794      continue;
795    for (unsigned i = 0, e = NumRegs; i != e; ++i)
796      if (FI->second[i].Value)
797        release(FI->second[i].Value);
798    delete[] FI->second;
799  }
800  LiveOuts.clear();
801  UndefReads.clear();
802  Avail.clear();
803  Allocator.DestroyAll();
804
805  return false;
806}
807
808FunctionPass *
809llvm::createExecutionDependencyFixPass(const TargetRegisterClass *RC) {
810  return new ExeDepsFix(RC);
811}
812