LLVM 24.0.0git
CodeGenCommonISel.cpp
Go to the documentation of this file.
1//===-- CodeGenCommonISel.cpp ---------------------------------------------===//
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// This file defines common utilies that are shared between SelectionDAG and
10// GlobalISel frameworks.
11//
12//===----------------------------------------------------------------------===//
13
22#include "llvm/IR/Instruction.h"
23
24#define DEBUG_TYPE "codegen-common"
25
26using namespace llvm;
27
28/// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
29/// is 0.
31StackProtectorDescriptor::addSuccessorMBB(
32 const BasicBlock *BB, MachineBasicBlock *ParentMBB, bool IsLikely,
33 MachineBasicBlock *SuccMBB) {
34 // If SuccBB has not been created yet, create it.
35 if (!SuccMBB) {
36 MachineFunction *MF = ParentMBB->getParent();
37 MachineFunction::iterator BBI(ParentMBB);
38 SuccMBB = MF->CreateMachineBasicBlock(BB);
39 MF->insert(++BBI, SuccMBB);
40 }
41 // Add it as a successor of ParentMBB.
42 ParentMBB->addSuccessor(
44 return SuccMBB;
45}
46
47/// Given that the input MI is before a partial terminator sequence TSeq, return
48/// true if M + TSeq also a partial terminator sequence.
49///
50/// A Terminator sequence is a sequence of MachineInstrs which at this point in
51/// lowering copy vregs into physical registers, which are then passed into
52/// terminator instructors so we can satisfy ABI constraints. A partial
53/// terminator sequence is an improper subset of a terminator sequence (i.e. it
54/// may be the whole terminator sequence).
56 // If we do not have a copy or an implicit def, we return true if and only if
57 // MI is a debug value.
58 if (!MI.isCopy() && !MI.isImplicitDef()) {
59 // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the
60 // physical registers if there is debug info associated with the terminator
61 // of our mbb. We want to include said debug info in our terminator
62 // sequence, so we return true in that case.
63 if (MI.isDebugInstr())
64 return true;
65
66 // For GlobalISel, we may have extension instructions for arguments within
67 // copy sequences. Allow these.
68 switch (MI.getOpcode()) {
69 case TargetOpcode::G_TRUNC:
70 case TargetOpcode::G_ZEXT:
71 case TargetOpcode::G_ANYEXT:
72 case TargetOpcode::G_SEXT:
73 case TargetOpcode::G_MERGE_VALUES:
74 case TargetOpcode::G_UNMERGE_VALUES:
75 case TargetOpcode::G_CONCAT_VECTORS:
76 case TargetOpcode::G_BUILD_VECTOR:
77 case TargetOpcode::G_EXTRACT:
78 return true;
79 default:
80 return false;
81 }
82 }
83
84 // We have left the terminator sequence if we are not doing one of the
85 // following:
86 //
87 // 1. Copying a vreg into a physical register.
88 // 2. Copying a vreg into a vreg.
89 // 3. Defining a register via an implicit def.
90
91 // OPI should always be a register definition...
92 MachineInstr::const_mop_iterator OPI = MI.operands_begin();
93 if (!OPI->isReg() || !OPI->isDef())
94 return false;
95
96 // Defining any register via an implicit def is always ok.
97 if (MI.isImplicitDef())
98 return true;
99
100 // Grab the copy source...
102 ++OPI2;
103 assert(OPI2 != MI.operands_end()
104 && "Should have a copy implying we should have 2 arguments.");
105
106 // Make sure that the copy dest is not a vreg when the copy source is a
107 // physical register.
108 if (!OPI2->isReg() ||
109 (!OPI->getReg().isPhysical() && OPI2->getReg().isPhysical()))
110 return false;
111
112 return true;
113}
114
115/// Find the split point at which to splice the end of BB into its success stack
116/// protector check machine basic block.
117///
118/// On many platforms, due to ABI constraints, terminators, even before register
119/// allocation, use physical registers. This creates an issue for us since
120/// physical registers at this point can not travel across basic
121/// blocks. Luckily, selectiondag always moves physical registers into vregs
122/// when they enter functions and moves them through a sequence of copies back
123/// into the physical registers right before the terminator creating a
124/// ``Terminator Sequence''. This function is searching for the beginning of the
125/// terminator sequence so that we can ensure that we splice off not just the
126/// terminator, but additionally the copies that move the vregs into the
127/// physical registers.
130 const TargetInstrInfo &TII) {
132 if (SplitPoint == BB->begin())
133 return SplitPoint;
134
136 MachineBasicBlock::iterator Previous = SplitPoint;
137 do {
138 --Previous;
139 } while (Previous != Start && Previous->isDebugInstr());
140
141 if (TII.isTailCall(*SplitPoint) &&
142 Previous->getOpcode() == TII.getCallFrameDestroyOpcode()) {
143 // Call frames cannot be nested, so if this frame is describing the tail
144 // call itself, then we must insert before the sequence even starts. For
145 // example:
146 // <split point>
147 // ADJCALLSTACKDOWN ...
148 // <Moves>
149 // ADJCALLSTACKUP ...
150 // TAILJMP somewhere
151 // On the other hand, it could be an unrelated call in which case this tail
152 // call has no register moves of its own and should be the split point. For
153 // example:
154 // ADJCALLSTACKDOWN
155 // CALL something_else
156 // ADJCALLSTACKUP
157 // <split point>
158 // TAILJMP somewhere
159 do {
160 --Previous;
161 if (Previous->isCall())
162 return SplitPoint;
163 } while(Previous->getOpcode() != TII.getCallFrameSetupOpcode());
164
165 return Previous;
166 }
167
168 while (MIIsInTerminatorSequence(*Previous)) {
169 SplitPoint = Previous;
170 if (Previous == Start)
171 break;
172 --Previous;
173 }
174
175 return SplitPoint;
176}
177
179 FPClassTest InvertedTest = ~Test;
180
181 // Pick the direction with fewer tests
182 // TODO: Handle more combinations of cases that can be handled together
183 switch (static_cast<unsigned>(InvertedTest)) {
184 case fcNan:
185 case fcSNan:
186 case fcQNan:
187 case fcInf:
188 case fcPosInf:
189 case fcNegInf:
190 case fcNormal:
191 case fcPosNormal:
192 case fcNegNormal:
193 case fcSubnormal:
194 case fcPosSubnormal:
195 case fcNegSubnormal:
196 case fcZero:
197 case fcPosZero:
198 case fcNegZero:
199 case fcFinite:
200 case fcPosFinite:
201 case fcNegFinite:
202 case fcZero | fcNan:
203 case fcSubnormal | fcZero:
204 case fcSubnormal | fcZero | fcNan:
205 return InvertedTest;
206 case fcInf | fcNan:
207 case fcPosInf | fcNan:
208 case fcNegInf | fcNan:
209 // If we're trying to use fcmp, we can take advantage of the nan check
210 // behavior of the compare (but this is more instructions in the integer
211 // expansion).
212 return UseFCmp ? InvertedTest : fcNone;
213 default:
214 return fcNone;
215 }
216
217 llvm_unreachable("covered FPClassTest");
218}
219
221 MachineInstr &Copy) {
222 assert((Copy.getOpcode() == TargetOpcode::COPY ||
223 Copy.getOpcode() == TargetOpcode::G_BITCAST) &&
224 "Must be a COPY or G_BITCAST");
225
226 return &Copy.getOperand(1);
227}
228
232 assert(Trunc.getOpcode() == TargetOpcode::G_TRUNC && "Must be a G_TRUNC");
233
234 const auto FromLLT = MRI.getType(Trunc.getOperand(1).getReg());
235 const auto ToLLT = MRI.getType(Trunc.defs().begin()->getReg());
236
237 // TODO: Support non-scalar types.
238 if (!FromLLT.isScalar()) {
239 return nullptr;
240 }
241
242 auto ExtOps = DIExpression::getExtOps(FromLLT.getSizeInBits(),
243 ToLLT.getSizeInBits(), false);
244 Ops.append(ExtOps.begin(), ExtOps.end());
245 return &Trunc.getOperand(1);
246}
247
251 switch (MI.getOpcode()) {
252 case TargetOpcode::G_TRUNC:
254 case TargetOpcode::COPY:
255 case TargetOpcode::G_BITCAST:
256 return getSalvageOpsForCopy(MRI, MI);
257 default:
258 return nullptr;
259 }
260}
261
262/// Replace \p DbgMI, which describes the result of \p BuildVector, with one
263/// fragment debug value per vector element.
265 MachineInstr &BuildVector, MachineInstr &DbgMI) {
266 const DIExpression *Expr = DbgMI.getDebugExpression();
267 if (DbgMI.getNumDebugOperands() != 1 || !Expr->isSingleLocationExpression() ||
268 Expr->isComplex())
269 return;
270
271 unsigned VecSize = MRI.getType(BuildVector.getOperand(0).getReg())
272 .getSizeInBits()
273 .getFixedValue();
274 if (auto Fragment = Expr->getFragmentInfo()) {
275 if (VecSize > Fragment->SizeInBits)
276 return;
277 } else if (auto VarSize = DbgMI.getDebugVariable()->getSizeInBits()) {
278 if (VecSize > *VarSize)
279 return;
280 }
281
282 unsigned NumElts = BuildVector.getNumOperands() - 1;
283 unsigned EltSize = VecSize / NumElts;
285 for (unsigned I = 0; I != NumElts; ++I) {
286 auto FragExpr =
287 DIExpression::createFragmentExpression(Expr, I * EltSize, EltSize);
288 if (!FragExpr)
289 return;
290 FragExprs.push_back(*FragExpr);
291 }
292
293 MachineBasicBlock &MBB = *DbgMI.getParent();
294 MachineFunction &MF = *MBB.getParent();
295 for (unsigned I = NumElts - 1; I != 0; --I) {
296 MachineInstr *NewMI = MF.CloneMachineInstr(&DbgMI);
297 NewMI->getDebugOperand(0).setReg(BuildVector.getOperand(I + 1).getReg());
298 NewMI->getDebugExpressionOp().setMetadata(FragExprs[I]);
299 MBB.insertAfter(DbgMI.getIterator(), NewMI);
300 LLVM_DEBUG(dbgs() << "SALVAGE: " << *NewMI << '\n');
301 }
302 DbgMI.getDebugOperand(0).setReg(BuildVector.getOperand(1).getReg());
303 DbgMI.getDebugExpressionOp().setMetadata(FragExprs[0]);
304 LLVM_DEBUG(dbgs() << "SALVAGE: " << DbgMI << '\n');
305}
306
310 // These are arbitrary chosen limits on the maximum number of values and the
311 // maximum size of a debug expression we can salvage up to, used for
312 // performance reasons.
313 const unsigned MaxExpressionSize = 128;
314
316 for (auto *DefMO : DbgUsers) {
317 MachineInstr *DbgMI = DefMO->getParent();
318 // A DBG_VALUE_LIST may use the salvaged register in several location
319 // operands; all of them are rewritten the first time it is seen.
320 if (!Visited.insert(DbgMI).second)
321 continue;
322 if (DbgMI->isIndirectDebugValue()) {
323 continue;
324 }
325
326 Register Reg = DefMO->getReg();
327 assert(DbgMI->hasDebugOperandForReg(Reg) &&
328 "Must use salvaged instruction as its location");
329
330 if (MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR) {
331 assert(DbgMI->isDebugValue() &&
332 "Must be either DBG_VALUE or DBG_VALUE_LIST");
333 salvageBuildVector(MRI, MI, *DbgMI);
334 continue;
335 }
336
337 const DIExpression *SalvagedExpr = DbgMI->getDebugExpression();
338
340 auto Op0 = salvageDebugInfoImpl(MRI, MI, Ops);
341 if (!Op0)
342 continue;
343
346 for (MachineOperand *LocMO : LocMOs)
347 SalvagedExpr = DIExpression::appendOpsToArg(
348 SalvagedExpr, Ops, DbgMI->getDebugOperandIndex(LocMO), true);
349
350 bool IsValidSalvageExpr =
351 SalvagedExpr->getNumElements() <= MaxExpressionSize;
352 if (IsValidSalvageExpr) {
353 for (MachineOperand *LocMO : LocMOs) {
354 LocMO->setReg(Op0->getReg());
355 LocMO->setSubReg(Op0->getSubReg());
356 }
357 DbgMI->getDebugExpressionOp().setMetadata(SalvagedExpr);
358
359 LLVM_DEBUG(dbgs() << "SALVAGE: " << *DbgMI << '\n');
360 }
361 }
362}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static void salvageBuildVector(const MachineRegisterInfo &MRI, MachineInstr &BuildVector, MachineInstr &DbgMI)
Replace DbgMI, which describes the result of BuildVector, with one fragment debug value per vector el...
static MachineOperand * getSalvageOpsForTrunc(const MachineRegisterInfo &MRI, MachineInstr &Trunc, SmallVectorImpl< uint64_t > &Ops)
static MachineOperand * getSalvageOpsForCopy(const MachineRegisterInfo &MRI, MachineInstr &Copy)
static bool MIIsInTerminatorSequence(const MachineInstr &MI)
Given that the input MI is before a partial terminator sequence TSeq, return true if M + TSeq also a ...
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define I(x, y, z)
Definition MD5.cpp:57
MachineRegisterInfo & MRI
This file defines the SmallPtrSet class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:61
static BranchProbability getBranchProbStackProtector(bool IsLikely)
DWARF expression.
unsigned getNumElements() const
static LLVM_ABI ExtOps getExtOps(unsigned FromSize, unsigned ToSize, bool Signed)
Returns the ops for a zero- or sign-extension in a DIExpression.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
LLVM_ABI bool isComplex() const
Return whether the location is computed on the expression stack, meaning it cannot be a simple regist...
static LLVM_ABI std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
static LLVM_ABI std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
LLVM_ABI bool isSingleLocationExpression() const
Return whether the evaluated expression makes use of a single location at the start of the expression...
LLVM_ABI std::optional< uint64_t > getSizeInBits() const
Determines the size of the variable's type.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
BasicBlockListType::iterator iterator
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
Representation of each machine instruction.
bool hasDebugOperandForReg(Register Reg) const
Returns whether this debug value has at least one debug operand with the register Reg.
LLVM_ABI iterator_range< filter_iterator< const MachineOperand *, std::function< bool(const MachineOperand &Op)> > > getDebugOperandsForReg(Register Reg) const
Returns a range of all of the operands that correspond to a debug use of Reg.
const MachineBasicBlock * getParent() const
LLVM_ABI const MachineOperand & getDebugExpressionOp() const
Return the operand for the complex address expression referenced by this DBG_VALUE instruction.
unsigned getNumDebugOperands() const
Returns the total number of operands which are debug locations.
unsigned getNumOperands() const
Retuns the total number of operands.
const MachineOperand * const_mop_iterator
LLVM_ABI const DILocalVariable * getDebugVariable() const
Return the debug variable referenced by this DBG_VALUE instruction.
LLVM_ABI const DIExpression * getDebugExpression() const
Return the complex address expression referenced by this DBG_VALUE instruction.
bool isDebugValue() const
unsigned getDebugOperandIndex(const MachineOperand *Op) const
MachineOperand & getDebugOperand(unsigned Index)
const MachineOperand & getOperand(unsigned i) const
bool isIndirectDebugValue() const
A DBG_VALUE is indirect iff the location operand is a register and the offset operand is an immediate...
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setMetadata(const MDNode *MD)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI FPClassTest invertFPClassTestIfSimpler(FPClassTest Test, bool UseFCmp)
Evaluates if the specified FP class test is better performed as the inverse (i.e.
LLVM_ABI MachineBasicBlock::iterator findSplitPointForStackProtector(MachineBasicBlock *BB, const TargetInstrInfo &TII)
Find the split point at which to splice the end of BB into its success stack protector check machine ...
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI Value * salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Ops, SmallVectorImpl< Value * > &AdditionalValues)
Definition Local.cpp:2353
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
LLVM_ABI void salvageDebugInfoForDbgValue(const MachineRegisterInfo &MRI, MachineInstr &MI, ArrayRef< MachineOperand * > DbgUsers)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...