MachineBasicBlock.cpp revision 7707a0df5b00c8326a581205639d6b2871f182e9
1//===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- 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// Collect the sequence of machine instructions for a basic block.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/MachineBasicBlock.h"
15#include "llvm/BasicBlock.h"
16#include "llvm/CodeGen/MachineFunction.h"
17#include "llvm/Target/TargetRegisterInfo.h"
18#include "llvm/Target/TargetData.h"
19#include "llvm/Target/TargetInstrDesc.h"
20#include "llvm/Target/TargetInstrInfo.h"
21#include "llvm/Target/TargetMachine.h"
22#include "llvm/Support/LeakDetector.h"
23#include "llvm/Support/raw_ostream.h"
24#include "llvm/Assembly/Writer.h"
25#include <algorithm>
26using namespace llvm;
27
28MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
29  : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
30    AddressTaken(false) {
31  Insts.Parent = this;
32}
33
34MachineBasicBlock::~MachineBasicBlock() {
35  LeakDetector::removeGarbageObject(this);
36}
37
38raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
39  MBB.print(OS);
40  return OS;
41}
42
43/// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the
44/// parent pointer of the MBB, the MBB numbering, and any instructions in the
45/// MBB to be on the right operand list for registers.
46///
47/// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
48/// gets the next available unique MBB number. If it is removed from a
49/// MachineFunction, it goes back to being #-1.
50void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
51  MachineFunction &MF = *N->getParent();
52  N->Number = MF.addToMBBNumbering(N);
53
54  // Make sure the instructions have their operands in the reginfo lists.
55  MachineRegisterInfo &RegInfo = MF.getRegInfo();
56  for (MachineBasicBlock::iterator I = N->begin(), E = N->end(); I != E; ++I)
57    I->AddRegOperandsToUseLists(RegInfo);
58
59  LeakDetector::removeGarbageObject(N);
60}
61
62void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
63  N->getParent()->removeFromMBBNumbering(N->Number);
64  N->Number = -1;
65  LeakDetector::addGarbageObject(N);
66}
67
68
69/// addNodeToList (MI) - When we add an instruction to a basic block
70/// list, we update its parent pointer and add its operands from reg use/def
71/// lists if appropriate.
72void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
73  assert(N->getParent() == 0 && "machine instruction already in a basic block");
74  N->setParent(Parent);
75
76  // Add the instruction's register operands to their corresponding
77  // use/def lists.
78  MachineFunction *MF = Parent->getParent();
79  N->AddRegOperandsToUseLists(MF->getRegInfo());
80
81  LeakDetector::removeGarbageObject(N);
82}
83
84/// removeNodeFromList (MI) - When we remove an instruction from a basic block
85/// list, we update its parent pointer and remove its operands from reg use/def
86/// lists if appropriate.
87void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
88  assert(N->getParent() != 0 && "machine instruction not in a basic block");
89
90  // Remove from the use/def lists.
91  N->RemoveRegOperandsFromUseLists();
92
93  N->setParent(0);
94
95  LeakDetector::addGarbageObject(N);
96}
97
98/// transferNodesFromList (MI) - When moving a range of instructions from one
99/// MBB list to another, we need to update the parent pointers and the use/def
100/// lists.
101void ilist_traits<MachineInstr>::
102transferNodesFromList(ilist_traits<MachineInstr> &fromList,
103                      MachineBasicBlock::iterator first,
104                      MachineBasicBlock::iterator last) {
105  assert(Parent->getParent() == fromList.Parent->getParent() &&
106        "MachineInstr parent mismatch!");
107
108  // Splice within the same MBB -> no change.
109  if (Parent == fromList.Parent) return;
110
111  // If splicing between two blocks within the same function, just update the
112  // parent pointers.
113  for (; first != last; ++first)
114    first->setParent(Parent);
115}
116
117void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
118  assert(!MI->getParent() && "MI is still in a block!");
119  Parent->getParent()->DeleteMachineInstr(MI);
120}
121
122MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
123  iterator I = end();
124  while (I != begin() && (--I)->getDesc().isTerminator())
125    ; /*noop */
126  if (I != end() && !I->getDesc().isTerminator()) ++I;
127  return I;
128}
129
130/// isOnlyReachableViaFallthough - Return true if this basic block has
131/// exactly one predecessor and the control transfer mechanism between
132/// the predecessor and this block is a fall-through.
133bool MachineBasicBlock::isOnlyReachableByFallthrough() const {
134  // If this is a landing pad, it isn't a fall through.  If it has no preds,
135  // then nothing falls through to it.
136  if (isLandingPad() || pred_empty())
137    return false;
138
139  // If there isn't exactly one predecessor, it can't be a fall through.
140  const_pred_iterator PI = pred_begin(), PI2 = PI;
141  ++PI2;
142  if (PI2 != pred_end())
143    return false;
144
145  // The predecessor has to be immediately before this block.
146  const MachineBasicBlock *Pred = *PI;
147
148  if (!Pred->isLayoutSuccessor(this))
149    return false;
150
151  // If the block is completely empty, then it definitely does fall through.
152  if (Pred->empty())
153    return true;
154
155  // Otherwise, check the last instruction.
156  const MachineInstr &LastInst = Pred->back();
157  return !LastInst.getDesc().isBarrier();
158}
159
160void MachineBasicBlock::dump() const {
161  print(errs());
162}
163
164static inline void OutputReg(raw_ostream &os, unsigned RegNo,
165                             const TargetRegisterInfo *TRI = 0) {
166  if (RegNo != 0 && TargetRegisterInfo::isPhysicalRegister(RegNo)) {
167    if (TRI)
168      os << " %" << TRI->get(RegNo).Name;
169    else
170      os << " %physreg" << RegNo;
171  } else
172    os << " %reg" << RegNo;
173}
174
175void MachineBasicBlock::print(raw_ostream &OS) const {
176  const MachineFunction *MF = getParent();
177  if (!MF) {
178    OS << "Can't print out MachineBasicBlock because parent MachineFunction"
179       << " is null\n";
180    return;
181  }
182
183  if (Alignment) { OS << "Alignment " << Alignment << "\n"; }
184
185  OS << "BB#" << getNumber() << ": ";
186
187  const char *Comma = "";
188  if (const BasicBlock *LBB = getBasicBlock()) {
189    OS << Comma << "derived from LLVM BB ";
190    WriteAsOperand(OS, LBB, /*PrintType=*/false);
191    Comma = ", ";
192  }
193  if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
194  if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
195  OS << '\n';
196
197  const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
198  if (!livein_empty()) {
199    OS << "    Live Ins:";
200    for (const_livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
201      OutputReg(OS, *I, TRI);
202    OS << '\n';
203  }
204  // Print the preds of this block according to the CFG.
205  if (!pred_empty()) {
206    OS << "    Predecessors according to CFG:";
207    for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
208      OS << " BB#" << (*PI)->getNumber();
209    OS << '\n';
210  }
211
212  for (const_iterator I = begin(); I != end(); ++I) {
213    OS << '\t';
214    I->print(OS, &getParent()->getTarget());
215  }
216
217  // Print the successors of this block according to the CFG.
218  if (!succ_empty()) {
219    OS << "    Successors according to CFG:";
220    for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI)
221      OS << " BB#" << (*SI)->getNumber();
222    OS << '\n';
223  }
224}
225
226void MachineBasicBlock::removeLiveIn(unsigned Reg) {
227  livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
228  assert(I != livein_end() && "Not a live in!");
229  LiveIns.erase(I);
230}
231
232bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
233  const_livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
234  return I != livein_end();
235}
236
237void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
238  getParent()->splice(NewAfter, this);
239}
240
241void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
242  MachineFunction::iterator BBI = NewBefore;
243  getParent()->splice(++BBI, this);
244}
245
246void MachineBasicBlock::updateTerminator() {
247  const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
248  // A block with no successors has no concerns with fall-through edges.
249  if (this->succ_empty()) return;
250
251  MachineBasicBlock *TBB = 0, *FBB = 0;
252  SmallVector<MachineOperand, 4> Cond;
253  bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
254  (void) B;
255  assert(!B && "UpdateTerminators requires analyzable predecessors!");
256  if (Cond.empty()) {
257    if (TBB) {
258      // The block has an unconditional branch. If its successor is now
259      // its layout successor, delete the branch.
260      if (isLayoutSuccessor(TBB))
261        TII->RemoveBranch(*this);
262    } else {
263      // The block has an unconditional fallthrough. If its successor is not
264      // its layout successor, insert a branch.
265      TBB = *succ_begin();
266      if (!isLayoutSuccessor(TBB))
267        TII->InsertBranch(*this, TBB, 0, Cond);
268    }
269  } else {
270    if (FBB) {
271      // The block has a non-fallthrough conditional branch. If one of its
272      // successors is its layout successor, rewrite it to a fallthrough
273      // conditional branch.
274      if (isLayoutSuccessor(TBB)) {
275        TII->RemoveBranch(*this);
276        TII->ReverseBranchCondition(Cond);
277        TII->InsertBranch(*this, FBB, 0, Cond);
278      } else if (isLayoutSuccessor(FBB)) {
279        TII->RemoveBranch(*this);
280        TII->InsertBranch(*this, TBB, 0, Cond);
281      }
282    } else {
283      // The block has a fallthrough conditional branch.
284      MachineBasicBlock *MBBA = *succ_begin();
285      MachineBasicBlock *MBBB = *next(succ_begin());
286      if (MBBA == TBB) std::swap(MBBB, MBBA);
287      if (isLayoutSuccessor(TBB)) {
288        TII->RemoveBranch(*this);
289        TII->ReverseBranchCondition(Cond);
290        TII->InsertBranch(*this, MBBA, 0, Cond);
291      } else if (!isLayoutSuccessor(MBBA)) {
292        TII->RemoveBranch(*this);
293        TII->InsertBranch(*this, TBB, MBBA, Cond);
294      }
295    }
296  }
297}
298
299void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ) {
300  Successors.push_back(succ);
301  succ->addPredecessor(this);
302}
303
304void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
305  succ->removePredecessor(this);
306  succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
307  assert(I != Successors.end() && "Not a current successor!");
308  Successors.erase(I);
309}
310
311MachineBasicBlock::succ_iterator
312MachineBasicBlock::removeSuccessor(succ_iterator I) {
313  assert(I != Successors.end() && "Not a current successor!");
314  (*I)->removePredecessor(this);
315  return Successors.erase(I);
316}
317
318void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
319  Predecessors.push_back(pred);
320}
321
322void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
323  std::vector<MachineBasicBlock *>::iterator I =
324    std::find(Predecessors.begin(), Predecessors.end(), pred);
325  assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
326  Predecessors.erase(I);
327}
328
329void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
330  if (this == fromMBB)
331    return;
332
333  for (MachineBasicBlock::succ_iterator I = fromMBB->succ_begin(),
334       E = fromMBB->succ_end(); I != E; ++I)
335    addSuccessor(*I);
336
337  while (!fromMBB->succ_empty())
338    fromMBB->removeSuccessor(fromMBB->succ_begin());
339}
340
341bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
342  std::vector<MachineBasicBlock *>::const_iterator I =
343    std::find(Successors.begin(), Successors.end(), MBB);
344  return I != Successors.end();
345}
346
347bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
348  MachineFunction::const_iterator I(this);
349  return next(I) == MachineFunction::const_iterator(MBB);
350}
351
352/// removeFromParent - This method unlinks 'this' from the containing function,
353/// and returns it, but does not delete it.
354MachineBasicBlock *MachineBasicBlock::removeFromParent() {
355  assert(getParent() && "Not embedded in a function!");
356  getParent()->remove(this);
357  return this;
358}
359
360
361/// eraseFromParent - This method unlinks 'this' from the containing function,
362/// and deletes it.
363void MachineBasicBlock::eraseFromParent() {
364  assert(getParent() && "Not embedded in a function!");
365  getParent()->erase(this);
366}
367
368
369/// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
370/// 'Old', change the code and CFG so that it branches to 'New' instead.
371void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
372                                               MachineBasicBlock *New) {
373  assert(Old != New && "Cannot replace self with self!");
374
375  MachineBasicBlock::iterator I = end();
376  while (I != begin()) {
377    --I;
378    if (!I->getDesc().isTerminator()) break;
379
380    // Scan the operands of this machine instruction, replacing any uses of Old
381    // with New.
382    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
383      if (I->getOperand(i).isMBB() &&
384          I->getOperand(i).getMBB() == Old)
385        I->getOperand(i).setMBB(New);
386  }
387
388  // Update the successor information.
389  removeSuccessor(Old);
390  addSuccessor(New);
391}
392
393/// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
394/// CFG to be inserted.  If we have proven that MBB can only branch to DestA and
395/// DestB, remove any other MBB successors from the CFG.  DestA and DestB can
396/// be null.
397/// Besides DestA and DestB, retain other edges leading to LandingPads
398/// (currently there can be only one; we don't check or require that here).
399/// Note it is possible that DestA and/or DestB are LandingPads.
400bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
401                                             MachineBasicBlock *DestB,
402                                             bool isCond) {
403  bool MadeChange = false;
404  bool AddedFallThrough = false;
405
406  MachineFunction::iterator FallThru = next(MachineFunction::iterator(this));
407
408  // If this block ends with a conditional branch that falls through to its
409  // successor, set DestB as the successor.
410  if (isCond) {
411    if (DestB == 0 && FallThru != getParent()->end()) {
412      DestB = FallThru;
413      AddedFallThrough = true;
414    }
415  } else {
416    // If this is an unconditional branch with no explicit dest, it must just be
417    // a fallthrough into DestB.
418    if (DestA == 0 && FallThru != getParent()->end()) {
419      DestA = FallThru;
420      AddedFallThrough = true;
421    }
422  }
423
424  MachineBasicBlock::succ_iterator SI = succ_begin();
425  MachineBasicBlock *OrigDestA = DestA, *OrigDestB = DestB;
426  while (SI != succ_end()) {
427    if (*SI == DestA) {
428      DestA = 0;
429      ++SI;
430    } else if (*SI == DestB) {
431      DestB = 0;
432      ++SI;
433    } else if ((*SI)->isLandingPad() &&
434               *SI!=OrigDestA && *SI!=OrigDestB) {
435      ++SI;
436    } else {
437      // Otherwise, this is a superfluous edge, remove it.
438      SI = removeSuccessor(SI);
439      MadeChange = true;
440    }
441  }
442  if (!AddedFallThrough) {
443    assert(DestA == 0 && DestB == 0 &&
444           "MachineCFG is missing edges!");
445  } else if (isCond) {
446    assert(DestA == 0 && "MachineCFG is missing edges!");
447  }
448  return MadeChange;
449}
450