1//===-- PHIEliminationUtils.cpp - Helper functions for PHI elimination ----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "PHIEliminationUtils.h"
10#include "llvm/ADT/SmallPtrSet.h"
11#include "llvm/CodeGen/MachineFunction.h"
12#include "llvm/CodeGen/MachineRegisterInfo.h"
13
14using namespace llvm;
15
16// findCopyInsertPoint - Find a safe place in MBB to insert a copy from SrcReg
17// when following the CFG edge to SuccMBB. This needs to be after any def of
18// SrcReg, but before any subsequent point where control flow might jump out of
19// the basic block.
20MachineBasicBlock::iterator
21llvm::findPHICopyInsertPoint(MachineBasicBlock* MBB, MachineBasicBlock* SuccMBB,
22 unsigned SrcReg) {
23 // Handle the trivial case trivially.
24 if (MBB->empty())
25 return MBB->begin();
26
27 // Usually, we just want to insert the copy before the first terminator
28 // instruction. However, for the edge going to a landing pad, we must insert
29 // the copy before the call/invoke instruction. Similarly for an INLINEASM_BR
30 // going to an indirect target. This is similar to SplitKit.cpp's
31 // computeLastInsertPoint, and similarly assumes that there cannot be multiple
32 // instructions that are Calls with EHPad successors or INLINEASM_BR in a
33 // block.
34 bool EHPadSuccessor = SuccMBB->isEHPad();
35 if (!EHPadSuccessor && !SuccMBB->isInlineAsmBrIndirectTarget())
36 return MBB->getFirstTerminator();
37
38 // Discover any defs in this basic block.
39 SmallPtrSet<MachineInstr *, 8> DefsInMBB;
40 MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
41 for (MachineInstr &RI : MRI.def_instructions(Reg: SrcReg))
42 if (RI.getParent() == MBB)
43 DefsInMBB.insert(Ptr: &RI);
44
45 MachineBasicBlock::iterator InsertPoint = MBB->begin();
46 // Insert the copy at the _latest_ point of:
47 // 1. Immediately AFTER the last def
48 // 2. Immediately BEFORE a call/inlineasm_br.
49 for (auto I = MBB->rbegin(), E = MBB->rend(); I != E; ++I) {
50 if (DefsInMBB.contains(Ptr: &*I)) {
51 InsertPoint = std::next(x: I.getReverse());
52 break;
53 }
54 if ((EHPadSuccessor && I->isCall()) ||
55 I->getOpcode() == TargetOpcode::INLINEASM_BR) {
56 InsertPoint = I.getReverse();
57 break;
58 }
59 }
60
61 // Make sure the copy goes after any phi nodes but before
62 // any debug nodes.
63 return MBB->SkipPHIsAndLabels(I: InsertPoint);
64}
65