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
21#include "llvm/IR/Constants.h"
23#include "llvm/IR/Instruction.h"
24#include "llvm/IR/LLVMContext.h"
25#include "llvm/IR/Metadata.h"
27
28#define DEBUG_TYPE "codegen-common"
29
30using namespace llvm;
31
33 unsigned OperandNo) {
34 const MDNode *MD = I.getMetadata(LLVMContext::MD_mem_cache_hint);
35 if (!MD)
36 return nullptr;
37
38 for (unsigned Idx = 0; Idx + 1 < MD->getNumOperands(); Idx += 2) {
39 const auto *OpNoCI = mdconst::extract<ConstantInt>(MD->getOperand(Idx));
40 const auto *Hint = cast<MDNode>(MD->getOperand(Idx + 1));
41 if (OpNoCI->getZExtValue() == OperandNo)
42 return Hint;
43 }
44
45 return nullptr;
46}
47
48/// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
49/// is 0.
51StackProtectorDescriptor::addSuccessorMBB(
52 const BasicBlock *BB, MachineBasicBlock *ParentMBB, bool IsLikely,
53 MachineBasicBlock *SuccMBB) {
54 // If SuccBB has not been created yet, create it.
55 if (!SuccMBB) {
56 MachineFunction *MF = ParentMBB->getParent();
57 MachineFunction::iterator BBI(ParentMBB);
58 SuccMBB = MF->CreateMachineBasicBlock(BB);
59 MF->insert(++BBI, SuccMBB);
60 }
61 // Add it as a successor of ParentMBB.
62 ParentMBB->addSuccessor(
64 return SuccMBB;
65}
66
67/// Given that the input MI is before a partial terminator sequence TSeq, return
68/// true if M + TSeq also a partial terminator sequence.
69///
70/// A Terminator sequence is a sequence of MachineInstrs which at this point in
71/// lowering copy vregs into physical registers, which are then passed into
72/// terminator instructors so we can satisfy ABI constraints. A partial
73/// terminator sequence is an improper subset of a terminator sequence (i.e. it
74/// may be the whole terminator sequence).
76 // If we do not have a copy or an implicit def, we return true if and only if
77 // MI is a debug value.
78 if (!MI.isCopy() && !MI.isImplicitDef()) {
79 // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the
80 // physical registers if there is debug info associated with the terminator
81 // of our mbb. We want to include said debug info in our terminator
82 // sequence, so we return true in that case.
83 if (MI.isDebugInstr())
84 return true;
85
86 // For GlobalISel, we may have extension instructions for arguments within
87 // copy sequences. Allow these.
88 switch (MI.getOpcode()) {
89 case TargetOpcode::G_TRUNC:
90 case TargetOpcode::G_ZEXT:
91 case TargetOpcode::G_ANYEXT:
92 case TargetOpcode::G_SEXT:
93 case TargetOpcode::G_MERGE_VALUES:
94 case TargetOpcode::G_UNMERGE_VALUES:
95 case TargetOpcode::G_CONCAT_VECTORS:
96 case TargetOpcode::G_BUILD_VECTOR:
97 case TargetOpcode::G_EXTRACT:
98 return true;
99 default:
100 return false;
101 }
102 }
103
104 // We have left the terminator sequence if we are not doing one of the
105 // following:
106 //
107 // 1. Copying a vreg into a physical register.
108 // 2. Copying a vreg into a vreg.
109 // 3. Defining a register via an implicit def.
110
111 // OPI should always be a register definition...
112 MachineInstr::const_mop_iterator OPI = MI.operands_begin();
113 if (!OPI->isReg() || !OPI->isDef())
114 return false;
115
116 // Defining any register via an implicit def is always ok.
117 if (MI.isImplicitDef())
118 return true;
119
120 // Grab the copy source...
122 ++OPI2;
123 assert(OPI2 != MI.operands_end()
124 && "Should have a copy implying we should have 2 arguments.");
125
126 // Make sure that the copy dest is not a vreg when the copy source is a
127 // physical register.
128 if (!OPI2->isReg() ||
129 (!OPI->getReg().isPhysical() && OPI2->getReg().isPhysical()))
130 return false;
131
132 return true;
133}
134
135/// Find the split point at which to splice the end of BB into its success stack
136/// protector check machine basic block.
137///
138/// On many platforms, due to ABI constraints, terminators, even before register
139/// allocation, use physical registers. This creates an issue for us since
140/// physical registers at this point can not travel across basic
141/// blocks. Luckily, selectiondag always moves physical registers into vregs
142/// when they enter functions and moves them through a sequence of copies back
143/// into the physical registers right before the terminator creating a
144/// ``Terminator Sequence''. This function is searching for the beginning of the
145/// terminator sequence so that we can ensure that we splice off not just the
146/// terminator, but additionally the copies that move the vregs into the
147/// physical registers.
150 const TargetInstrInfo &TII) {
152 if (SplitPoint == BB->begin())
153 return SplitPoint;
154
156 MachineBasicBlock::iterator Previous = SplitPoint;
157 do {
158 --Previous;
159 } while (Previous != Start && Previous->isDebugInstr());
160
161 if (TII.isTailCall(*SplitPoint) &&
162 Previous->getOpcode() == TII.getCallFrameDestroyOpcode()) {
163 // Call frames cannot be nested, so if this frame is describing the tail
164 // call itself, then we must insert before the sequence even starts. For
165 // example:
166 // <split point>
167 // ADJCALLSTACKDOWN ...
168 // <Moves>
169 // ADJCALLSTACKUP ...
170 // TAILJMP somewhere
171 // On the other hand, it could be an unrelated call in which case this tail
172 // call has no register moves of its own and should be the split point. For
173 // example:
174 // ADJCALLSTACKDOWN
175 // CALL something_else
176 // ADJCALLSTACKUP
177 // <split point>
178 // TAILJMP somewhere
179 do {
180 --Previous;
181 if (Previous->isCall())
182 return SplitPoint;
183 } while(Previous->getOpcode() != TII.getCallFrameSetupOpcode());
184
185 return Previous;
186 }
187
188 while (MIIsInTerminatorSequence(*Previous)) {
189 SplitPoint = Previous;
190 if (Previous == Start)
191 break;
192 --Previous;
193 }
194
195 return SplitPoint;
196}
197
199 FPClassTest InvertedTest = ~Test;
200
201 // Pick the direction with fewer tests
202 // TODO: Handle more combinations of cases that can be handled together
203 switch (static_cast<unsigned>(InvertedTest)) {
204 case fcNan:
205 case fcSNan:
206 case fcQNan:
207 case fcInf:
208 case fcPosInf:
209 case fcNegInf:
210 case fcNormal:
211 case fcPosNormal:
212 case fcNegNormal:
213 case fcSubnormal:
214 case fcPosSubnormal:
215 case fcNegSubnormal:
216 case fcZero:
217 case fcPosZero:
218 case fcNegZero:
219 case fcFinite:
220 case fcPosFinite:
221 case fcNegFinite:
222 case fcZero | fcNan:
223 case fcSubnormal | fcZero:
224 case fcSubnormal | fcZero | fcNan:
225 return InvertedTest;
226 case fcInf | fcNan:
227 case fcPosInf | fcNan:
228 case fcNegInf | fcNan:
229 // If we're trying to use fcmp, we can take advantage of the nan check
230 // behavior of the compare (but this is more instructions in the integer
231 // expansion).
232 return UseFCmp ? InvertedTest : fcNone;
233 default:
234 return fcNone;
235 }
236
237 llvm_unreachable("covered FPClassTest");
238}
239
241 MachineInstr &Copy) {
242 assert(Copy.getOpcode() == TargetOpcode::COPY && "Must be a COPY");
243
244 return &Copy.getOperand(1);
245}
246
248 MachineInstr &Trunc,
250 assert(Trunc.getOpcode() == TargetOpcode::G_TRUNC && "Must be a G_TRUNC");
251
252 const auto FromLLT = MRI.getType(Trunc.getOperand(1).getReg());
253 const auto ToLLT = MRI.getType(Trunc.defs().begin()->getReg());
254
255 // TODO: Support non-scalar types.
256 if (!FromLLT.isScalar()) {
257 return nullptr;
258 }
259
260 auto ExtOps = DIExpression::getExtOps(FromLLT.getSizeInBits(),
261 ToLLT.getSizeInBits(), false);
262 Ops.append(ExtOps.begin(), ExtOps.end());
263 return &Trunc.getOperand(1);
264}
265
269 switch (MI.getOpcode()) {
270 case TargetOpcode::G_TRUNC:
272 case TargetOpcode::COPY:
273 return getSalvageOpsForCopy(MRI, MI);
274 default:
275 return nullptr;
276 }
277}
278
282 // These are arbitrary chosen limits on the maximum number of values and the
283 // maximum size of a debug expression we can salvage up to, used for
284 // performance reasons.
285 const unsigned MaxExpressionSize = 128;
286
288 for (auto *DefMO : DbgUsers) {
289 MachineInstr *DbgMI = DefMO->getParent();
290 // A DBG_VALUE_LIST may use the salvaged register in several location
291 // operands; all of them are rewritten the first time it is seen.
292 if (!Visited.insert(DbgMI).second)
293 continue;
294 if (DbgMI->isIndirectDebugValue()) {
295 continue;
296 }
297
298 Register Reg = DefMO->getReg();
299 assert(DbgMI->hasDebugOperandForReg(Reg) &&
300 "Must use salvaged instruction as its location");
301
302 const DIExpression *SalvagedExpr = DbgMI->getDebugExpression();
303
305 auto Op0 = salvageDebugInfoImpl(MRI, MI, Ops);
306 if (!Op0)
307 continue;
308
311 for (MachineOperand *LocMO : LocMOs)
312 SalvagedExpr = DIExpression::appendOpsToArg(
313 SalvagedExpr, Ops, DbgMI->getDebugOperandIndex(LocMO), true);
314
315 bool IsValidSalvageExpr =
316 SalvagedExpr->getNumElements() <= MaxExpressionSize;
317 if (IsValidSalvageExpr) {
318 for (MachineOperand *LocMO : LocMOs) {
319 LocMO->setReg(Op0->getReg());
320 LocMO->setSubReg(Op0->getSubReg());
321 }
322 DbgMI->getDebugExpressionOp().setMetadata(SalvagedExpr);
323
324 LLVM_DEBUG(dbgs() << "SALVAGE: " << *DbgMI << '\n');
325 }
326 }
327}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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 ...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
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
This file contains the declarations for metadata subclasses.
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:62
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...
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
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.
mop_range defs()
Returns all explicit operands that are register definitions.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
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.
const MachineOperand * const_mop_iterator
LLVM_ABI const DIExpression * getDebugExpression() const
Return the complex address expression referenced by this DBG_VALUE instruction.
unsigned getDebugOperandIndex(const MachineOperand *Op) const
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.
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...
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.
IteratorT begin() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
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 const MDNode * getMemCacheHintMetadata(const Instruction &I, unsigned OperandNo=0)
Return the cache hint metadata node for memory operand OperandNo on I, or nullptr when the instructio...
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
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
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...