LLVM 24.0.0git
CodeGenCommonISel.h
Go to the documentation of this file.
1//===- CodeGenCommonISel.h - Common code between ISels ---------*- C++ -*--===//
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 declares common utilities that are shared between SelectionDAG and
10// GlobalISel frameworks.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CODEGEN_CODEGENCOMMONISEL_H
15#define LLVM_CODEGEN_CODEGENCOMMONISEL_H
16
18#include <cassert>
19namespace llvm {
20
21class BasicBlock;
22class Instruction;
23class MDNode;
24enum FPClassTest : unsigned;
25
26/// Encapsulates all of the information needed to generate a stack protector
27/// check, and signals to isel when initialized that one needs to be generated.
28///
29/// *NOTE* The following is a high level documentation of SelectionDAG Stack
30/// Protector Generation. This is now also ported be shared with GlobalISel,
31/// but without any significant changes.
32///
33/// High Level Overview of ISel Stack Protector Generation:
34///
35/// Previously, the "stack protector" IR pass handled stack protector
36/// generation. This necessitated splitting basic blocks at the IR level to
37/// create the success/failure basic blocks in the tail of the basic block in
38/// question. As a result of this, calls that would have qualified for the
39/// sibling call optimization were no longer eligible for optimization since
40/// said calls were no longer right in the "tail position" (i.e. the immediate
41/// predecessor of a ReturnInst instruction).
42///
43/// Since the sibling call optimization causes the callee to reuse the caller's
44/// stack, if we could delay the generation of the stack protector check until
45/// later in CodeGen after the sibling call decision was made, we get both the
46/// tail call optimization and the stack protector check!
47///
48/// A few goals in solving this problem were:
49///
50/// 1. Preserve the architecture independence of stack protector generation.
51///
52/// 2. Preserve the normal IR level stack protector check for platforms like
53/// OpenBSD for which we support platform-specific stack protector
54/// generation.
55///
56/// The main problem that guided the present solution is that one can not
57/// solve this problem in an architecture independent manner at the IR level
58/// only. This is because:
59///
60/// 1. The decision on whether or not to perform a sibling call on certain
61/// platforms (for instance i386) requires lower level information
62/// related to available registers that can not be known at the IR level.
63///
64/// 2. Even if the previous point were not true, the decision on whether to
65/// perform a tail call is done in LowerCallTo in SelectionDAG (or
66/// CallLowering in GlobalISel) which occurs after the Stack Protector
67/// Pass. As a result, one would need to put the relevant callinst into the
68/// stack protector check success basic block (where the return inst is
69/// placed) and then move it back later at ISel/MI time before the
70/// stack protector check if the tail call optimization failed. The MI
71/// level option was nixed immediately since it would require
72/// platform-specific pattern matching. The ISel level option was
73/// nixed because SelectionDAG only processes one IR level basic block at a
74/// time implying one could not create a DAG Combine to move the callinst.
75///
76/// To get around this problem:
77///
78/// 1. SelectionDAG can only process one block at a time, we can generate
79/// multiple machine basic blocks for one IR level basic block.
80/// This is how we handle bit tests and switches.
81///
82/// 2. At the MI level, tail calls are represented via a special return
83/// MIInst called "tcreturn". Thus if we know the basic block in which we
84/// wish to insert the stack protector check, we get the correct behavior
85/// by always inserting the stack protector check right before the return
86/// statement. This is a "magical transformation" since no matter where
87/// the stack protector check intrinsic is, we always insert the stack
88/// protector check code at the end of the BB.
89///
90/// Given the aforementioned constraints, the following solution was devised:
91///
92/// 1. On platforms that do not support ISel stack protector check
93/// generation, allow for the normal IR level stack protector check
94/// generation to continue.
95///
96/// 2. On platforms that do support ISel stack protector check
97/// generation:
98///
99/// a. Use the IR level stack protector pass to decide if a stack
100/// protector is required/which BB we insert the stack protector check
101/// in by reusing the logic already therein.
102///
103/// b. After we finish selecting the basic block, we produce the validation
104/// code with one of these techniques:
105/// 1) with a call to a guard check function
106/// 2) with inlined instrumentation
107///
108/// 1) We insert a call to the check function before the terminator.
109///
110/// 2) We first find a splice point in the parent basic block
111/// before the terminator and then splice the terminator of said basic
112/// block into the success basic block. Then we code-gen a new tail for
113/// the parent basic block consisting of the two loads, the comparison,
114/// and finally two branches to the success/failure basic blocks. We
115/// conclude by code-gening the failure basic block if we have not
116/// code-gened it already (all stack protector checks we generate in
117/// the same function, use the same failure basic block).
119public:
121
122 /// Returns true if all fields of the stack protector descriptor are
123 /// initialized implying that we should/are ready to emit a stack protector.
125 return ParentMBB && SuccessMBB && FailureMBB;
126 }
127
129 return ParentMBB && !SuccessMBB && !FailureMBB;
130 }
131
132 /// Initialize the stack protector descriptor structure for a new basic
133 /// block.
135 bool FunctionBasedInstrumentation) {
136 // Make sure we are not initialized yet.
137 assert(!shouldEmitStackProtector() && "Stack Protector Descriptor is "
138 "already initialized!");
139 ParentMBB = MBB;
140 if (!FunctionBasedInstrumentation) {
141 SuccessMBB = addSuccessorMBB(BB, MBB, /* IsLikely */ true);
142 FailureMBB = addSuccessorMBB(BB, MBB, /* IsLikely */ false, FailureMBB);
143 }
144 }
145
146 /// Reset state that changes when we handle different basic blocks.
147 ///
148 /// This currently includes:
149 ///
150 /// 1. The specific basic block we are generating a
151 /// stack protector for (ParentMBB).
152 ///
153 /// 2. The successor machine basic block that will contain the tail of
154 /// parent mbb after we create the stack protector check (SuccessMBB). This
155 /// BB is visited only on stack protector check success.
157 ParentMBB = nullptr;
158 SuccessMBB = nullptr;
159 }
160
161 /// Reset state that only changes when we switch functions.
162 ///
163 /// This currently includes:
164 ///
165 /// 1. FailureMBB since we reuse the failure code path for all stack
166 /// protector checks created in an individual function.
167 ///
168 /// 2.The guard variable since the guard variable we are checking against is
169 /// always the same.
170 void resetPerFunctionState() { FailureMBB = nullptr; }
171
172 MachineBasicBlock *getParentMBB() { return ParentMBB; }
173 MachineBasicBlock *getSuccessMBB() { return SuccessMBB; }
174 MachineBasicBlock *getFailureMBB() { return FailureMBB; }
175
176private:
177 /// The basic block for which we are generating the stack protector.
178 ///
179 /// As a result of stack protector generation, we will splice the
180 /// terminators of this basic block into the successor mbb SuccessMBB and
181 /// replace it with a compare/branch to the successor mbbs
182 /// SuccessMBB/FailureMBB depending on whether or not the stack protector
183 /// was violated.
184 MachineBasicBlock *ParentMBB = nullptr;
185
186 /// A basic block visited on stack protector check success that contains the
187 /// terminators of ParentMBB.
188 MachineBasicBlock *SuccessMBB = nullptr;
189
190 /// This basic block visited on stack protector check failure that will
191 /// contain a call to __stack_chk_fail().
192 MachineBasicBlock *FailureMBB = nullptr;
193
194 /// Add a successor machine basic block to ParentMBB. If the successor mbb
195 /// has not been created yet (i.e. if SuccMBB = 0), then the machine basic
196 /// block will be created. Assign a large weight if IsLikely is true.
198 addSuccessorMBB(const BasicBlock *BB, MachineBasicBlock *ParentMBB,
199 bool IsLikely, MachineBasicBlock *SuccMBB = nullptr);
200};
201
202/// Find the split point at which to splice the end of BB into its success stack
203/// protector check machine basic block.
204///
205/// On many platforms, due to ABI constraints, terminators, even before register
206/// allocation, use physical registers. This creates an issue for us since
207/// physical registers at this point can not travel across basic
208/// blocks. Luckily, selectiondag always moves physical registers into vregs
209/// when they enter functions and moves them through a sequence of copies back
210/// into the physical registers right before the terminator creating a
211/// ``Terminator Sequence''. This function is searching for the beginning of the
212/// terminator sequence so that we can ensure that we splice off not just the
213/// terminator, but additionally the copies that move the vregs into the
214/// physical registers.
216findSplitPointForStackProtector(MachineBasicBlock *BB,
217 const TargetInstrInfo &TII);
218
219/// Evaluates if the specified FP class test is better performed as the inverse
220/// (i.e. fewer instructions should be required to lower it). An example is the
221/// test "inf|normal|subnormal|zero", which is an inversion of "nan".
222///
223/// \param Test The test as specified in 'is_fpclass' intrinsic invocation.
224/// \param UseFCmp The intention is to perform the comparison using
225/// floating-point compare instructions which check for nan.
226///
227/// \returns The inverted test, or fcNone, if inversion does not produce a
228/// simpler test.
229LLVM_ABI FPClassTest invertFPClassTestIfSimpler(FPClassTest Test, bool UseFCmp);
230
231/// Return the cache hint metadata node for memory operand \p OperandNo on \p I,
232/// or nullptr when the instruction has no hint for that operand. For a \c
233/// CallBase, \p OperandNo is an argument index; otherwise it is an instruction
234/// operand index.
235LLVM_ABI const MDNode *getMemCacheHintMetadata(const Instruction &I,
236 unsigned OperandNo = 0);
237
238/// Assuming the instruction \p MI is going to be deleted, attempt to salvage
239/// debug users of \p MI by writing the effect of \p MI in a DIExpression.
240LLVM_ABI void salvageDebugInfoForDbgValue(const MachineRegisterInfo &MRI,
241 MachineInstr &MI,
243
244} // namespace llvm
245
246#endif // LLVM_CODEGEN_CODEGENCOMMONISEL_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
#define LLVM_ABI
Definition Compiler.h:215
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Metadata node.
Definition Metadata.h:1069
MachineInstrBundleIterator< MachineInstr > iterator
void initialize(const BasicBlock *BB, MachineBasicBlock *MBB, bool FunctionBasedInstrumentation)
Initialize the stack protector descriptor structure for a new basic block.
MachineBasicBlock * getSuccessMBB()
void resetPerBBState()
Reset state that changes when we handle different basic blocks.
void resetPerFunctionState()
Reset state that only changes when we switch functions.
MachineBasicBlock * getFailureMBB()
MachineBasicBlock * getParentMBB()
bool shouldEmitStackProtector() const
Returns true if all fields of the stack protector descriptor are initialized implying that we should/...
bool shouldEmitFunctionBasedCheckStackProtector() const
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...
ArrayRef(const T &OneElt) -> ArrayRef< T >
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...