Bug Summary

File:llvm/include/llvm/CodeGen/SelectionDAGNodes.h
Warning:line 1101, column 10
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name StatepointLowering.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/lib/CodeGen/SelectionDAG -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/lib/CodeGen/SelectionDAG -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-09-17-195756-12974-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp

/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp

1//===- StatepointLowering.cpp - SDAGBuilder's statepoint code -------------===//
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 includes support code use by SelectionDAGBuilder when lowering a
10// statepoint sequence in SelectionDAG IR.
11//
12//===----------------------------------------------------------------------===//
13
14#include "StatepointLowering.h"
15#include "SelectionDAGBuilder.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/None.h"
18#include "llvm/ADT/Optional.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/CodeGen/FunctionLoweringInfo.h"
23#include "llvm/CodeGen/GCMetadata.h"
24#include "llvm/CodeGen/GCStrategy.h"
25#include "llvm/CodeGen/ISDOpcodes.h"
26#include "llvm/CodeGen/MachineFrameInfo.h"
27#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineMemOperand.h"
29#include "llvm/CodeGen/RuntimeLibcalls.h"
30#include "llvm/CodeGen/SelectionDAG.h"
31#include "llvm/CodeGen/StackMaps.h"
32#include "llvm/CodeGen/TargetLowering.h"
33#include "llvm/CodeGen/TargetOpcodes.h"
34#include "llvm/IR/CallingConv.h"
35#include "llvm/IR/DerivedTypes.h"
36#include "llvm/IR/Instruction.h"
37#include "llvm/IR/Instructions.h"
38#include "llvm/IR/LLVMContext.h"
39#include "llvm/IR/Statepoint.h"
40#include "llvm/IR/Type.h"
41#include "llvm/Support/Casting.h"
42#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/MachineValueType.h"
44#include "llvm/Target/TargetMachine.h"
45#include "llvm/Target/TargetOptions.h"
46#include <cassert>
47#include <cstddef>
48#include <cstdint>
49#include <iterator>
50#include <tuple>
51#include <utility>
52
53using namespace llvm;
54
55#define DEBUG_TYPE"statepoint-lowering" "statepoint-lowering"
56
57STATISTIC(NumSlotsAllocatedForStatepoints,static llvm::Statistic NumSlotsAllocatedForStatepoints = {"statepoint-lowering"
, "NumSlotsAllocatedForStatepoints", "Number of stack slots allocated for statepoints"
}
58 "Number of stack slots allocated for statepoints")static llvm::Statistic NumSlotsAllocatedForStatepoints = {"statepoint-lowering"
, "NumSlotsAllocatedForStatepoints", "Number of stack slots allocated for statepoints"
}
;
59STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered")static llvm::Statistic NumOfStatepoints = {"statepoint-lowering"
, "NumOfStatepoints", "Number of statepoint nodes encountered"
}
;
60STATISTIC(StatepointMaxSlotsRequired,static llvm::Statistic StatepointMaxSlotsRequired = {"statepoint-lowering"
, "StatepointMaxSlotsRequired", "Maximum number of stack slots required for a singe statepoint"
}
61 "Maximum number of stack slots required for a singe statepoint")static llvm::Statistic StatepointMaxSlotsRequired = {"statepoint-lowering"
, "StatepointMaxSlotsRequired", "Maximum number of stack slots required for a singe statepoint"
}
;
62
63cl::opt<bool> UseRegistersForDeoptValues(
64 "use-registers-for-deopt-values", cl::Hidden, cl::init(false),
65 cl::desc("Allow using registers for non pointer deopt args"));
66
67cl::opt<unsigned> MaxRegistersForGCPointers(
68 "max-registers-for-gc-values", cl::Hidden, cl::init(0),
69 cl::desc("Max number of VRegs allowed to pass GC pointer meta args in"));
70
71cl::opt<bool> AlwaysSpillBase("statepoint-always-spill-base", cl::Hidden,
72 cl::init(true),
73 cl::desc("Force spilling of base GC pointers"));
74
75typedef FunctionLoweringInfo::StatepointRelocationRecord RecordType;
76
77static void pushStackMapConstant(SmallVectorImpl<SDValue>& Ops,
78 SelectionDAGBuilder &Builder, uint64_t Value) {
79 SDLoc L = Builder.getCurSDLoc();
80 Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
81 MVT::i64));
82 Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
83}
84
85void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
86 // Consistency check
87 assert(PendingGCRelocateCalls.empty() &&((PendingGCRelocateCalls.empty() && "Trying to visit statepoint before finished processing previous one"
) ? static_cast<void> (0) : __assert_fail ("PendingGCRelocateCalls.empty() && \"Trying to visit statepoint before finished processing previous one\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 88, __PRETTY_FUNCTION__))
88 "Trying to visit statepoint before finished processing previous one")((PendingGCRelocateCalls.empty() && "Trying to visit statepoint before finished processing previous one"
) ? static_cast<void> (0) : __assert_fail ("PendingGCRelocateCalls.empty() && \"Trying to visit statepoint before finished processing previous one\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 88, __PRETTY_FUNCTION__))
;
89 Locations.clear();
90 NextSlotToAllocate = 0;
91 // Need to resize this on each safepoint - we need the two to stay in sync and
92 // the clear patterns of a SelectionDAGBuilder have no relation to
93 // FunctionLoweringInfo. Also need to ensure used bits get cleared.
94 AllocatedStackSlots.clear();
95 AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
96}
97
98void StatepointLoweringState::clear() {
99 Locations.clear();
100 AllocatedStackSlots.clear();
101 assert(PendingGCRelocateCalls.empty() &&((PendingGCRelocateCalls.empty() && "cleared before statepoint sequence completed"
) ? static_cast<void> (0) : __assert_fail ("PendingGCRelocateCalls.empty() && \"cleared before statepoint sequence completed\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 102, __PRETTY_FUNCTION__))
102 "cleared before statepoint sequence completed")((PendingGCRelocateCalls.empty() && "cleared before statepoint sequence completed"
) ? static_cast<void> (0) : __assert_fail ("PendingGCRelocateCalls.empty() && \"cleared before statepoint sequence completed\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 102, __PRETTY_FUNCTION__))
;
103}
104
105SDValue
106StatepointLoweringState::allocateStackSlot(EVT ValueType,
107 SelectionDAGBuilder &Builder) {
108 NumSlotsAllocatedForStatepoints++;
109 MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
110
111 unsigned SpillSize = ValueType.getStoreSize();
112 assert((SpillSize * 8) == ValueType.getSizeInBits() && "Size not in bytes?")(((SpillSize * 8) == ValueType.getSizeInBits() && "Size not in bytes?"
) ? static_cast<void> (0) : __assert_fail ("(SpillSize * 8) == ValueType.getSizeInBits() && \"Size not in bytes?\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 112, __PRETTY_FUNCTION__))
;
113
114 // First look for a previously created stack slot which is not in
115 // use (accounting for the fact arbitrary slots may already be
116 // reserved), or to create a new stack slot and use it.
117
118 const size_t NumSlots = AllocatedStackSlots.size();
119 assert(NextSlotToAllocate <= NumSlots && "Broken invariant")((NextSlotToAllocate <= NumSlots && "Broken invariant"
) ? static_cast<void> (0) : __assert_fail ("NextSlotToAllocate <= NumSlots && \"Broken invariant\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 119, __PRETTY_FUNCTION__))
;
120
121 assert(AllocatedStackSlots.size() ==((AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots
.size() && "Broken invariant") ? static_cast<void>
(0) : __assert_fail ("AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots.size() && \"Broken invariant\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 123, __PRETTY_FUNCTION__))
122 Builder.FuncInfo.StatepointStackSlots.size() &&((AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots
.size() && "Broken invariant") ? static_cast<void>
(0) : __assert_fail ("AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots.size() && \"Broken invariant\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 123, __PRETTY_FUNCTION__))
123 "Broken invariant")((AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots
.size() && "Broken invariant") ? static_cast<void>
(0) : __assert_fail ("AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots.size() && \"Broken invariant\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 123, __PRETTY_FUNCTION__))
;
124
125 for (; NextSlotToAllocate < NumSlots; NextSlotToAllocate++) {
126 if (!AllocatedStackSlots.test(NextSlotToAllocate)) {
127 const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
128 if (MFI.getObjectSize(FI) == SpillSize) {
129 AllocatedStackSlots.set(NextSlotToAllocate);
130 // TODO: Is ValueType the right thing to use here?
131 return Builder.DAG.getFrameIndex(FI, ValueType);
132 }
133 }
134 }
135
136 // Couldn't find a free slot, so create a new one:
137
138 SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
139 const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
140 MFI.markAsStatepointSpillSlotObjectIndex(FI);
141
142 Builder.FuncInfo.StatepointStackSlots.push_back(FI);
143 AllocatedStackSlots.resize(AllocatedStackSlots.size()+1, true);
144 assert(AllocatedStackSlots.size() ==((AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots
.size() && "Broken invariant") ? static_cast<void>
(0) : __assert_fail ("AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots.size() && \"Broken invariant\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 146, __PRETTY_FUNCTION__))
145 Builder.FuncInfo.StatepointStackSlots.size() &&((AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots
.size() && "Broken invariant") ? static_cast<void>
(0) : __assert_fail ("AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots.size() && \"Broken invariant\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 146, __PRETTY_FUNCTION__))
146 "Broken invariant")((AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots
.size() && "Broken invariant") ? static_cast<void>
(0) : __assert_fail ("AllocatedStackSlots.size() == Builder.FuncInfo.StatepointStackSlots.size() && \"Broken invariant\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 146, __PRETTY_FUNCTION__))
;
147
148 StatepointMaxSlotsRequired.updateMax(
149 Builder.FuncInfo.StatepointStackSlots.size());
150
151 return SpillSlot;
152}
153
154/// Utility function for reservePreviousStackSlotForValue. Tries to find
155/// stack slot index to which we have spilled value for previous statepoints.
156/// LookUpDepth specifies maximum DFS depth this function is allowed to look.
157static Optional<int> findPreviousSpillSlot(const Value *Val,
158 SelectionDAGBuilder &Builder,
159 int LookUpDepth) {
160 // Can not look any further - give up now
161 if (LookUpDepth <= 0)
162 return None;
163
164 // Spill location is known for gc relocates
165 if (const auto *Relocate = dyn_cast<GCRelocateInst>(Val)) {
166 const auto &RelocationMap =
167 Builder.FuncInfo.StatepointRelocationMaps[Relocate->getStatepoint()];
168
169 auto It = RelocationMap.find(Relocate->getDerivedPtr());
170 if (It == RelocationMap.end())
171 return None;
172
173 auto &Record = It->second;
174 if (Record.type != RecordType::Spill)
175 return None;
176
177 return Record.payload.FI;
178 }
179
180 // Look through bitcast instructions.
181 if (const BitCastInst *Cast = dyn_cast<BitCastInst>(Val))
182 return findPreviousSpillSlot(Cast->getOperand(0), Builder, LookUpDepth - 1);
183
184 // Look through phi nodes
185 // All incoming values should have same known stack slot, otherwise result
186 // is unknown.
187 if (const PHINode *Phi = dyn_cast<PHINode>(Val)) {
188 Optional<int> MergedResult = None;
189
190 for (auto &IncomingValue : Phi->incoming_values()) {
191 Optional<int> SpillSlot =
192 findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth - 1);
193 if (!SpillSlot.hasValue())
194 return None;
195
196 if (MergedResult.hasValue() && *MergedResult != *SpillSlot)
197 return None;
198
199 MergedResult = SpillSlot;
200 }
201 return MergedResult;
202 }
203
204 // TODO: We can do better for PHI nodes. In cases like this:
205 // ptr = phi(relocated_pointer, not_relocated_pointer)
206 // statepoint(ptr)
207 // We will return that stack slot for ptr is unknown. And later we might
208 // assign different stack slots for ptr and relocated_pointer. This limits
209 // llvm's ability to remove redundant stores.
210 // Unfortunately it's hard to accomplish in current infrastructure.
211 // We use this function to eliminate spill store completely, while
212 // in example we still need to emit store, but instead of any location
213 // we need to use special "preferred" location.
214
215 // TODO: handle simple updates. If a value is modified and the original
216 // value is no longer live, it would be nice to put the modified value in the
217 // same slot. This allows folding of the memory accesses for some
218 // instructions types (like an increment).
219 // statepoint (i)
220 // i1 = i+1
221 // statepoint (i1)
222 // However we need to be careful for cases like this:
223 // statepoint(i)
224 // i1 = i+1
225 // statepoint(i, i1)
226 // Here we want to reserve spill slot for 'i', but not for 'i+1'. If we just
227 // put handling of simple modifications in this function like it's done
228 // for bitcasts we might end up reserving i's slot for 'i+1' because order in
229 // which we visit values is unspecified.
230
231 // Don't know any information about this instruction
232 return None;
233}
234
235/// Return true if-and-only-if the given SDValue can be lowered as either a
236/// constant argument or a stack reference. The key point is that the value
237/// doesn't need to be spilled or tracked as a vreg use.
238static bool willLowerDirectly(SDValue Incoming) {
239 // We are making an unchecked assumption that the frame size <= 2^16 as that
240 // is the largest offset which can be encoded in the stackmap format.
241 if (isa<FrameIndexSDNode>(Incoming))
242 return true;
243
244 // The largest constant describeable in the StackMap format is 64 bits.
245 // Potential Optimization: Constants values are sign extended by consumer,
246 // and thus there are many constants of static type > 64 bits whose value
247 // happens to be sext(Con64) and could thus be lowered directly.
248 if (Incoming.getValueType().getSizeInBits() > 64)
249 return false;
250
251 return (isa<ConstantSDNode>(Incoming) || isa<ConstantFPSDNode>(Incoming) ||
252 Incoming.isUndef());
253}
254
255/// Try to find existing copies of the incoming values in stack slots used for
256/// statepoint spilling. If we can find a spill slot for the incoming value,
257/// mark that slot as allocated, and reuse the same slot for this safepoint.
258/// This helps to avoid series of loads and stores that only serve to reshuffle
259/// values on the stack between calls.
260static void reservePreviousStackSlotForValue(const Value *IncomingValue,
261 SelectionDAGBuilder &Builder) {
262 SDValue Incoming = Builder.getValue(IncomingValue);
263
264 // If we won't spill this, we don't need to check for previously allocated
265 // stack slots.
266 if (willLowerDirectly(Incoming))
267 return;
268
269 SDValue OldLocation = Builder.StatepointLowering.getLocation(Incoming);
270 if (OldLocation.getNode())
271 // Duplicates in input
272 return;
273
274 const int LookUpDepth = 6;
275 Optional<int> Index =
276 findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth);
277 if (!Index.hasValue())
278 return;
279
280 const auto &StatepointSlots = Builder.FuncInfo.StatepointStackSlots;
281
282 auto SlotIt = find(StatepointSlots, *Index);
283 assert(SlotIt != StatepointSlots.end() &&((SlotIt != StatepointSlots.end() && "Value spilled to the unknown stack slot"
) ? static_cast<void> (0) : __assert_fail ("SlotIt != StatepointSlots.end() && \"Value spilled to the unknown stack slot\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 284, __PRETTY_FUNCTION__))
284 "Value spilled to the unknown stack slot")((SlotIt != StatepointSlots.end() && "Value spilled to the unknown stack slot"
) ? static_cast<void> (0) : __assert_fail ("SlotIt != StatepointSlots.end() && \"Value spilled to the unknown stack slot\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 284, __PRETTY_FUNCTION__))
;
285
286 // This is one of our dedicated lowering slots
287 const int Offset = std::distance(StatepointSlots.begin(), SlotIt);
288 if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
289 // stack slot already assigned to someone else, can't use it!
290 // TODO: currently we reserve space for gc arguments after doing
291 // normal allocation for deopt arguments. We should reserve for
292 // _all_ deopt and gc arguments, then start allocating. This
293 // will prevent some moves being inserted when vm state changes,
294 // but gc state doesn't between two calls.
295 return;
296 }
297 // Reserve this stack slot
298 Builder.StatepointLowering.reserveStackSlot(Offset);
299
300 // Cache this slot so we find it when going through the normal
301 // assignment loop.
302 SDValue Loc =
303 Builder.DAG.getTargetFrameIndex(*Index, Builder.getFrameIndexTy());
304 Builder.StatepointLowering.setLocation(Incoming, Loc);
305}
306
307/// Extract call from statepoint, lower it and return pointer to the
308/// call node. Also update NodeMap so that getValue(statepoint) will
309/// reference lowered call result
310static std::pair<SDValue, SDNode *> lowerCallFromStatepointLoweringInfo(
311 SelectionDAGBuilder::StatepointLoweringInfo &SI,
312 SelectionDAGBuilder &Builder, SmallVectorImpl<SDValue> &PendingExports) {
313 SDValue ReturnValue, CallEndVal;
314 std::tie(ReturnValue, CallEndVal) =
315 Builder.lowerInvokable(SI.CLI, SI.EHPadBB);
316 SDNode *CallEnd = CallEndVal.getNode();
317
318 // Get a call instruction from the call sequence chain. Tail calls are not
319 // allowed. The following code is essentially reverse engineering X86's
320 // LowerCallTo.
321 //
322 // We are expecting DAG to have the following form:
323 //
324 // ch = eh_label (only in case of invoke statepoint)
325 // ch, glue = callseq_start ch
326 // ch, glue = X86::Call ch, glue
327 // ch, glue = callseq_end ch, glue
328 // get_return_value ch, glue
329 //
330 // get_return_value can either be a sequence of CopyFromReg instructions
331 // to grab the return value from the return register(s), or it can be a LOAD
332 // to load a value returned by reference via a stack slot.
333
334 bool HasDef = !SI.CLI.RetTy->isVoidTy();
335 if (HasDef) {
336 if (CallEnd->getOpcode() == ISD::LOAD)
337 CallEnd = CallEnd->getOperand(0).getNode();
338 else
339 while (CallEnd->getOpcode() == ISD::CopyFromReg)
340 CallEnd = CallEnd->getOperand(0).getNode();
341 }
342
343 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!")((CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!"
) ? static_cast<void> (0) : __assert_fail ("CallEnd->getOpcode() == ISD::CALLSEQ_END && \"expected!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 343, __PRETTY_FUNCTION__))
;
344 return std::make_pair(ReturnValue, CallEnd->getOperand(0).getNode());
345}
346
347static MachineMemOperand* getMachineMemOperand(MachineFunction &MF,
348 FrameIndexSDNode &FI) {
349 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FI.getIndex());
350 auto MMOFlags = MachineMemOperand::MOStore |
351 MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
352 auto &MFI = MF.getFrameInfo();
353 return MF.getMachineMemOperand(PtrInfo, MMOFlags,
354 MFI.getObjectSize(FI.getIndex()),
355 MFI.getObjectAlign(FI.getIndex()));
356}
357
358/// Spill a value incoming to the statepoint. It might be either part of
359/// vmstate
360/// or gcstate. In both cases unconditionally spill it on the stack unless it
361/// is a null constant. Return pair with first element being frame index
362/// containing saved value and second element with outgoing chain from the
363/// emitted store
364static std::tuple<SDValue, SDValue, MachineMemOperand*>
365spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
366 SelectionDAGBuilder &Builder) {
367 SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
368 MachineMemOperand* MMO = nullptr;
369
370 // Emit new store if we didn't do it for this ptr before
371 if (!Loc.getNode()) {
372 Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
373 Builder);
374 int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
375 // We use TargetFrameIndex so that isel will not select it into LEA
376 Loc = Builder.DAG.getTargetFrameIndex(Index, Builder.getFrameIndexTy());
377
378 // Right now we always allocate spill slots that are of the same
379 // size as the value we're about to spill (the size of spillee can
380 // vary since we spill vectors of pointers too). At some point we
381 // can consider allowing spills of smaller values to larger slots
382 // (i.e. change the '==' in the assert below to a '>=').
383 MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
384 assert((MFI.getObjectSize(Index) * 8) ==(((MFI.getObjectSize(Index) * 8) == (int64_t)Incoming.getValueSizeInBits
() && "Bad spill: stack slot does not match!") ? static_cast
<void> (0) : __assert_fail ("(MFI.getObjectSize(Index) * 8) == (int64_t)Incoming.getValueSizeInBits() && \"Bad spill: stack slot does not match!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 386, __PRETTY_FUNCTION__))
385 (int64_t)Incoming.getValueSizeInBits() &&(((MFI.getObjectSize(Index) * 8) == (int64_t)Incoming.getValueSizeInBits
() && "Bad spill: stack slot does not match!") ? static_cast
<void> (0) : __assert_fail ("(MFI.getObjectSize(Index) * 8) == (int64_t)Incoming.getValueSizeInBits() && \"Bad spill: stack slot does not match!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 386, __PRETTY_FUNCTION__))
386 "Bad spill: stack slot does not match!")(((MFI.getObjectSize(Index) * 8) == (int64_t)Incoming.getValueSizeInBits
() && "Bad spill: stack slot does not match!") ? static_cast
<void> (0) : __assert_fail ("(MFI.getObjectSize(Index) * 8) == (int64_t)Incoming.getValueSizeInBits() && \"Bad spill: stack slot does not match!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 386, __PRETTY_FUNCTION__))
;
387
388 // Note: Using the alignment of the spill slot (rather than the abi or
389 // preferred alignment) is required for correctness when dealing with spill
390 // slots with preferred alignments larger than frame alignment..
391 auto &MF = Builder.DAG.getMachineFunction();
392 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
393 auto *StoreMMO = MF.getMachineMemOperand(
394 PtrInfo, MachineMemOperand::MOStore, MFI.getObjectSize(Index),
395 MFI.getObjectAlign(Index));
396 Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
397 StoreMMO);
398
399 MMO = getMachineMemOperand(MF, *cast<FrameIndexSDNode>(Loc));
400
401 Builder.StatepointLowering.setLocation(Incoming, Loc);
402 }
403
404 assert(Loc.getNode())((Loc.getNode()) ? static_cast<void> (0) : __assert_fail
("Loc.getNode()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 404, __PRETTY_FUNCTION__))
;
405 return std::make_tuple(Loc, Chain, MMO);
406}
407
408/// Lower a single value incoming to a statepoint node. This value can be
409/// either a deopt value or a gc value, the handling is the same. We special
410/// case constants and allocas, then fall back to spilling if required.
411static void
412lowerIncomingStatepointValue(SDValue Incoming, bool RequireSpillSlot,
413 SmallVectorImpl<SDValue> &Ops,
414 SmallVectorImpl<MachineMemOperand *> &MemRefs,
415 SelectionDAGBuilder &Builder) {
416
417 if (willLowerDirectly(Incoming)) {
23
Taking true branch
418 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
24
Calling 'dyn_cast<llvm::FrameIndexSDNode, llvm::SDValue>'
39
Returning from 'dyn_cast<llvm::FrameIndexSDNode, llvm::SDValue>'
40
Assuming 'FI' is null
41
Taking false branch
419 // This handles allocas as arguments to the statepoint (this is only
420 // really meaningful for a deopt value. For GC, we'd be trying to
421 // relocate the address of the alloca itself?)
422 assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&((Incoming.getValueType() == Builder.getFrameIndexTy() &&
"Incoming value is a frame index!") ? static_cast<void>
(0) : __assert_fail ("Incoming.getValueType() == Builder.getFrameIndexTy() && \"Incoming value is a frame index!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 423, __PRETTY_FUNCTION__))
423 "Incoming value is a frame index!")((Incoming.getValueType() == Builder.getFrameIndexTy() &&
"Incoming value is a frame index!") ? static_cast<void>
(0) : __assert_fail ("Incoming.getValueType() == Builder.getFrameIndexTy() && \"Incoming value is a frame index!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 423, __PRETTY_FUNCTION__))
;
424 Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
425 Builder.getFrameIndexTy()));
426
427 auto &MF = Builder.DAG.getMachineFunction();
428 auto *MMO = getMachineMemOperand(MF, *FI);
429 MemRefs.push_back(MMO);
430 return;
431 }
432
433 assert(Incoming.getValueType().getSizeInBits() <= 64)((Incoming.getValueType().getSizeInBits() <= 64) ? static_cast
<void> (0) : __assert_fail ("Incoming.getValueType().getSizeInBits() <= 64"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 433, __PRETTY_FUNCTION__))
;
42
Calling 'SDValue::getValueType'
434
435 if (Incoming.isUndef()) {
436 // Put an easily recognized constant that's unlikely to be a valid
437 // value so that uses of undef by the consumer of the stackmap is
438 // easily recognized. This is legal since the compiler is always
439 // allowed to chose an arbitrary value for undef.
440 pushStackMapConstant(Ops, Builder, 0xFEFEFEFE);
441 return;
442 }
443
444 // If the original value was a constant, make sure it gets recorded as
445 // such in the stackmap. This is required so that the consumer can
446 // parse any internal format to the deopt state. It also handles null
447 // pointers and other constant pointers in GC states.
448 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
449 pushStackMapConstant(Ops, Builder, C->getSExtValue());
450 return;
451 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Incoming)) {
452 pushStackMapConstant(Ops, Builder,
453 C->getValueAPF().bitcastToAPInt().getZExtValue());
454 return;
455 }
456
457 llvm_unreachable("unhandled direct lowering case")::llvm::llvm_unreachable_internal("unhandled direct lowering case"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 457)
;
458 }
459
460
461
462 if (!RequireSpillSlot) {
463 // If this value is live in (not live-on-return, or live-through), we can
464 // treat it the same way patchpoint treats it's "live in" values. We'll
465 // end up folding some of these into stack references, but they'll be
466 // handled by the register allocator. Note that we do not have the notion
467 // of a late use so these values might be placed in registers which are
468 // clobbered by the call. This is fine for live-in. For live-through
469 // fix-up pass should be executed to force spilling of such registers.
470 Ops.push_back(Incoming);
471 } else {
472 // Otherwise, locate a spill slot and explicitly spill it so it can be
473 // found by the runtime later. Note: We know all of these spills are
474 // independent, but don't bother to exploit that chain wise. DAGCombine
475 // will happily do so as needed, so doing it here would be a small compile
476 // time win at most.
477 SDValue Chain = Builder.getRoot();
478 auto Res = spillIncomingStatepointValue(Incoming, Chain, Builder);
479 Ops.push_back(std::get<0>(Res));
480 if (auto *MMO = std::get<2>(Res))
481 MemRefs.push_back(MMO);
482 Chain = std::get<1>(Res);;
483 Builder.DAG.setRoot(Chain);
484 }
485
486}
487
488/// Lower deopt state and gc pointer arguments of the statepoint. The actual
489/// lowering is described in lowerIncomingStatepointValue. This function is
490/// responsible for lowering everything in the right position and playing some
491/// tricks to avoid redundant stack manipulation where possible. On
492/// completion, 'Ops' will contain ready to use operands for machine code
493/// statepoint. The chain nodes will have already been created and the DAG root
494/// will be set to the last value spilled (if any were).
495static void
496lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
497 SmallVectorImpl<MachineMemOperand *> &MemRefs,
498 DenseMap<SDValue, int> &LowerAsVReg,
499 SelectionDAGBuilder::StatepointLoweringInfo &SI,
500 SelectionDAGBuilder &Builder) {
501 // Lower the deopt and gc arguments for this statepoint. Layout will be:
502 // deopt argument length, deopt arguments.., gc arguments...
503#ifndef NDEBUG
504 if (auto *GFI = Builder.GFI) {
1
Assuming 'GFI' is null
2
Taking false branch
505 // Check that each of the gc pointer and bases we've gotten out of the
506 // safepoint is something the strategy thinks might be a pointer (or vector
507 // of pointers) into the GC heap. This is basically just here to help catch
508 // errors during statepoint insertion. TODO: This should actually be in the
509 // Verifier, but we can't get to the GCStrategy from there (yet).
510 GCStrategy &S = GFI->getStrategy();
511 for (const Value *V : SI.Bases) {
512 auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
513 if (Opt.hasValue()) {
514 assert(Opt.getValue() &&((Opt.getValue() && "non gc managed base pointer found in statepoint"
) ? static_cast<void> (0) : __assert_fail ("Opt.getValue() && \"non gc managed base pointer found in statepoint\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 515, __PRETTY_FUNCTION__))
515 "non gc managed base pointer found in statepoint")((Opt.getValue() && "non gc managed base pointer found in statepoint"
) ? static_cast<void> (0) : __assert_fail ("Opt.getValue() && \"non gc managed base pointer found in statepoint\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 515, __PRETTY_FUNCTION__))
;
516 }
517 }
518 for (const Value *V : SI.Ptrs) {
519 auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
520 if (Opt.hasValue()) {
521 assert(Opt.getValue() &&((Opt.getValue() && "non gc managed derived pointer found in statepoint"
) ? static_cast<void> (0) : __assert_fail ("Opt.getValue() && \"non gc managed derived pointer found in statepoint\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 522, __PRETTY_FUNCTION__))
522 "non gc managed derived pointer found in statepoint")((Opt.getValue() && "non gc managed derived pointer found in statepoint"
) ? static_cast<void> (0) : __assert_fail ("Opt.getValue() && \"non gc managed derived pointer found in statepoint\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 522, __PRETTY_FUNCTION__))
;
523 }
524 }
525 assert(SI.Bases.size() == SI.Ptrs.size() && "Pointer without base!")((SI.Bases.size() == SI.Ptrs.size() && "Pointer without base!"
) ? static_cast<void> (0) : __assert_fail ("SI.Bases.size() == SI.Ptrs.size() && \"Pointer without base!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 525, __PRETTY_FUNCTION__))
;
526 } else {
527 assert(SI.Bases.empty() && "No gc specified, so cannot relocate pointers!")((SI.Bases.empty() && "No gc specified, so cannot relocate pointers!"
) ? static_cast<void> (0) : __assert_fail ("SI.Bases.empty() && \"No gc specified, so cannot relocate pointers!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 527, __PRETTY_FUNCTION__))
;
3
'?' condition is true
528 assert(SI.Ptrs.empty() && "No gc specified, so cannot relocate pointers!")((SI.Ptrs.empty() && "No gc specified, so cannot relocate pointers!"
) ? static_cast<void> (0) : __assert_fail ("SI.Ptrs.empty() && \"No gc specified, so cannot relocate pointers!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 528, __PRETTY_FUNCTION__))
;
4
'?' condition is true
529 }
530#endif
531
532 // Figure out what lowering strategy we're going to use for each part
533 // Note: Is is conservatively correct to lower both "live-in" and "live-out"
534 // as "live-through". A "live-through" variable is one which is "live-in",
535 // "live-out", and live throughout the lifetime of the call (i.e. we can find
536 // it from any PC within the transitive callee of the statepoint). In
537 // particular, if the callee spills callee preserved registers we may not
538 // be able to find a value placed in that register during the call. This is
539 // fine for live-out, but not for live-through. If we were willing to make
540 // assumptions about the code generator producing the callee, we could
541 // potentially allow live-through values in callee saved registers.
542 const bool LiveInDeopt =
543 SI.StatepointFlags & (uint64_t)StatepointFlags::DeoptLiveIn;
544
545 // Decide which deriver pointers will go on VRegs
546 const unsigned MaxTiedRegs = 15; // Max number of tied regs MI can have.
547 unsigned MaxVRegPtrs =
548 std::min(MaxTiedRegs, MaxRegistersForGCPointers.getValue());
549
550 LLVM_DEBUG(dbgs() << "Desiding how to lower GC Pointers:\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << "Desiding how to lower GC Pointers:\n"
; } } while (false)
;
5
Assuming 'DebugFlag' is false
6
Loop condition is false. Exiting loop
551 unsigned CurNumVRegs = 0;
552 for (const Value *P : SI.Ptrs) {
7
Assuming '__begin1' is equal to '__end1'
553 if (LowerAsVReg.size() == MaxVRegPtrs)
554 break;
555 SDValue PtrSD = Builder.getValue(P);
556 if (willLowerDirectly(PtrSD) || P->getType()->isVectorTy()) {
557 LLVM_DEBUG(dbgs() << "direct/spill "; PtrSD.dump(&Builder.DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << "direct/spill "; PtrSD
.dump(&Builder.DAG); } } while (false)
;
558 continue;
559 }
560 LLVM_DEBUG(dbgs() << "vreg "; PtrSD.dump(&Builder.DAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << "vreg "; PtrSD.dump
(&Builder.DAG); } } while (false)
;
561 LowerAsVReg[PtrSD] = CurNumVRegs++;
562 }
563 LLVM_DEBUG(dbgs() << LowerAsVReg.size()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << LowerAsVReg.size()
<< " derived pointers will go in vregs\n"; } } while (
false)
8
Assuming 'DebugFlag' is false
9
Loop condition is false. Exiting loop
564 << " derived pointers will go in vregs\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << LowerAsVReg.size()
<< " derived pointers will go in vregs\n"; } } while (
false)
;
565
566 auto isGCValue = [&](const Value *V) {
567 auto *Ty = V->getType();
568 if (!Ty->isPtrOrPtrVectorTy())
569 return false;
570 if (auto *GFI = Builder.GFI)
571 if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
572 return *IsManaged;
573 return true; // conservative
574 };
575
576 auto requireSpillSlot = [&](const Value *V) {
577 if (isGCValue(V))
578 return !LowerAsVReg.count(Builder.getValue(V));
579 return !(LiveInDeopt || UseRegistersForDeoptValues);
580 };
581
582 // Before we actually start lowering (and allocating spill slots for values),
583 // reserve any stack slots which we judge to be profitable to reuse for a
584 // particular value. This is purely an optimization over the code below and
585 // doesn't change semantics at all. It is important for performance that we
586 // reserve slots for both deopt and gc values before lowering either.
587 for (const Value *V : SI.DeoptState) {
10
Assuming '__begin1' is equal to '__end1'
588 if (requireSpillSlot(V))
589 reservePreviousStackSlotForValue(V, Builder);
590 }
591
592 for (unsigned i = 0; i < SI.Bases.size(); ++i) {
11
Assuming the condition is false
12
Loop condition is false. Execution continues on line 604
593 SDValue SDV = Builder.getValue(SI.Bases[i]);
594 if (AlwaysSpillBase || !LowerAsVReg.count(SDV))
595 reservePreviousStackSlotForValue(SI.Bases[i], Builder);
596 SDV = Builder.getValue(SI.Ptrs[i]);
597 if (!LowerAsVReg.count(SDV))
598 reservePreviousStackSlotForValue(SI.Ptrs[i], Builder);
599 }
600
601 // First, prefix the list with the number of unique values to be
602 // lowered. Note that this is the number of *Values* not the
603 // number of SDValues required to lower them.
604 const int NumVMSArgs = SI.DeoptState.size();
605 pushStackMapConstant(Ops, Builder, NumVMSArgs);
606
607 // The vm state arguments are lowered in an opaque manner. We do not know
608 // what type of values are contained within.
609 LLVM_DEBUG(dbgs() << "Lowering deopt state\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << "Lowering deopt state\n"
; } } while (false)
;
13
Assuming 'DebugFlag' is false
14
Loop condition is false. Exiting loop
610 for (const Value *V : SI.DeoptState) {
15
Assuming '__begin1' is not equal to '__end1'
611 SDValue Incoming;
612 // If this is a function argument at a static frame index, generate it as
613 // the frame index.
614 if (const Argument *Arg
16.1
'Arg' is null
16.1
'Arg' is null
16.1
'Arg' is null
= dyn_cast<Argument>(V)) {
16
Assuming 'V' is not a 'Argument'
17
Taking false branch
615 int FI = Builder.FuncInfo.getArgumentFrameIndex(Arg);
616 if (FI != INT_MAX2147483647)
617 Incoming = Builder.DAG.getFrameIndex(FI, Builder.getFrameIndexTy());
618 }
619 if (!Incoming.getNode())
18
Taking true branch
620 Incoming = Builder.getValue(V);
621 LLVM_DEBUG(dbgs() << "Value " << *Vdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << "Value " << *
V << " requireSpillSlot = " << requireSpillSlot(V
) << "\n"; } } while (false)
19
Assuming 'DebugFlag' is false
20
Loop condition is false. Exiting loop
622 << " requireSpillSlot = " << requireSpillSlot(V) << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << "Value " << *
V << " requireSpillSlot = " << requireSpillSlot(V
) << "\n"; } } while (false)
;
623 lowerIncomingStatepointValue(Incoming, requireSpillSlot(V), Ops, MemRefs,
21
Value assigned to 'Incoming.Node'
22
Calling 'lowerIncomingStatepointValue'
624 Builder);
625 }
626
627 // Finally, go ahead and lower all the gc arguments. There's no prefixed
628 // length for this one. After lowering, we'll have the base and pointer
629 // arrays interwoven with each (lowered) base pointer immediately followed by
630 // it's (lowered) derived pointer. i.e
631 // (base[0], ptr[0], base[1], ptr[1], ...)
632 for (unsigned i = 0; i < SI.Bases.size(); ++i) {
633 bool RequireSpillSlot;
634 SDValue Base = Builder.getValue(SI.Bases[i]);
635 RequireSpillSlot = AlwaysSpillBase || !LowerAsVReg.count(Base);
636 lowerIncomingStatepointValue(Base, RequireSpillSlot, Ops, MemRefs,
637 Builder);
638
639 SDValue Derived = Builder.getValue(SI.Ptrs[i]);
640 RequireSpillSlot = !LowerAsVReg.count(Derived);
641 lowerIncomingStatepointValue(Derived, RequireSpillSlot, Ops, MemRefs,
642 Builder);
643 }
644
645 // If there are any explicit spill slots passed to the statepoint, record
646 // them, but otherwise do not do anything special. These are user provided
647 // allocas and give control over placement to the consumer. In this case,
648 // it is the contents of the slot which may get updated, not the pointer to
649 // the alloca
650 for (Value *V : SI.GCArgs) {
651 SDValue Incoming = Builder.getValue(V);
652 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
653 // This handles allocas as arguments to the statepoint
654 assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&((Incoming.getValueType() == Builder.getFrameIndexTy() &&
"Incoming value is a frame index!") ? static_cast<void>
(0) : __assert_fail ("Incoming.getValueType() == Builder.getFrameIndexTy() && \"Incoming value is a frame index!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 655, __PRETTY_FUNCTION__))
655 "Incoming value is a frame index!")((Incoming.getValueType() == Builder.getFrameIndexTy() &&
"Incoming value is a frame index!") ? static_cast<void>
(0) : __assert_fail ("Incoming.getValueType() == Builder.getFrameIndexTy() && \"Incoming value is a frame index!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 655, __PRETTY_FUNCTION__))
;
656 Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
657 Builder.getFrameIndexTy()));
658
659 auto &MF = Builder.DAG.getMachineFunction();
660 auto *MMO = getMachineMemOperand(MF, *FI);
661 MemRefs.push_back(MMO);
662 }
663 }
664}
665
666SDValue SelectionDAGBuilder::LowerAsSTATEPOINT(
667 SelectionDAGBuilder::StatepointLoweringInfo &SI) {
668 // The basic scheme here is that information about both the original call and
669 // the safepoint is encoded in the CallInst. We create a temporary call and
670 // lower it, then reverse engineer the calling sequence.
671
672 NumOfStatepoints++;
673 // Clear state
674 StatepointLowering.startNewStatepoint(*this);
675 assert(SI.Bases.size() == SI.Ptrs.size() &&((SI.Bases.size() == SI.Ptrs.size() && SI.Ptrs.size()
<= SI.GCRelocates.size()) ? static_cast<void> (0) :
__assert_fail ("SI.Bases.size() == SI.Ptrs.size() && SI.Ptrs.size() <= SI.GCRelocates.size()"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 676, __PRETTY_FUNCTION__))
676 SI.Ptrs.size() <= SI.GCRelocates.size())((SI.Bases.size() == SI.Ptrs.size() && SI.Ptrs.size()
<= SI.GCRelocates.size()) ? static_cast<void> (0) :
__assert_fail ("SI.Bases.size() == SI.Ptrs.size() && SI.Ptrs.size() <= SI.GCRelocates.size()"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 676, __PRETTY_FUNCTION__))
;
677
678 LLVM_DEBUG(dbgs() << "Lowering statepoint " << *SI.StatepointInstr << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << "Lowering statepoint "
<< *SI.StatepointInstr << "\n"; } } while (false
)
;
679#ifndef NDEBUG
680 for (auto *Reloc : SI.GCRelocates)
681 if (Reloc->getParent() == SI.StatepointInstr->getParent())
682 StatepointLowering.scheduleRelocCall(*Reloc);
683#endif
684
685 // Lower statepoint vmstate and gcstate arguments
686 SmallVector<SDValue, 10> LoweredMetaArgs;
687 SmallVector<MachineMemOperand*, 16> MemRefs;
688 // Maps derived pointer SDValue to statepoint result of relocated pointer.
689 DenseMap<SDValue, int> LowerAsVReg;
690 lowerStatepointMetaArgs(LoweredMetaArgs, MemRefs, LowerAsVReg, SI, *this);
691
692 // Now that we've emitted the spills, we need to update the root so that the
693 // call sequence is ordered correctly.
694 SI.CLI.setChain(getRoot());
695
696 // Get call node, we will replace it later with statepoint
697 SDValue ReturnVal;
698 SDNode *CallNode;
699 std::tie(ReturnVal, CallNode) =
700 lowerCallFromStatepointLoweringInfo(SI, *this, PendingExports);
701
702 // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
703 // nodes with all the appropriate arguments and return values.
704
705 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
706 SDValue Chain = CallNode->getOperand(0);
707
708 SDValue Glue;
709 bool CallHasIncomingGlue = CallNode->getGluedNode();
710 if (CallHasIncomingGlue) {
711 // Glue is always last operand
712 Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
713 }
714
715 // Build the GC_TRANSITION_START node if necessary.
716 //
717 // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
718 // order in which they appear in the call to the statepoint intrinsic. If
719 // any of the operands is a pointer-typed, that operand is immediately
720 // followed by a SRCVALUE for the pointer that may be used during lowering
721 // (e.g. to form MachinePointerInfo values for loads/stores).
722 const bool IsGCTransition =
723 (SI.StatepointFlags & (uint64_t)StatepointFlags::GCTransition) ==
724 (uint64_t)StatepointFlags::GCTransition;
725 if (IsGCTransition) {
726 SmallVector<SDValue, 8> TSOps;
727
728 // Add chain
729 TSOps.push_back(Chain);
730
731 // Add GC transition arguments
732 for (const Value *V : SI.GCTransitionArgs) {
733 TSOps.push_back(getValue(V));
734 if (V->getType()->isPointerTy())
735 TSOps.push_back(DAG.getSrcValue(V));
736 }
737
738 // Add glue if necessary
739 if (CallHasIncomingGlue)
740 TSOps.push_back(Glue);
741
742 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
743
744 SDValue GCTransitionStart =
745 DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
746
747 Chain = GCTransitionStart.getValue(0);
748 Glue = GCTransitionStart.getValue(1);
749 }
750
751 // TODO: Currently, all of these operands are being marked as read/write in
752 // PrologEpilougeInserter.cpp, we should special case the VMState arguments
753 // and flags to be read-only.
754 SmallVector<SDValue, 40> Ops;
755
756 // Add the <id> and <numBytes> constants.
757 Ops.push_back(DAG.getTargetConstant(SI.ID, getCurSDLoc(), MVT::i64));
758 Ops.push_back(
759 DAG.getTargetConstant(SI.NumPatchBytes, getCurSDLoc(), MVT::i32));
760
761 // Calculate and push starting position of vmstate arguments
762 // Get number of arguments incoming directly into call node
763 unsigned NumCallRegArgs =
764 CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
765 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
766
767 // Add call target
768 SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
769 Ops.push_back(CallTarget);
770
771 // Add call arguments
772 // Get position of register mask in the call
773 SDNode::op_iterator RegMaskIt;
774 if (CallHasIncomingGlue)
775 RegMaskIt = CallNode->op_end() - 2;
776 else
777 RegMaskIt = CallNode->op_end() - 1;
778 Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
779
780 // Add a constant argument for the calling convention
781 pushStackMapConstant(Ops, *this, SI.CLI.CallConv);
782
783 // Add a constant argument for the flags
784 uint64_t Flags = SI.StatepointFlags;
785 assert(((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&((((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
"Unknown flag used") ? static_cast<void> (0) : __assert_fail
("((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) && \"Unknown flag used\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 786, __PRETTY_FUNCTION__))
786 "Unknown flag used")((((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
"Unknown flag used") ? static_cast<void> (0) : __assert_fail
("((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) && \"Unknown flag used\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 786, __PRETTY_FUNCTION__))
;
787 pushStackMapConstant(Ops, *this, Flags);
788
789 // Insert all vmstate and gcstate arguments
790 Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
791
792 // Add register mask from call node
793 Ops.push_back(*RegMaskIt);
794
795 // Add chain
796 Ops.push_back(Chain);
797
798 // Same for the glue, but we add it only if original call had it
799 if (Glue.getNode())
800 Ops.push_back(Glue);
801
802 // Compute return values. Provide a glue output since we consume one as
803 // input. This allows someone else to chain off us as needed.
804 SmallVector<EVT, 8> NodeTys;
805 for (auto &Ptr : SI.Ptrs) {
806 SDValue SD = getValue(Ptr);
807 if (!LowerAsVReg.count(SD))
808 continue;
809 NodeTys.push_back(SD.getValueType());
810 }
811 LLVM_DEBUG(dbgs() << "Statepoint has " << NodeTys.size() << " results\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("statepoint-lowering")) { dbgs() << "Statepoint has " <<
NodeTys.size() << " results\n"; } } while (false)
;
812 assert(NodeTys.size() == LowerAsVReg.size() && "Inconsistent GC Ptr lowering")((NodeTys.size() == LowerAsVReg.size() && "Inconsistent GC Ptr lowering"
) ? static_cast<void> (0) : __assert_fail ("NodeTys.size() == LowerAsVReg.size() && \"Inconsistent GC Ptr lowering\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 812, __PRETTY_FUNCTION__))
;
813 NodeTys.push_back(MVT::Other);
814 NodeTys.push_back(MVT::Glue);
815
816 unsigned NumResults = NodeTys.size();
817 MachineSDNode *StatepointMCNode =
818 DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
819 DAG.setNodeMemRefs(StatepointMCNode, MemRefs);
820
821
822 // For values lowered to tied-defs, create the virtual registers. Note that
823 // for simplicity, we *always* create a vreg even within a single block.
824 DenseMap<const Value *, Register> VirtRegs;
825 for (const auto *Relocate : SI.GCRelocates) {
826 Value *Derived = Relocate->getDerivedPtr();
827 SDValue SD = getValue(Derived);
828 if (!LowerAsVReg.count(SD))
829 continue;
830
831 // Handle multiple gc.relocates of the same input efficiently.
832 if (VirtRegs.count(Derived))
833 continue;
834
835 SDValue Relocated = SDValue(StatepointMCNode, LowerAsVReg[SD]);
836
837 auto *RetTy = Relocate->getType();
838 Register Reg = FuncInfo.CreateRegs(RetTy);
839 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
840 DAG.getDataLayout(), Reg, RetTy, None);
841 SDValue Chain = DAG.getRoot();
842 RFV.getCopyToRegs(Relocated, DAG, getCurSDLoc(), Chain, nullptr);
843 PendingExports.push_back(Chain);
844
845 VirtRegs[Derived] = Reg;
846 }
847
848 // Record for later use how each relocation was lowered. This is needed to
849 // allow later gc.relocates to mirror the lowering chosen.
850 const Instruction *StatepointInstr = SI.StatepointInstr;
851 auto &RelocationMap = FuncInfo.StatepointRelocationMaps[StatepointInstr];
852 for (const GCRelocateInst *Relocate : SI.GCRelocates) {
853 const Value *V = Relocate->getDerivedPtr();
854 SDValue SDV = getValue(V);
855 SDValue Loc = StatepointLowering.getLocation(SDV);
856
857 RecordType Record;
858 if (LowerAsVReg.count(SDV)) {
859 Record.type = RecordType::VReg;
860 assert(VirtRegs.count(V))((VirtRegs.count(V)) ? static_cast<void> (0) : __assert_fail
("VirtRegs.count(V)", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 860, __PRETTY_FUNCTION__))
;
861 Record.payload.Reg = VirtRegs[V];
862 } else if (Loc.getNode()) {
863 Record.type = RecordType::Spill;
864 Record.payload.FI = cast<FrameIndexSDNode>(Loc)->getIndex();
865 } else {
866 Record.type = RecordType::NoRelocate;
867 // If we didn't relocate a value, we'll essentialy end up inserting an
868 // additional use of the original value when lowering the gc.relocate.
869 // We need to make sure the value is available at the new use, which
870 // might be in another block.
871 if (Relocate->getParent() != StatepointInstr->getParent())
872 ExportFromCurrentBlock(V);
873 }
874 RelocationMap[V] = Record;
875 }
876
877
878
879 SDNode *SinkNode = StatepointMCNode;
880
881 // Build the GC_TRANSITION_END node if necessary.
882 //
883 // See the comment above regarding GC_TRANSITION_START for the layout of
884 // the operands to the GC_TRANSITION_END node.
885 if (IsGCTransition) {
886 SmallVector<SDValue, 8> TEOps;
887
888 // Add chain
889 TEOps.push_back(SDValue(StatepointMCNode, NumResults - 2));
890
891 // Add GC transition arguments
892 for (const Value *V : SI.GCTransitionArgs) {
893 TEOps.push_back(getValue(V));
894 if (V->getType()->isPointerTy())
895 TEOps.push_back(DAG.getSrcValue(V));
896 }
897
898 // Add glue
899 TEOps.push_back(SDValue(StatepointMCNode, NumResults - 1));
900
901 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
902
903 SDValue GCTransitionStart =
904 DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
905
906 SinkNode = GCTransitionStart.getNode();
907 }
908
909 // Replace original call
910 // Call: ch,glue = CALL ...
911 // Statepoint: [gc relocates],ch,glue = STATEPOINT ...
912 unsigned NumSinkValues = SinkNode->getNumValues();
913 SDValue StatepointValues[2] = {SDValue(SinkNode, NumSinkValues - 2),
914 SDValue(SinkNode, NumSinkValues - 1)};
915 DAG.ReplaceAllUsesWith(CallNode, StatepointValues);
916 // Remove original call node
917 DAG.DeleteNode(CallNode);
918
919 // Since we always emit CopyToRegs (even for local relocates), we must
920 // update root, so that they are emitted before any local uses.
921 (void)getControlRoot();
922
923 // TODO: A better future implementation would be to emit a single variable
924 // argument, variable return value STATEPOINT node here and then hookup the
925 // return value of each gc.relocate to the respective output of the
926 // previously emitted STATEPOINT value. Unfortunately, this doesn't appear
927 // to actually be possible today.
928
929 return ReturnVal;
930}
931
932void
933SelectionDAGBuilder::LowerStatepoint(const GCStatepointInst &I,
934 const BasicBlock *EHPadBB /*= nullptr*/) {
935 assert(I.getCallingConv() != CallingConv::AnyReg &&((I.getCallingConv() != CallingConv::AnyReg && "anyregcc is not supported on statepoints!"
) ? static_cast<void> (0) : __assert_fail ("I.getCallingConv() != CallingConv::AnyReg && \"anyregcc is not supported on statepoints!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 936, __PRETTY_FUNCTION__))
936 "anyregcc is not supported on statepoints!")((I.getCallingConv() != CallingConv::AnyReg && "anyregcc is not supported on statepoints!"
) ? static_cast<void> (0) : __assert_fail ("I.getCallingConv() != CallingConv::AnyReg && \"anyregcc is not supported on statepoints!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 936, __PRETTY_FUNCTION__))
;
937
938#ifndef NDEBUG
939 // Check that the associated GCStrategy expects to encounter statepoints.
940 assert(GFI->getStrategy().useStatepoints() &&((GFI->getStrategy().useStatepoints() && "GCStrategy does not expect to encounter statepoints"
) ? static_cast<void> (0) : __assert_fail ("GFI->getStrategy().useStatepoints() && \"GCStrategy does not expect to encounter statepoints\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 941, __PRETTY_FUNCTION__))
941 "GCStrategy does not expect to encounter statepoints")((GFI->getStrategy().useStatepoints() && "GCStrategy does not expect to encounter statepoints"
) ? static_cast<void> (0) : __assert_fail ("GFI->getStrategy().useStatepoints() && \"GCStrategy does not expect to encounter statepoints\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 941, __PRETTY_FUNCTION__))
;
942#endif
943
944 SDValue ActualCallee;
945 SDValue Callee = getValue(I.getActualCalledOperand());
946
947 if (I.getNumPatchBytes() > 0) {
948 // If we've been asked to emit a nop sequence instead of a call instruction
949 // for this statepoint then don't lower the call target, but use a constant
950 // `undef` instead. Not lowering the call target lets statepoint clients
951 // get away without providing a physical address for the symbolic call
952 // target at link time.
953 ActualCallee = DAG.getUNDEF(Callee.getValueType());
954 } else {
955 ActualCallee = Callee;
956 }
957
958 StatepointLoweringInfo SI(DAG);
959 populateCallLoweringInfo(SI.CLI, &I, GCStatepointInst::CallArgsBeginPos,
960 I.getNumCallArgs(), ActualCallee,
961 I.getActualReturnType(), false /* IsPatchPoint */);
962
963 // There may be duplication in the gc.relocate list; such as two copies of
964 // each relocation on normal and exceptional path for an invoke. We only
965 // need to spill once and record one copy in the stackmap, but we need to
966 // reload once per gc.relocate. (Dedupping gc.relocates is trickier and best
967 // handled as a CSE problem elsewhere.)
968 // TODO: There a couple of major stackmap size optimizations we could do
969 // here if we wished.
970 // 1) If we've encountered a derived pair {B, D}, we don't need to actually
971 // record {B,B} if it's seen later.
972 // 2) Due to rematerialization, actual derived pointers are somewhat rare;
973 // given that, we could change the format to record base pointer relocations
974 // separately with half the space. This would require a format rev and a
975 // fairly major rework of the STATEPOINT node though.
976 SmallSet<SDValue, 8> Seen;
977 for (const GCRelocateInst *Relocate : I.getGCRelocates()) {
978 SI.GCRelocates.push_back(Relocate);
979
980 SDValue DerivedSD = getValue(Relocate->getDerivedPtr());
981 if (Seen.insert(DerivedSD).second) {
982 SI.Bases.push_back(Relocate->getBasePtr());
983 SI.Ptrs.push_back(Relocate->getDerivedPtr());
984 }
985 }
986
987 SI.GCArgs = ArrayRef<const Use>(I.gc_args_begin(), I.gc_args_end());
988 SI.StatepointInstr = &I;
989 SI.ID = I.getID();
990
991 SI.DeoptState = ArrayRef<const Use>(I.deopt_begin(), I.deopt_end());
992 SI.GCTransitionArgs = ArrayRef<const Use>(I.gc_transition_args_begin(),
993 I.gc_transition_args_end());
994
995 SI.StatepointFlags = I.getFlags();
996 SI.NumPatchBytes = I.getNumPatchBytes();
997 SI.EHPadBB = EHPadBB;
998
999 SDValue ReturnValue = LowerAsSTATEPOINT(SI);
1000
1001 // Export the result value if needed
1002 const GCResultInst *GCResult = I.getGCResult();
1003 Type *RetTy = I.getActualReturnType();
1004
1005 if (RetTy->isVoidTy() || !GCResult) {
1006 // The return value is not needed, just generate a poison value.
1007 setValue(&I, DAG.getIntPtrConstant(-1, getCurSDLoc()));
1008 return;
1009 }
1010
1011 if (GCResult->getParent() == I.getParent()) {
1012 // Result value will be used in a same basic block. Don't export it or
1013 // perform any explicit register copies. The gc_result will simply grab
1014 // this value.
1015 setValue(&I, ReturnValue);
1016 return;
1017 }
1018
1019 // Result value will be used in a different basic block so we need to export
1020 // it now. Default exporting mechanism will not work here because statepoint
1021 // call has a different type than the actual call. It means that by default
1022 // llvm will create export register of the wrong type (always i32 in our
1023 // case). So instead we need to create export register with correct type
1024 // manually.
1025 // TODO: To eliminate this problem we can remove gc.result intrinsics
1026 // completely and make statepoint call to return a tuple.
1027 unsigned Reg = FuncInfo.CreateRegs(RetTy);
1028 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1029 DAG.getDataLayout(), Reg, RetTy,
1030 I.getCallingConv());
1031 SDValue Chain = DAG.getEntryNode();
1032
1033 RFV.getCopyToRegs(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
1034 PendingExports.push_back(Chain);
1035 FuncInfo.ValueMap[&I] = Reg;
1036}
1037
1038void SelectionDAGBuilder::LowerCallSiteWithDeoptBundleImpl(
1039 const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB,
1040 bool VarArgDisallowed, bool ForceVoidReturnTy) {
1041 StatepointLoweringInfo SI(DAG);
1042 unsigned ArgBeginIndex = Call->arg_begin() - Call->op_begin();
1043 populateCallLoweringInfo(
1044 SI.CLI, Call, ArgBeginIndex, Call->getNumArgOperands(), Callee,
1045 ForceVoidReturnTy ? Type::getVoidTy(*DAG.getContext()) : Call->getType(),
1046 false);
1047 if (!VarArgDisallowed)
1048 SI.CLI.IsVarArg = Call->getFunctionType()->isVarArg();
1049
1050 auto DeoptBundle = *Call->getOperandBundle(LLVMContext::OB_deopt);
1051
1052 unsigned DefaultID = StatepointDirectives::DeoptBundleStatepointID;
1053
1054 auto SD = parseStatepointDirectivesFromAttrs(Call->getAttributes());
1055 SI.ID = SD.StatepointID.getValueOr(DefaultID);
1056 SI.NumPatchBytes = SD.NumPatchBytes.getValueOr(0);
1057
1058 SI.DeoptState =
1059 ArrayRef<const Use>(DeoptBundle.Inputs.begin(), DeoptBundle.Inputs.end());
1060 SI.StatepointFlags = static_cast<uint64_t>(StatepointFlags::None);
1061 SI.EHPadBB = EHPadBB;
1062
1063 // NB! The GC arguments are deliberately left empty.
1064
1065 if (SDValue ReturnVal = LowerAsSTATEPOINT(SI)) {
1066 ReturnVal = lowerRangeToAssertZExt(DAG, *Call, ReturnVal);
1067 setValue(Call, ReturnVal);
1068 }
1069}
1070
1071void SelectionDAGBuilder::LowerCallSiteWithDeoptBundle(
1072 const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB) {
1073 LowerCallSiteWithDeoptBundleImpl(Call, Callee, EHPadBB,
1074 /* VarArgDisallowed = */ false,
1075 /* ForceVoidReturnTy = */ false);
1076}
1077
1078void SelectionDAGBuilder::visitGCResult(const GCResultInst &CI) {
1079 // The result value of the gc_result is simply the result of the actual
1080 // call. We've already emitted this, so just grab the value.
1081 const GCStatepointInst *SI = CI.getStatepoint();
1082
1083 if (SI->getParent() == CI.getParent()) {
1084 setValue(&CI, getValue(SI));
1085 return;
1086 }
1087 // Statepoint is in different basic block so we should have stored call
1088 // result in a virtual register.
1089 // We can not use default getValue() functionality to copy value from this
1090 // register because statepoint and actual call return types can be
1091 // different, and getValue() will use CopyFromReg of the wrong type,
1092 // which is always i32 in our case.
1093 Type *RetTy = SI->getActualReturnType();
1094 SDValue CopyFromReg = getCopyFromRegs(SI, RetTy);
1095
1096 assert(CopyFromReg.getNode())((CopyFromReg.getNode()) ? static_cast<void> (0) : __assert_fail
("CopyFromReg.getNode()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 1096, __PRETTY_FUNCTION__))
;
1097 setValue(&CI, CopyFromReg);
1098}
1099
1100void SelectionDAGBuilder::visitGCRelocate(const GCRelocateInst &Relocate) {
1101#ifndef NDEBUG
1102 // Consistency check
1103 // We skip this check for relocates not in the same basic block as their
1104 // statepoint. It would be too expensive to preserve validation info through
1105 // different basic blocks.
1106 if (Relocate.getStatepoint()->getParent() == Relocate.getParent())
1107 StatepointLowering.relocCallVisited(Relocate);
1108
1109 auto *Ty = Relocate.getType()->getScalarType();
1110 if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
1111 assert(*IsManaged && "Non gc managed pointer relocated!")((*IsManaged && "Non gc managed pointer relocated!") ?
static_cast<void> (0) : __assert_fail ("*IsManaged && \"Non gc managed pointer relocated!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 1111, __PRETTY_FUNCTION__))
;
1112#endif
1113
1114 const Value *DerivedPtr = Relocate.getDerivedPtr();
1115 auto &RelocationMap =
1116 FuncInfo.StatepointRelocationMaps[Relocate.getStatepoint()];
1117 auto SlotIt = RelocationMap.find(DerivedPtr);
1118 assert(SlotIt != RelocationMap.end() && "Relocating not lowered gc value")((SlotIt != RelocationMap.end() && "Relocating not lowered gc value"
) ? static_cast<void> (0) : __assert_fail ("SlotIt != RelocationMap.end() && \"Relocating not lowered gc value\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 1118, __PRETTY_FUNCTION__))
;
1119 const RecordType &Record = SlotIt->second;
1120
1121 // If relocation was done via virtual register..
1122 if (Record.type == RecordType::VReg) {
1123 Register InReg = Record.payload.Reg;
1124 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1125 DAG.getDataLayout(), InReg, Relocate.getType(),
1126 None); // This is not an ABI copy.
1127 SDValue Chain = DAG.getEntryNode();
1128 SDValue Relocation = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
1129 Chain, nullptr, nullptr);
1130 setValue(&Relocate, Relocation);
1131 return;
1132 }
1133
1134 SDValue SD = getValue(DerivedPtr);
1135
1136 if (SD.isUndef() && SD.getValueType().getSizeInBits() <= 64) {
1137 // Lowering relocate(undef) as arbitrary constant. Current constant value
1138 // is chosen such that it's unlikely to be a valid pointer.
1139 setValue(&Relocate, DAG.getTargetConstant(0xFEFEFEFE, SDLoc(SD), MVT::i64));
1140 return;
1141 }
1142
1143
1144 // We didn't need to spill these special cases (constants and allocas).
1145 // See the handling in spillIncomingValueForStatepoint for detail.
1146 if (Record.type == RecordType::NoRelocate) {
1147 setValue(&Relocate, SD);
1148 return;
1149 }
1150
1151 assert(Record.type == RecordType::Spill)((Record.type == RecordType::Spill) ? static_cast<void>
(0) : __assert_fail ("Record.type == RecordType::Spill", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 1151, __PRETTY_FUNCTION__))
;
1152
1153 unsigned Index = Record.payload.FI;;
1154 SDValue SpillSlot = DAG.getTargetFrameIndex(Index, getFrameIndexTy());
1155
1156 // All the reloads are independent and are reading memory only modified by
1157 // statepoints (i.e. no other aliasing stores); informing SelectionDAG of
1158 // this this let's CSE kick in for free and allows reordering of instructions
1159 // if possible. The lowering for statepoint sets the root, so this is
1160 // ordering all reloads with the either a) the statepoint node itself, or b)
1161 // the entry of the current block for an invoke statepoint.
1162 const SDValue Chain = DAG.getRoot(); // != Builder.getRoot()
1163
1164 auto &MF = DAG.getMachineFunction();
1165 auto &MFI = MF.getFrameInfo();
1166 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
1167 auto *LoadMMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
1168 MFI.getObjectSize(Index),
1169 MFI.getObjectAlign(Index));
1170
1171 auto LoadVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
1172 Relocate.getType());
1173
1174 SDValue SpillLoad = DAG.getLoad(LoadVT, getCurSDLoc(), Chain,
1175 SpillSlot, LoadMMO);
1176 PendingLoads.push_back(SpillLoad.getValue(1));
1177
1178 assert(SpillLoad.getNode())((SpillLoad.getNode()) ? static_cast<void> (0) : __assert_fail
("SpillLoad.getNode()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp"
, 1178, __PRETTY_FUNCTION__))
;
1179 setValue(&Relocate, SpillLoad);
1180}
1181
1182void SelectionDAGBuilder::LowerDeoptimizeCall(const CallInst *CI) {
1183 const auto &TLI = DAG.getTargetLoweringInfo();
1184 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(RTLIB::DEOPTIMIZE),
1185 TLI.getPointerTy(DAG.getDataLayout()));
1186
1187 // We don't lower calls to __llvm_deoptimize as varargs, but as a regular
1188 // call. We also do not lower the return value to any virtual register, and
1189 // change the immediately following return to a trap instruction.
1190 LowerCallSiteWithDeoptBundleImpl(CI, Callee, /* EHPadBB = */ nullptr,
1191 /* VarArgDisallowed = */ true,
1192 /* ForceVoidReturnTy = */ true);
1193}
1194
1195void SelectionDAGBuilder::LowerDeoptimizingReturn() {
1196 // We do not lower the return value from llvm.deoptimize to any virtual
1197 // register, and change the immediately following return to a trap
1198 // instruction.
1199 if (DAG.getTarget().Options.TrapUnreachable)
1200 DAG.setRoot(
1201 DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
1202}

/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- 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 defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
10// and dyn_cast_or_null<X>() templates.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_CASTING_H
15#define LLVM_SUPPORT_CASTING_H
16
17#include "llvm/Support/Compiler.h"
18#include "llvm/Support/type_traits.h"
19#include <cassert>
20#include <memory>
21#include <type_traits>
22
23namespace llvm {
24
25//===----------------------------------------------------------------------===//
26// isa<x> Support Templates
27//===----------------------------------------------------------------------===//
28
29// Define a template that can be specialized by smart pointers to reflect the
30// fact that they are automatically dereferenced, and are not involved with the
31// template selection process... the default implementation is a noop.
32//
33template<typename From> struct simplify_type {
34 using SimpleType = From; // The real type this represents...
35
36 // An accessor to get the real value...
37 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
38};
39
40template<typename From> struct simplify_type<const From> {
41 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
42 using SimpleType =
43 typename add_const_past_pointer<NonConstSimpleType>::type;
44 using RetType =
45 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
46
47 static RetType getSimplifiedValue(const From& Val) {
48 return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val));
49 }
50};
51
52// The core of the implementation of isa<X> is here; To and From should be
53// the names of classes. This template can be specialized to customize the
54// implementation of isa<> without rewriting it from scratch.
55template <typename To, typename From, typename Enabler = void>
56struct isa_impl {
57 static inline bool doit(const From &Val) {
58 return To::classof(&Val);
59 }
60};
61
62/// Always allow upcasts, and perform no dynamic check for them.
63template <typename To, typename From>
64struct isa_impl<To, From, std::enable_if_t<std::is_base_of<To, From>::value>> {
65 static inline bool doit(const From &) { return true; }
66};
67
68template <typename To, typename From> struct isa_impl_cl {
69 static inline bool doit(const From &Val) {
70 return isa_impl<To, From>::doit(Val);
71 }
72};
73
74template <typename To, typename From> struct isa_impl_cl<To, const From> {
75 static inline bool doit(const From &Val) {
76 return isa_impl<To, From>::doit(Val);
77 }
78};
79
80template <typename To, typename From>
81struct isa_impl_cl<To, const std::unique_ptr<From>> {
82 static inline bool doit(const std::unique_ptr<From> &Val) {
83 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/Support/Casting.h"
, 83, __PRETTY_FUNCTION__))
;
84 return isa_impl_cl<To, From>::doit(*Val);
85 }
86};
87
88template <typename To, typename From> struct isa_impl_cl<To, From*> {
89 static inline bool doit(const From *Val) {
90 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/Support/Casting.h"
, 90, __PRETTY_FUNCTION__))
;
91 return isa_impl<To, From>::doit(*Val);
92 }
93};
94
95template <typename To, typename From> struct isa_impl_cl<To, From*const> {
96 static inline bool doit(const From *Val) {
97 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/Support/Casting.h"
, 97, __PRETTY_FUNCTION__))
;
98 return isa_impl<To, From>::doit(*Val);
99 }
100};
101
102template <typename To, typename From> struct isa_impl_cl<To, const From*> {
103 static inline bool doit(const From *Val) {
104 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/Support/Casting.h"
, 104, __PRETTY_FUNCTION__))
;
105 return isa_impl<To, From>::doit(*Val);
106 }
107};
108
109template <typename To, typename From> struct isa_impl_cl<To, const From*const> {
110 static inline bool doit(const From *Val) {
111 assert(Val && "isa<> used on a null pointer")((Val && "isa<> used on a null pointer") ? static_cast
<void> (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/Support/Casting.h"
, 111, __PRETTY_FUNCTION__))
;
112 return isa_impl<To, From>::doit(*Val);
113 }
114};
115
116template<typename To, typename From, typename SimpleFrom>
117struct isa_impl_wrap {
118 // When From != SimplifiedType, we can simplify the type some more by using
119 // the simplify_type template.
120 static bool doit(const From &Val) {
121 return isa_impl_wrap<To, SimpleFrom,
122 typename simplify_type<SimpleFrom>::SimpleType>::doit(
123 simplify_type<const From>::getSimplifiedValue(Val));
124 }
125};
126
127template<typename To, typename FromTy>
128struct isa_impl_wrap<To, FromTy, FromTy> {
129 // When From == SimpleType, we are as simple as we are going to get.
130 static bool doit(const FromTy &Val) {
131 return isa_impl_cl<To,FromTy>::doit(Val);
132 }
133};
134
135// isa<X> - Return true if the parameter to the template is an instance of one
136// of the template type arguments. Used like this:
137//
138// if (isa<Type>(myVal)) { ... }
139// if (isa<Type0, Type1, Type2>(myVal)) { ... }
140//
141template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
142 return isa_impl_wrap<X, const Y,
143 typename simplify_type<const Y>::SimpleType>::doit(Val);
144}
145
146template <typename First, typename Second, typename... Rest, typename Y>
147LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
148 return isa<First>(Val) || isa<Second, Rest...>(Val);
149}
150
151// isa_and_nonnull<X> - Functionally identical to isa, except that a null value
152// is accepted.
153//
154template <typename... X, class Y>
155LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa_and_nonnull(const Y &Val) {
156 if (!Val)
157 return false;
158 return isa<X...>(Val);
159}
160
161//===----------------------------------------------------------------------===//
162// cast<x> Support Templates
163//===----------------------------------------------------------------------===//
164
165template<class To, class From> struct cast_retty;
166
167// Calculate what type the 'cast' function should return, based on a requested
168// type of To and a source type of From.
169template<class To, class From> struct cast_retty_impl {
170 using ret_type = To &; // Normal case, return Ty&
171};
172template<class To, class From> struct cast_retty_impl<To, const From> {
173 using ret_type = const To &; // Normal case, return Ty&
174};
175
176template<class To, class From> struct cast_retty_impl<To, From*> {
177 using ret_type = To *; // Pointer arg case, return Ty*
178};
179
180template<class To, class From> struct cast_retty_impl<To, const From*> {
181 using ret_type = const To *; // Constant pointer arg case, return const Ty*
182};
183
184template<class To, class From> struct cast_retty_impl<To, const From*const> {
185 using ret_type = const To *; // Constant pointer arg case, return const Ty*
186};
187
188template <class To, class From>
189struct cast_retty_impl<To, std::unique_ptr<From>> {
190private:
191 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
192 using ResultType = std::remove_pointer_t<PointerType>;
193
194public:
195 using ret_type = std::unique_ptr<ResultType>;
196};
197
198template<class To, class From, class SimpleFrom>
199struct cast_retty_wrap {
200 // When the simplified type and the from type are not the same, use the type
201 // simplifier to reduce the type, then reuse cast_retty_impl to get the
202 // resultant type.
203 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
204};
205
206template<class To, class FromTy>
207struct cast_retty_wrap<To, FromTy, FromTy> {
208 // When the simplified type is equal to the from type, use it directly.
209 using ret_type = typename cast_retty_impl<To,FromTy>::ret_type;
210};
211
212template<class To, class From>
213struct cast_retty {
214 using ret_type = typename cast_retty_wrap<
215 To, From, typename simplify_type<From>::SimpleType>::ret_type;
216};
217
218// Ensure the non-simple values are converted using the simplify_type template
219// that may be specialized by smart pointers...
220//
221template<class To, class From, class SimpleFrom> struct cast_convert_val {
222 // This is not a simple type, use the template to simplify it...
223 static typename cast_retty<To, From>::ret_type doit(From &Val) {
224 return cast_convert_val<To, SimpleFrom,
34
Returning without writing to 'Val.Node'
225 typename simplify_type<SimpleFrom>::SimpleType>::doit(
226 simplify_type<From>::getSimplifiedValue(Val));
31
Calling 'simplify_type::getSimplifiedValue'
33
Returning from 'simplify_type::getSimplifiedValue'
227 }
228};
229
230template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> {
231 // This _is_ a simple type, just cast it.
232 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
233 typename cast_retty<To, FromTy>::ret_type Res2
234 = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val);
235 return Res2;
236 }
237};
238
239template <class X> struct is_simple_type {
240 static const bool value =
241 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
242};
243
244// cast<X> - Return the argument parameter cast to the specified type. This
245// casting operator asserts that the type is correct, so it does not return null
246// on failure. It does not allow a null argument (use cast_or_null for that).
247// It is typically used like this:
248//
249// cast<Instruction>(myVal)->getParent()
250//
251template <class X, class Y>
252inline std::enable_if_t<!is_simple_type<Y>::value,
253 typename cast_retty<X, const Y>::ret_type>
254cast(const Y &Val) {
255 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/Support/Casting.h"
, 255, __PRETTY_FUNCTION__))
;
256 return cast_convert_val<
257 X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val);
258}
259
260template <class X, class Y>
261inline typename cast_retty<X, Y>::ret_type cast(Y &Val) {
262 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/Support/Casting.h"
, 262, __PRETTY_FUNCTION__))
;
28
Assuming 'Val' is a 'FrameIndexSDNode'
29
'?' condition is true
263 return cast_convert_val<X, Y,
30
Calling 'cast_convert_val::doit'
35
Returning from 'cast_convert_val::doit'
36
Returning without writing to 'Val.Node'
264 typename simplify_type<Y>::SimpleType>::doit(Val);
265}
266
267template <class X, class Y>
268inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) {
269 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/Support/Casting.h"
, 269, __PRETTY_FUNCTION__))
;
270 return cast_convert_val<X, Y*,
271 typename simplify_type<Y*>::SimpleType>::doit(Val);
272}
273
274template <class X, class Y>
275inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
276cast(std::unique_ptr<Y> &&Val) {
277 assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")((isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/Support/Casting.h"
, 277, __PRETTY_FUNCTION__))
;
278 using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type;
279 return ret_type(
280 cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit(
281 Val.release()));
282}
283
284// cast_or_null<X> - Functionally identical to cast, except that a null value is
285// accepted.
286//
287template <class X, class Y>
288LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
289 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
290cast_or_null(const Y &Val) {
291 if (!Val)
292 return nullptr;
293 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/Support/Casting.h"
, 293, __PRETTY_FUNCTION__))
;
294 return cast<X>(Val);
295}
296
297template <class X, class Y>
298LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<!is_simple_type<Y>::value,
299 typename cast_retty<X, Y>::ret_type>
300cast_or_null(Y &Val) {
301 if (!Val)
302 return nullptr;
303 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/Support/Casting.h"
, 303, __PRETTY_FUNCTION__))
;
304 return cast<X>(Val);
305}
306
307template <class X, class Y>
308LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
309cast_or_null(Y *Val) {
310 if (!Val) return nullptr;
311 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")((isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? static_cast<void> (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/Support/Casting.h"
, 311, __PRETTY_FUNCTION__))
;
312 return cast<X>(Val);
313}
314
315template <class X, class Y>
316inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
317cast_or_null(std::unique_ptr<Y> &&Val) {
318 if (!Val)
319 return nullptr;
320 return cast<X>(std::move(Val));
321}
322
323// dyn_cast<X> - Return the argument parameter cast to the specified type. This
324// casting operator returns null if the argument is of the wrong type, so it can
325// be used to test for a type as well as cast if successful. This should be
326// used in the context of an if statement like this:
327//
328// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
329//
330
331template <class X, class Y>
332LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
333 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
334dyn_cast(const Y &Val) {
335 return isa<X>(Val) ? cast<X>(Val) : nullptr;
336}
337
338template <class X, class Y>
339LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) {
340 return isa<X>(Val) ? cast<X>(Val) : nullptr;
25
Assuming 'Val' is a 'FrameIndexSDNode'
26
'?' condition is true
27
Calling 'cast<llvm::FrameIndexSDNode, llvm::SDValue>'
37
Returning from 'cast<llvm::FrameIndexSDNode, llvm::SDValue>'
38
Returning without writing to 'Val.Node'
341}
342
343template <class X, class Y>
344LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) {
345 return isa<X>(Val) ? cast<X>(Val) : nullptr;
346}
347
348// dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null
349// value is accepted.
350//
351template <class X, class Y>
352LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<
353 !is_simple_type<Y>::value, typename cast_retty<X, const Y>::ret_type>
354dyn_cast_or_null(const Y &Val) {
355 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
356}
357
358template <class X, class Y>
359LLVM_NODISCARD[[clang::warn_unused_result]] inline std::enable_if_t<!is_simple_type<Y>::value,
360 typename cast_retty<X, Y>::ret_type>
361dyn_cast_or_null(Y &Val) {
362 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
363}
364
365template <class X, class Y>
366LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
367dyn_cast_or_null(Y *Val) {
368 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
369}
370
371// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
372// taking ownership of the input pointer iff isa<X>(Val) is true. If the
373// cast is successful, From refers to nullptr on exit and the casted value
374// is returned. If the cast is unsuccessful, the function returns nullptr
375// and From is unchanged.
376template <class X, class Y>
377LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &Val)
378 -> decltype(cast<X>(Val)) {
379 if (!isa<X>(Val))
380 return nullptr;
381 return cast<X>(std::move(Val));
382}
383
384template <class X, class Y>
385LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val) {
386 return unique_dyn_cast<X, Y>(Val);
387}
388
389// dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, except that
390// a null value is accepted.
391template <class X, class Y>
392LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &Val)
393 -> decltype(cast<X>(Val)) {
394 if (!Val)
395 return nullptr;
396 return unique_dyn_cast<X, Y>(Val);
397}
398
399template <class X, class Y>
400LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val) {
401 return unique_dyn_cast_or_null<X, Y>(Val);
402}
403
404} // end namespace llvm
405
406#endif // LLVM_SUPPORT_CASTING_H

/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h

1//===- llvm/CodeGen/SelectionDAGNodes.h - SelectionDAG Nodes ----*- 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 the SDNode class and derived classes, which are used to
10// represent the nodes and operations present in a SelectionDAG. These nodes
11// and operations are machine code level operations, with some similarities to
12// the GCC RTL representation.
13//
14// Clients should include the SelectionDAG.h file instead of this file directly.
15//
16//===----------------------------------------------------------------------===//
17
18#ifndef LLVM_CODEGEN_SELECTIONDAGNODES_H
19#define LLVM_CODEGEN_SELECTIONDAGNODES_H
20
21#include "llvm/ADT/APFloat.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/BitVector.h"
24#include "llvm/ADT/FoldingSet.h"
25#include "llvm/ADT/GraphTraits.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/ilist_node.h"
29#include "llvm/ADT/iterator.h"
30#include "llvm/ADT/iterator_range.h"
31#include "llvm/CodeGen/ISDOpcodes.h"
32#include "llvm/CodeGen/MachineMemOperand.h"
33#include "llvm/CodeGen/Register.h"
34#include "llvm/CodeGen/ValueTypes.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/DebugLoc.h"
37#include "llvm/IR/Instruction.h"
38#include "llvm/IR/Instructions.h"
39#include "llvm/IR/Metadata.h"
40#include "llvm/IR/Operator.h"
41#include "llvm/Support/AlignOf.h"
42#include "llvm/Support/AtomicOrdering.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/MachineValueType.h"
46#include "llvm/Support/TypeSize.h"
47#include <algorithm>
48#include <cassert>
49#include <climits>
50#include <cstddef>
51#include <cstdint>
52#include <cstring>
53#include <iterator>
54#include <string>
55#include <tuple>
56
57namespace llvm {
58
59class APInt;
60class Constant;
61template <typename T> struct DenseMapInfo;
62class GlobalValue;
63class MachineBasicBlock;
64class MachineConstantPoolValue;
65class MCSymbol;
66class raw_ostream;
67class SDNode;
68class SelectionDAG;
69class Type;
70class Value;
71
72void checkForCycles(const SDNode *N, const SelectionDAG *DAG = nullptr,
73 bool force = false);
74
75/// This represents a list of ValueType's that has been intern'd by
76/// a SelectionDAG. Instances of this simple value class are returned by
77/// SelectionDAG::getVTList(...).
78///
79struct SDVTList {
80 const EVT *VTs;
81 unsigned int NumVTs;
82};
83
84namespace ISD {
85
86 /// Node predicates
87
88 /// If N is a BUILD_VECTOR node whose elements are all the same constant or
89 /// undefined, return true and return the constant value in \p SplatValue.
90 bool isConstantSplatVector(const SDNode *N, APInt &SplatValue);
91
92 /// Return true if the specified node is a BUILD_VECTOR where all of the
93 /// elements are ~0 or undef.
94 bool isBuildVectorAllOnes(const SDNode *N);
95
96 /// Return true if the specified node is a BUILD_VECTOR where all of the
97 /// elements are 0 or undef.
98 bool isBuildVectorAllZeros(const SDNode *N);
99
100 /// Return true if the specified node is a BUILD_VECTOR node of all
101 /// ConstantSDNode or undef.
102 bool isBuildVectorOfConstantSDNodes(const SDNode *N);
103
104 /// Return true if the specified node is a BUILD_VECTOR node of all
105 /// ConstantFPSDNode or undef.
106 bool isBuildVectorOfConstantFPSDNodes(const SDNode *N);
107
108 /// Return true if the node has at least one operand and all operands of the
109 /// specified node are ISD::UNDEF.
110 bool allOperandsUndef(const SDNode *N);
111
112} // end namespace ISD
113
114//===----------------------------------------------------------------------===//
115/// Unlike LLVM values, Selection DAG nodes may return multiple
116/// values as the result of a computation. Many nodes return multiple values,
117/// from loads (which define a token and a return value) to ADDC (which returns
118/// a result and a carry value), to calls (which may return an arbitrary number
119/// of values).
120///
121/// As such, each use of a SelectionDAG computation must indicate the node that
122/// computes it as well as which return value to use from that node. This pair
123/// of information is represented with the SDValue value type.
124///
125class SDValue {
126 friend struct DenseMapInfo<SDValue>;
127
128 SDNode *Node = nullptr; // The node defining the value we are using.
129 unsigned ResNo = 0; // Which return value of the node we are using.
130
131public:
132 SDValue() = default;
133 SDValue(SDNode *node, unsigned resno);
134
135 /// get the index which selects a specific result in the SDNode
136 unsigned getResNo() const { return ResNo; }
137
138 /// get the SDNode which holds the desired result
139 SDNode *getNode() const { return Node; }
140
141 /// set the SDNode
142 void setNode(SDNode *N) { Node = N; }
143
144 inline SDNode *operator->() const { return Node; }
145
146 bool operator==(const SDValue &O) const {
147 return Node == O.Node && ResNo == O.ResNo;
148 }
149 bool operator!=(const SDValue &O) const {
150 return !operator==(O);
151 }
152 bool operator<(const SDValue &O) const {
153 return std::tie(Node, ResNo) < std::tie(O.Node, O.ResNo);
154 }
155 explicit operator bool() const {
156 return Node != nullptr;
157 }
158
159 SDValue getValue(unsigned R) const {
160 return SDValue(Node, R);
161 }
162
163 /// Return true if this node is an operand of N.
164 bool isOperandOf(const SDNode *N) const;
165
166 /// Return the ValueType of the referenced return value.
167 inline EVT getValueType() const;
168
169 /// Return the simple ValueType of the referenced return value.
170 MVT getSimpleValueType() const {
171 return getValueType().getSimpleVT();
172 }
173
174 /// Returns the size of the value in bits.
175 ///
176 /// If the value type is a scalable vector type, the scalable property will
177 /// be set and the runtime size will be a positive integer multiple of the
178 /// base size.
179 TypeSize getValueSizeInBits() const {
180 return getValueType().getSizeInBits();
181 }
182
183 TypeSize getScalarValueSizeInBits() const {
184 return getValueType().getScalarType().getSizeInBits();
185 }
186
187 // Forwarding methods - These forward to the corresponding methods in SDNode.
188 inline unsigned getOpcode() const;
189 inline unsigned getNumOperands() const;
190 inline const SDValue &getOperand(unsigned i) const;
191 inline uint64_t getConstantOperandVal(unsigned i) const;
192 inline const APInt &getConstantOperandAPInt(unsigned i) const;
193 inline bool isTargetMemoryOpcode() const;
194 inline bool isTargetOpcode() const;
195 inline bool isMachineOpcode() const;
196 inline bool isUndef() const;
197 inline unsigned getMachineOpcode() const;
198 inline const DebugLoc &getDebugLoc() const;
199 inline void dump() const;
200 inline void dump(const SelectionDAG *G) const;
201 inline void dumpr() const;
202 inline void dumpr(const SelectionDAG *G) const;
203
204 /// Return true if this operand (which must be a chain) reaches the
205 /// specified operand without crossing any side-effecting instructions.
206 /// In practice, this looks through token factors and non-volatile loads.
207 /// In order to remain efficient, this only
208 /// looks a couple of nodes in, it does not do an exhaustive search.
209 bool reachesChainWithoutSideEffects(SDValue Dest,
210 unsigned Depth = 2) const;
211
212 /// Return true if there are no nodes using value ResNo of Node.
213 inline bool use_empty() const;
214
215 /// Return true if there is exactly one node using value ResNo of Node.
216 inline bool hasOneUse() const;
217};
218
219template<> struct DenseMapInfo<SDValue> {
220 static inline SDValue getEmptyKey() {
221 SDValue V;
222 V.ResNo = -1U;
223 return V;
224 }
225
226 static inline SDValue getTombstoneKey() {
227 SDValue V;
228 V.ResNo = -2U;
229 return V;
230 }
231
232 static unsigned getHashValue(const SDValue &Val) {
233 return ((unsigned)((uintptr_t)Val.getNode() >> 4) ^
234 (unsigned)((uintptr_t)Val.getNode() >> 9)) + Val.getResNo();
235 }
236
237 static bool isEqual(const SDValue &LHS, const SDValue &RHS) {
238 return LHS == RHS;
239 }
240};
241
242/// Allow casting operators to work directly on
243/// SDValues as if they were SDNode*'s.
244template<> struct simplify_type<SDValue> {
245 using SimpleType = SDNode *;
246
247 static SimpleType getSimplifiedValue(SDValue &Val) {
248 return Val.getNode();
32
Returning without writing to 'Val.Node'
249 }
250};
251template<> struct simplify_type<const SDValue> {
252 using SimpleType = /*const*/ SDNode *;
253
254 static SimpleType getSimplifiedValue(const SDValue &Val) {
255 return Val.getNode();
256 }
257};
258
259/// Represents a use of a SDNode. This class holds an SDValue,
260/// which records the SDNode being used and the result number, a
261/// pointer to the SDNode using the value, and Next and Prev pointers,
262/// which link together all the uses of an SDNode.
263///
264class SDUse {
265 /// Val - The value being used.
266 SDValue Val;
267 /// User - The user of this value.
268 SDNode *User = nullptr;
269 /// Prev, Next - Pointers to the uses list of the SDNode referred by
270 /// this operand.
271 SDUse **Prev = nullptr;
272 SDUse *Next = nullptr;
273
274public:
275 SDUse() = default;
276 SDUse(const SDUse &U) = delete;
277 SDUse &operator=(const SDUse &) = delete;
278
279 /// Normally SDUse will just implicitly convert to an SDValue that it holds.
280 operator const SDValue&() const { return Val; }
281
282 /// If implicit conversion to SDValue doesn't work, the get() method returns
283 /// the SDValue.
284 const SDValue &get() const { return Val; }
285
286 /// This returns the SDNode that contains this Use.
287 SDNode *getUser() { return User; }
288
289 /// Get the next SDUse in the use list.
290 SDUse *getNext() const { return Next; }
291
292 /// Convenience function for get().getNode().
293 SDNode *getNode() const { return Val.getNode(); }
294 /// Convenience function for get().getResNo().
295 unsigned getResNo() const { return Val.getResNo(); }
296 /// Convenience function for get().getValueType().
297 EVT getValueType() const { return Val.getValueType(); }
298
299 /// Convenience function for get().operator==
300 bool operator==(const SDValue &V) const {
301 return Val == V;
302 }
303
304 /// Convenience function for get().operator!=
305 bool operator!=(const SDValue &V) const {
306 return Val != V;
307 }
308
309 /// Convenience function for get().operator<
310 bool operator<(const SDValue &V) const {
311 return Val < V;
312 }
313
314private:
315 friend class SelectionDAG;
316 friend class SDNode;
317 // TODO: unfriend HandleSDNode once we fix its operand handling.
318 friend class HandleSDNode;
319
320 void setUser(SDNode *p) { User = p; }
321
322 /// Remove this use from its existing use list, assign it the
323 /// given value, and add it to the new value's node's use list.
324 inline void set(const SDValue &V);
325 /// Like set, but only supports initializing a newly-allocated
326 /// SDUse with a non-null value.
327 inline void setInitial(const SDValue &V);
328 /// Like set, but only sets the Node portion of the value,
329 /// leaving the ResNo portion unmodified.
330 inline void setNode(SDNode *N);
331
332 void addToList(SDUse **List) {
333 Next = *List;
334 if (Next) Next->Prev = &Next;
335 Prev = List;
336 *List = this;
337 }
338
339 void removeFromList() {
340 *Prev = Next;
341 if (Next) Next->Prev = Prev;
342 }
343};
344
345/// simplify_type specializations - Allow casting operators to work directly on
346/// SDValues as if they were SDNode*'s.
347template<> struct simplify_type<SDUse> {
348 using SimpleType = SDNode *;
349
350 static SimpleType getSimplifiedValue(SDUse &Val) {
351 return Val.getNode();
352 }
353};
354
355/// These are IR-level optimization flags that may be propagated to SDNodes.
356/// TODO: This data structure should be shared by the IR optimizer and the
357/// the backend.
358struct SDNodeFlags {
359private:
360 bool NoUnsignedWrap : 1;
361 bool NoSignedWrap : 1;
362 bool Exact : 1;
363 bool NoNaNs : 1;
364 bool NoInfs : 1;
365 bool NoSignedZeros : 1;
366 bool AllowReciprocal : 1;
367 bool AllowContract : 1;
368 bool ApproximateFuncs : 1;
369 bool AllowReassociation : 1;
370
371 // We assume instructions do not raise floating-point exceptions by default,
372 // and only those marked explicitly may do so. We could choose to represent
373 // this via a positive "FPExcept" flags like on the MI level, but having a
374 // negative "NoFPExcept" flag here (that defaults to true) makes the flag
375 // intersection logic more straightforward.
376 bool NoFPExcept : 1;
377
378public:
379 /// Default constructor turns off all optimization flags.
380 SDNodeFlags()
381 : NoUnsignedWrap(false), NoSignedWrap(false), Exact(false), NoNaNs(false),
382 NoInfs(false), NoSignedZeros(false), AllowReciprocal(false),
383 AllowContract(false), ApproximateFuncs(false),
384 AllowReassociation(false), NoFPExcept(false) {}
385
386 /// Propagate the fast-math-flags from an IR FPMathOperator.
387 void copyFMF(const FPMathOperator &FPMO) {
388 setNoNaNs(FPMO.hasNoNaNs());
389 setNoInfs(FPMO.hasNoInfs());
390 setNoSignedZeros(FPMO.hasNoSignedZeros());
391 setAllowReciprocal(FPMO.hasAllowReciprocal());
392 setAllowContract(FPMO.hasAllowContract());
393 setApproximateFuncs(FPMO.hasApproxFunc());
394 setAllowReassociation(FPMO.hasAllowReassoc());
395 }
396
397 // These are mutators for each flag.
398 void setNoUnsignedWrap(bool b) { NoUnsignedWrap = b; }
399 void setNoSignedWrap(bool b) { NoSignedWrap = b; }
400 void setExact(bool b) { Exact = b; }
401 void setNoNaNs(bool b) { NoNaNs = b; }
402 void setNoInfs(bool b) { NoInfs = b; }
403 void setNoSignedZeros(bool b) { NoSignedZeros = b; }
404 void setAllowReciprocal(bool b) { AllowReciprocal = b; }
405 void setAllowContract(bool b) { AllowContract = b; }
406 void setApproximateFuncs(bool b) { ApproximateFuncs = b; }
407 void setAllowReassociation(bool b) { AllowReassociation = b; }
408 void setNoFPExcept(bool b) { NoFPExcept = b; }
409
410 // These are accessors for each flag.
411 bool hasNoUnsignedWrap() const { return NoUnsignedWrap; }
412 bool hasNoSignedWrap() const { return NoSignedWrap; }
413 bool hasExact() const { return Exact; }
414 bool hasNoNaNs() const { return NoNaNs; }
415 bool hasNoInfs() const { return NoInfs; }
416 bool hasNoSignedZeros() const { return NoSignedZeros; }
417 bool hasAllowReciprocal() const { return AllowReciprocal; }
418 bool hasAllowContract() const { return AllowContract; }
419 bool hasApproximateFuncs() const { return ApproximateFuncs; }
420 bool hasAllowReassociation() const { return AllowReassociation; }
421 bool hasNoFPExcept() const { return NoFPExcept; }
422
423 /// Clear any flags in this flag set that aren't also set in Flags. All
424 /// flags will be cleared if Flags are undefined.
425 void intersectWith(const SDNodeFlags Flags) {
426 NoUnsignedWrap &= Flags.NoUnsignedWrap;
427 NoSignedWrap &= Flags.NoSignedWrap;
428 Exact &= Flags.Exact;
429 NoNaNs &= Flags.NoNaNs;
430 NoInfs &= Flags.NoInfs;
431 NoSignedZeros &= Flags.NoSignedZeros;
432 AllowReciprocal &= Flags.AllowReciprocal;
433 AllowContract &= Flags.AllowContract;
434 ApproximateFuncs &= Flags.ApproximateFuncs;
435 AllowReassociation &= Flags.AllowReassociation;
436 NoFPExcept &= Flags.NoFPExcept;
437 }
438};
439
440/// Represents one node in the SelectionDAG.
441///
442class SDNode : public FoldingSetNode, public ilist_node<SDNode> {
443private:
444 /// The operation that this node performs.
445 int16_t NodeType;
446
447protected:
448 // We define a set of mini-helper classes to help us interpret the bits in our
449 // SubclassData. These are designed to fit within a uint16_t so they pack
450 // with NodeType.
451
452#if defined(_AIX) && (!defined(__GNUC__4) || defined(__ibmxl__))
453// Except for GCC; by default, AIX compilers store bit-fields in 4-byte words
454// and give the `pack` pragma push semantics.
455#define BEGIN_TWO_BYTE_PACK() _Pragma("pack(2)")pack(2)
456#define END_TWO_BYTE_PACK() _Pragma("pack(pop)")pack(pop)
457#else
458#define BEGIN_TWO_BYTE_PACK()
459#define END_TWO_BYTE_PACK()
460#endif
461
462BEGIN_TWO_BYTE_PACK()
463 class SDNodeBitfields {
464 friend class SDNode;
465 friend class MemIntrinsicSDNode;
466 friend class MemSDNode;
467 friend class SelectionDAG;
468
469 uint16_t HasDebugValue : 1;
470 uint16_t IsMemIntrinsic : 1;
471 uint16_t IsDivergent : 1;
472 };
473 enum { NumSDNodeBits = 3 };
474
475 class ConstantSDNodeBitfields {
476 friend class ConstantSDNode;
477
478 uint16_t : NumSDNodeBits;
479
480 uint16_t IsOpaque : 1;
481 };
482
483 class MemSDNodeBitfields {
484 friend class MemSDNode;
485 friend class MemIntrinsicSDNode;
486 friend class AtomicSDNode;
487
488 uint16_t : NumSDNodeBits;
489
490 uint16_t IsVolatile : 1;
491 uint16_t IsNonTemporal : 1;
492 uint16_t IsDereferenceable : 1;
493 uint16_t IsInvariant : 1;
494 };
495 enum { NumMemSDNodeBits = NumSDNodeBits + 4 };
496
497 class LSBaseSDNodeBitfields {
498 friend class LSBaseSDNode;
499 friend class MaskedLoadStoreSDNode;
500 friend class MaskedGatherScatterSDNode;
501
502 uint16_t : NumMemSDNodeBits;
503
504 // This storage is shared between disparate class hierarchies to hold an
505 // enumeration specific to the class hierarchy in use.
506 // LSBaseSDNode => enum ISD::MemIndexedMode
507 // MaskedLoadStoreBaseSDNode => enum ISD::MemIndexedMode
508 // MaskedGatherScatterSDNode => enum ISD::MemIndexType
509 uint16_t AddressingMode : 3;
510 };
511 enum { NumLSBaseSDNodeBits = NumMemSDNodeBits + 3 };
512
513 class LoadSDNodeBitfields {
514 friend class LoadSDNode;
515 friend class MaskedLoadSDNode;
516
517 uint16_t : NumLSBaseSDNodeBits;
518
519 uint16_t ExtTy : 2; // enum ISD::LoadExtType
520 uint16_t IsExpanding : 1;
521 };
522
523 class StoreSDNodeBitfields {
524 friend class StoreSDNode;
525 friend class MaskedStoreSDNode;
526
527 uint16_t : NumLSBaseSDNodeBits;
528
529 uint16_t IsTruncating : 1;
530 uint16_t IsCompressing : 1;
531 };
532
533 union {
534 char RawSDNodeBits[sizeof(uint16_t)];
535 SDNodeBitfields SDNodeBits;
536 ConstantSDNodeBitfields ConstantSDNodeBits;
537 MemSDNodeBitfields MemSDNodeBits;
538 LSBaseSDNodeBitfields LSBaseSDNodeBits;
539 LoadSDNodeBitfields LoadSDNodeBits;
540 StoreSDNodeBitfields StoreSDNodeBits;
541 };
542END_TWO_BYTE_PACK()
543#undef BEGIN_TWO_BYTE_PACK
544#undef END_TWO_BYTE_PACK
545
546 // RawSDNodeBits must cover the entirety of the union. This means that all of
547 // the union's members must have size <= RawSDNodeBits. We write the RHS as
548 // "2" instead of sizeof(RawSDNodeBits) because MSVC can't handle the latter.
549 static_assert(sizeof(SDNodeBitfields) <= 2, "field too wide");
550 static_assert(sizeof(ConstantSDNodeBitfields) <= 2, "field too wide");
551 static_assert(sizeof(MemSDNodeBitfields) <= 2, "field too wide");
552 static_assert(sizeof(LSBaseSDNodeBitfields) <= 2, "field too wide");
553 static_assert(sizeof(LoadSDNodeBitfields) <= 2, "field too wide");
554 static_assert(sizeof(StoreSDNodeBitfields) <= 2, "field too wide");
555
556private:
557 friend class SelectionDAG;
558 // TODO: unfriend HandleSDNode once we fix its operand handling.
559 friend class HandleSDNode;
560
561 /// Unique id per SDNode in the DAG.
562 int NodeId = -1;
563
564 /// The values that are used by this operation.
565 SDUse *OperandList = nullptr;
566
567 /// The types of the values this node defines. SDNode's may
568 /// define multiple values simultaneously.
569 const EVT *ValueList;
570
571 /// List of uses for this SDNode.
572 SDUse *UseList = nullptr;
573
574 /// The number of entries in the Operand/Value list.
575 unsigned short NumOperands = 0;
576 unsigned short NumValues;
577
578 // The ordering of the SDNodes. It roughly corresponds to the ordering of the
579 // original LLVM instructions.
580 // This is used for turning off scheduling, because we'll forgo
581 // the normal scheduling algorithms and output the instructions according to
582 // this ordering.
583 unsigned IROrder;
584
585 /// Source line information.
586 DebugLoc debugLoc;
587
588 /// Return a pointer to the specified value type.
589 static const EVT *getValueTypeList(EVT VT);
590
591 SDNodeFlags Flags;
592
593public:
594 /// Unique and persistent id per SDNode in the DAG.
595 /// Used for debug printing.
596 uint16_t PersistentId;
597
598 //===--------------------------------------------------------------------===//
599 // Accessors
600 //
601
602 /// Return the SelectionDAG opcode value for this node. For
603 /// pre-isel nodes (those for which isMachineOpcode returns false), these
604 /// are the opcode values in the ISD and <target>ISD namespaces. For
605 /// post-isel opcodes, see getMachineOpcode.
606 unsigned getOpcode() const { return (unsigned short)NodeType; }
607
608 /// Test if this node has a target-specific opcode (in the
609 /// \<target\>ISD namespace).
610 bool isTargetOpcode() const { return NodeType >= ISD::BUILTIN_OP_END; }
611
612 /// Test if this node has a target-specific opcode that may raise
613 /// FP exceptions (in the \<target\>ISD namespace and greater than
614 /// FIRST_TARGET_STRICTFP_OPCODE). Note that all target memory
615 /// opcode are currently automatically considered to possibly raise
616 /// FP exceptions as well.
617 bool isTargetStrictFPOpcode() const {
618 return NodeType >= ISD::FIRST_TARGET_STRICTFP_OPCODE;
619 }
620
621 /// Test if this node has a target-specific
622 /// memory-referencing opcode (in the \<target\>ISD namespace and
623 /// greater than FIRST_TARGET_MEMORY_OPCODE).
624 bool isTargetMemoryOpcode() const {
625 return NodeType >= ISD::FIRST_TARGET_MEMORY_OPCODE;
626 }
627
628 /// Return true if the type of the node type undefined.
629 bool isUndef() const { return NodeType == ISD::UNDEF; }
630
631 /// Test if this node is a memory intrinsic (with valid pointer information).
632 /// INTRINSIC_W_CHAIN and INTRINSIC_VOID nodes are sometimes created for
633 /// non-memory intrinsics (with chains) that are not really instances of
634 /// MemSDNode. For such nodes, we need some extra state to determine the
635 /// proper classof relationship.
636 bool isMemIntrinsic() const {
637 return (NodeType == ISD::INTRINSIC_W_CHAIN ||
638 NodeType == ISD::INTRINSIC_VOID) &&
639 SDNodeBits.IsMemIntrinsic;
640 }
641
642 /// Test if this node is a strict floating point pseudo-op.
643 bool isStrictFPOpcode() {
644 switch (NodeType) {
645 default:
646 return false;
647 case ISD::STRICT_FP16_TO_FP:
648 case ISD::STRICT_FP_TO_FP16:
649#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
650 case ISD::STRICT_##DAGN:
651#include "llvm/IR/ConstrainedOps.def"
652 return true;
653 }
654 }
655
656 /// Test if this node has a post-isel opcode, directly
657 /// corresponding to a MachineInstr opcode.
658 bool isMachineOpcode() const { return NodeType < 0; }
659
660 /// This may only be called if isMachineOpcode returns
661 /// true. It returns the MachineInstr opcode value that the node's opcode
662 /// corresponds to.
663 unsigned getMachineOpcode() const {
664 assert(isMachineOpcode() && "Not a MachineInstr opcode!")((isMachineOpcode() && "Not a MachineInstr opcode!") ?
static_cast<void> (0) : __assert_fail ("isMachineOpcode() && \"Not a MachineInstr opcode!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 664, __PRETTY_FUNCTION__))
;
665 return ~NodeType;
666 }
667
668 bool getHasDebugValue() const { return SDNodeBits.HasDebugValue; }
669 void setHasDebugValue(bool b) { SDNodeBits.HasDebugValue = b; }
670
671 bool isDivergent() const { return SDNodeBits.IsDivergent; }
672
673 /// Return true if there are no uses of this node.
674 bool use_empty() const { return UseList == nullptr; }
675
676 /// Return true if there is exactly one use of this node.
677 bool hasOneUse() const {
678 return !use_empty() && std::next(use_begin()) == use_end();
679 }
680
681 /// Return the number of uses of this node. This method takes
682 /// time proportional to the number of uses.
683 size_t use_size() const { return std::distance(use_begin(), use_end()); }
684
685 /// Return the unique node id.
686 int getNodeId() const { return NodeId; }
687
688 /// Set unique node id.
689 void setNodeId(int Id) { NodeId = Id; }
690
691 /// Return the node ordering.
692 unsigned getIROrder() const { return IROrder; }
693
694 /// Set the node ordering.
695 void setIROrder(unsigned Order) { IROrder = Order; }
696
697 /// Return the source location info.
698 const DebugLoc &getDebugLoc() const { return debugLoc; }
699
700 /// Set source location info. Try to avoid this, putting
701 /// it in the constructor is preferable.
702 void setDebugLoc(DebugLoc dl) { debugLoc = std::move(dl); }
703
704 /// This class provides iterator support for SDUse
705 /// operands that use a specific SDNode.
706 class use_iterator
707 : public std::iterator<std::forward_iterator_tag, SDUse, ptrdiff_t> {
708 friend class SDNode;
709
710 SDUse *Op = nullptr;
711
712 explicit use_iterator(SDUse *op) : Op(op) {}
713
714 public:
715 using reference = std::iterator<std::forward_iterator_tag,
716 SDUse, ptrdiff_t>::reference;
717 using pointer = std::iterator<std::forward_iterator_tag,
718 SDUse, ptrdiff_t>::pointer;
719
720 use_iterator() = default;
721 use_iterator(const use_iterator &I) : Op(I.Op) {}
722
723 bool operator==(const use_iterator &x) const {
724 return Op == x.Op;
725 }
726 bool operator!=(const use_iterator &x) const {
727 return !operator==(x);
728 }
729
730 /// Return true if this iterator is at the end of uses list.
731 bool atEnd() const { return Op == nullptr; }
732
733 // Iterator traversal: forward iteration only.
734 use_iterator &operator++() { // Preincrement
735 assert(Op && "Cannot increment end iterator!")((Op && "Cannot increment end iterator!") ? static_cast
<void> (0) : __assert_fail ("Op && \"Cannot increment end iterator!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 735, __PRETTY_FUNCTION__))
;
736 Op = Op->getNext();
737 return *this;
738 }
739
740 use_iterator operator++(int) { // Postincrement
741 use_iterator tmp = *this; ++*this; return tmp;
742 }
743
744 /// Retrieve a pointer to the current user node.
745 SDNode *operator*() const {
746 assert(Op && "Cannot dereference end iterator!")((Op && "Cannot dereference end iterator!") ? static_cast
<void> (0) : __assert_fail ("Op && \"Cannot dereference end iterator!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 746, __PRETTY_FUNCTION__))
;
747 return Op->getUser();
748 }
749
750 SDNode *operator->() const { return operator*(); }
751
752 SDUse &getUse() const { return *Op; }
753
754 /// Retrieve the operand # of this use in its user.
755 unsigned getOperandNo() const {
756 assert(Op && "Cannot dereference end iterator!")((Op && "Cannot dereference end iterator!") ? static_cast
<void> (0) : __assert_fail ("Op && \"Cannot dereference end iterator!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 756, __PRETTY_FUNCTION__))
;
757 return (unsigned)(Op - Op->getUser()->OperandList);
758 }
759 };
760
761 /// Provide iteration support to walk over all uses of an SDNode.
762 use_iterator use_begin() const {
763 return use_iterator(UseList);
764 }
765
766 static use_iterator use_end() { return use_iterator(nullptr); }
767
768 inline iterator_range<use_iterator> uses() {
769 return make_range(use_begin(), use_end());
770 }
771 inline iterator_range<use_iterator> uses() const {
772 return make_range(use_begin(), use_end());
773 }
774
775 /// Return true if there are exactly NUSES uses of the indicated value.
776 /// This method ignores uses of other values defined by this operation.
777 bool hasNUsesOfValue(unsigned NUses, unsigned Value) const;
778
779 /// Return true if there are any use of the indicated value.
780 /// This method ignores uses of other values defined by this operation.
781 bool hasAnyUseOfValue(unsigned Value) const;
782
783 /// Return true if this node is the only use of N.
784 bool isOnlyUserOf(const SDNode *N) const;
785
786 /// Return true if this node is an operand of N.
787 bool isOperandOf(const SDNode *N) const;
788
789 /// Return true if this node is a predecessor of N.
790 /// NOTE: Implemented on top of hasPredecessor and every bit as
791 /// expensive. Use carefully.
792 bool isPredecessorOf(const SDNode *N) const {
793 return N->hasPredecessor(this);
794 }
795
796 /// Return true if N is a predecessor of this node.
797 /// N is either an operand of this node, or can be reached by recursively
798 /// traversing up the operands.
799 /// NOTE: This is an expensive method. Use it carefully.
800 bool hasPredecessor(const SDNode *N) const;
801
802 /// Returns true if N is a predecessor of any node in Worklist. This
803 /// helper keeps Visited and Worklist sets externally to allow unions
804 /// searches to be performed in parallel, caching of results across
805 /// queries and incremental addition to Worklist. Stops early if N is
806 /// found but will resume. Remember to clear Visited and Worklists
807 /// if DAG changes. MaxSteps gives a maximum number of nodes to visit before
808 /// giving up. The TopologicalPrune flag signals that positive NodeIds are
809 /// topologically ordered (Operands have strictly smaller node id) and search
810 /// can be pruned leveraging this.
811 static bool hasPredecessorHelper(const SDNode *N,
812 SmallPtrSetImpl<const SDNode *> &Visited,
813 SmallVectorImpl<const SDNode *> &Worklist,
814 unsigned int MaxSteps = 0,
815 bool TopologicalPrune = false) {
816 SmallVector<const SDNode *, 8> DeferredNodes;
817 if (Visited.count(N))
818 return true;
819
820 // Node Id's are assigned in three places: As a topological
821 // ordering (> 0), during legalization (results in values set to
822 // 0), new nodes (set to -1). If N has a topolgical id then we
823 // know that all nodes with ids smaller than it cannot be
824 // successors and we need not check them. Filter out all node
825 // that can't be matches. We add them to the worklist before exit
826 // in case of multiple calls. Note that during selection the topological id
827 // may be violated if a node's predecessor is selected before it. We mark
828 // this at selection negating the id of unselected successors and
829 // restricting topological pruning to positive ids.
830
831 int NId = N->getNodeId();
832 // If we Invalidated the Id, reconstruct original NId.
833 if (NId < -1)
834 NId = -(NId + 1);
835
836 bool Found = false;
837 while (!Worklist.empty()) {
838 const SDNode *M = Worklist.pop_back_val();
839 int MId = M->getNodeId();
840 if (TopologicalPrune && M->getOpcode() != ISD::TokenFactor && (NId > 0) &&
841 (MId > 0) && (MId < NId)) {
842 DeferredNodes.push_back(M);
843 continue;
844 }
845 for (const SDValue &OpV : M->op_values()) {
846 SDNode *Op = OpV.getNode();
847 if (Visited.insert(Op).second)
848 Worklist.push_back(Op);
849 if (Op == N)
850 Found = true;
851 }
852 if (Found)
853 break;
854 if (MaxSteps != 0 && Visited.size() >= MaxSteps)
855 break;
856 }
857 // Push deferred nodes back on worklist.
858 Worklist.append(DeferredNodes.begin(), DeferredNodes.end());
859 // If we bailed early, conservatively return found.
860 if (MaxSteps != 0 && Visited.size() >= MaxSteps)
861 return true;
862 return Found;
863 }
864
865 /// Return true if all the users of N are contained in Nodes.
866 /// NOTE: Requires at least one match, but doesn't require them all.
867 static bool areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N);
868
869 /// Return the number of values used by this operation.
870 unsigned getNumOperands() const { return NumOperands; }
871
872 /// Return the maximum number of operands that a SDNode can hold.
873 static constexpr size_t getMaxNumOperands() {
874 return std::numeric_limits<decltype(SDNode::NumOperands)>::max();
875 }
876
877 /// Helper method returns the integer value of a ConstantSDNode operand.
878 inline uint64_t getConstantOperandVal(unsigned Num) const;
879
880 /// Helper method returns the APInt of a ConstantSDNode operand.
881 inline const APInt &getConstantOperandAPInt(unsigned Num) const;
882
883 const SDValue &getOperand(unsigned Num) const {
884 assert(Num < NumOperands && "Invalid child # of SDNode!")((Num < NumOperands && "Invalid child # of SDNode!"
) ? static_cast<void> (0) : __assert_fail ("Num < NumOperands && \"Invalid child # of SDNode!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 884, __PRETTY_FUNCTION__))
;
885 return OperandList[Num];
886 }
887
888 using op_iterator = SDUse *;
889
890 op_iterator op_begin() const { return OperandList; }
891 op_iterator op_end() const { return OperandList+NumOperands; }
892 ArrayRef<SDUse> ops() const { return makeArrayRef(op_begin(), op_end()); }
893
894 /// Iterator for directly iterating over the operand SDValue's.
895 struct value_op_iterator
896 : iterator_adaptor_base<value_op_iterator, op_iterator,
897 std::random_access_iterator_tag, SDValue,
898 ptrdiff_t, value_op_iterator *,
899 value_op_iterator *> {
900 explicit value_op_iterator(SDUse *U = nullptr)
901 : iterator_adaptor_base(U) {}
902
903 const SDValue &operator*() const { return I->get(); }
904 };
905
906 iterator_range<value_op_iterator> op_values() const {
907 return make_range(value_op_iterator(op_begin()),
908 value_op_iterator(op_end()));
909 }
910
911 SDVTList getVTList() const {
912 SDVTList X = { ValueList, NumValues };
913 return X;
914 }
915
916 /// If this node has a glue operand, return the node
917 /// to which the glue operand points. Otherwise return NULL.
918 SDNode *getGluedNode() const {
919 if (getNumOperands() != 0 &&
920 getOperand(getNumOperands()-1).getValueType() == MVT::Glue)
921 return getOperand(getNumOperands()-1).getNode();
922 return nullptr;
923 }
924
925 /// If this node has a glue value with a user, return
926 /// the user (there is at most one). Otherwise return NULL.
927 SDNode *getGluedUser() const {
928 for (use_iterator UI = use_begin(), UE = use_end(); UI != UE; ++UI)
929 if (UI.getUse().get().getValueType() == MVT::Glue)
930 return *UI;
931 return nullptr;
932 }
933
934 const SDNodeFlags getFlags() const { return Flags; }
935 void setFlags(SDNodeFlags NewFlags) { Flags = NewFlags; }
936
937 /// Clear any flags in this node that aren't also set in Flags.
938 /// If Flags is not in a defined state then this has no effect.
939 void intersectFlagsWith(const SDNodeFlags Flags);
940
941 /// Return the number of values defined/returned by this operator.
942 unsigned getNumValues() const { return NumValues; }
943
944 /// Return the type of a specified result.
945 EVT getValueType(unsigned ResNo) const {
946 assert(ResNo < NumValues && "Illegal result number!")((ResNo < NumValues && "Illegal result number!") ?
static_cast<void> (0) : __assert_fail ("ResNo < NumValues && \"Illegal result number!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 946, __PRETTY_FUNCTION__))
;
947 return ValueList[ResNo];
948 }
949
950 /// Return the type of a specified result as a simple type.
951 MVT getSimpleValueType(unsigned ResNo) const {
952 return getValueType(ResNo).getSimpleVT();
953 }
954
955 /// Returns MVT::getSizeInBits(getValueType(ResNo)).
956 ///
957 /// If the value type is a scalable vector type, the scalable property will
958 /// be set and the runtime size will be a positive integer multiple of the
959 /// base size.
960 TypeSize getValueSizeInBits(unsigned ResNo) const {
961 return getValueType(ResNo).getSizeInBits();
962 }
963
964 using value_iterator = const EVT *;
965
966 value_iterator value_begin() const { return ValueList; }
967 value_iterator value_end() const { return ValueList+NumValues; }
968 iterator_range<value_iterator> values() const {
969 return llvm::make_range(value_begin(), value_end());
970 }
971
972 /// Return the opcode of this operation for printing.
973 std::string getOperationName(const SelectionDAG *G = nullptr) const;
974 static const char* getIndexedModeName(ISD::MemIndexedMode AM);
975 void print_types(raw_ostream &OS, const SelectionDAG *G) const;
976 void print_details(raw_ostream &OS, const SelectionDAG *G) const;
977 void print(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
978 void printr(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
979
980 /// Print a SelectionDAG node and all children down to
981 /// the leaves. The given SelectionDAG allows target-specific nodes
982 /// to be printed in human-readable form. Unlike printr, this will
983 /// print the whole DAG, including children that appear multiple
984 /// times.
985 ///
986 void printrFull(raw_ostream &O, const SelectionDAG *G = nullptr) const;
987
988 /// Print a SelectionDAG node and children up to
989 /// depth "depth." The given SelectionDAG allows target-specific
990 /// nodes to be printed in human-readable form. Unlike printr, this
991 /// will print children that appear multiple times wherever they are
992 /// used.
993 ///
994 void printrWithDepth(raw_ostream &O, const SelectionDAG *G = nullptr,
995 unsigned depth = 100) const;
996
997 /// Dump this node, for debugging.
998 void dump() const;
999
1000 /// Dump (recursively) this node and its use-def subgraph.
1001 void dumpr() const;
1002
1003 /// Dump this node, for debugging.
1004 /// The given SelectionDAG allows target-specific nodes to be printed
1005 /// in human-readable form.
1006 void dump(const SelectionDAG *G) const;
1007
1008 /// Dump (recursively) this node and its use-def subgraph.
1009 /// The given SelectionDAG allows target-specific nodes to be printed
1010 /// in human-readable form.
1011 void dumpr(const SelectionDAG *G) const;
1012
1013 /// printrFull to dbgs(). The given SelectionDAG allows
1014 /// target-specific nodes to be printed in human-readable form.
1015 /// Unlike dumpr, this will print the whole DAG, including children
1016 /// that appear multiple times.
1017 void dumprFull(const SelectionDAG *G = nullptr) const;
1018
1019 /// printrWithDepth to dbgs(). The given
1020 /// SelectionDAG allows target-specific nodes to be printed in
1021 /// human-readable form. Unlike dumpr, this will print children
1022 /// that appear multiple times wherever they are used.
1023 ///
1024 void dumprWithDepth(const SelectionDAG *G = nullptr,
1025 unsigned depth = 100) const;
1026
1027 /// Gather unique data for the node.
1028 void Profile(FoldingSetNodeID &ID) const;
1029
1030 /// This method should only be used by the SDUse class.
1031 void addUse(SDUse &U) { U.addToList(&UseList); }
1032
1033protected:
1034 static SDVTList getSDVTList(EVT VT) {
1035 SDVTList Ret = { getValueTypeList(VT), 1 };
1036 return Ret;
1037 }
1038
1039 /// Create an SDNode.
1040 ///
1041 /// SDNodes are created without any operands, and never own the operand
1042 /// storage. To add operands, see SelectionDAG::createOperands.
1043 SDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs)
1044 : NodeType(Opc), ValueList(VTs.VTs), NumValues(VTs.NumVTs),
1045 IROrder(Order), debugLoc(std::move(dl)) {
1046 memset(&RawSDNodeBits, 0, sizeof(RawSDNodeBits));
1047 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor")((debugLoc.hasTrivialDestructor() && "Expected trivial destructor"
) ? static_cast<void> (0) : __assert_fail ("debugLoc.hasTrivialDestructor() && \"Expected trivial destructor\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1047, __PRETTY_FUNCTION__))
;
1048 assert(NumValues == VTs.NumVTs &&((NumValues == VTs.NumVTs && "NumValues wasn't wide enough for its operands!"
) ? static_cast<void> (0) : __assert_fail ("NumValues == VTs.NumVTs && \"NumValues wasn't wide enough for its operands!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1049, __PRETTY_FUNCTION__))
1049 "NumValues wasn't wide enough for its operands!")((NumValues == VTs.NumVTs && "NumValues wasn't wide enough for its operands!"
) ? static_cast<void> (0) : __assert_fail ("NumValues == VTs.NumVTs && \"NumValues wasn't wide enough for its operands!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1049, __PRETTY_FUNCTION__))
;
1050 }
1051
1052 /// Release the operands and set this node to have zero operands.
1053 void DropOperands();
1054};
1055
1056/// Wrapper class for IR location info (IR ordering and DebugLoc) to be passed
1057/// into SDNode creation functions.
1058/// When an SDNode is created from the DAGBuilder, the DebugLoc is extracted
1059/// from the original Instruction, and IROrder is the ordinal position of
1060/// the instruction.
1061/// When an SDNode is created after the DAG is being built, both DebugLoc and
1062/// the IROrder are propagated from the original SDNode.
1063/// So SDLoc class provides two constructors besides the default one, one to
1064/// be used by the DAGBuilder, the other to be used by others.
1065class SDLoc {
1066private:
1067 DebugLoc DL;
1068 int IROrder = 0;
1069
1070public:
1071 SDLoc() = default;
1072 SDLoc(const SDNode *N) : DL(N->getDebugLoc()), IROrder(N->getIROrder()) {}
1073 SDLoc(const SDValue V) : SDLoc(V.getNode()) {}
1074 SDLoc(const Instruction *I, int Order) : IROrder(Order) {
1075 assert(Order >= 0 && "bad IROrder")((Order >= 0 && "bad IROrder") ? static_cast<void
> (0) : __assert_fail ("Order >= 0 && \"bad IROrder\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1075, __PRETTY_FUNCTION__))
;
1076 if (I)
1077 DL = I->getDebugLoc();
1078 }
1079
1080 unsigned getIROrder() const { return IROrder; }
1081 const DebugLoc &getDebugLoc() const { return DL; }
1082};
1083
1084// Define inline functions from the SDValue class.
1085
1086inline SDValue::SDValue(SDNode *node, unsigned resno)
1087 : Node(node), ResNo(resno) {
1088 // Explicitly check for !ResNo to avoid use-after-free, because there are
1089 // callers that use SDValue(N, 0) with a deleted N to indicate successful
1090 // combines.
1091 assert((!Node || !ResNo || ResNo < Node->getNumValues()) &&(((!Node || !ResNo || ResNo < Node->getNumValues()) &&
"Invalid result number for the given node!") ? static_cast<
void> (0) : __assert_fail ("(!Node || !ResNo || ResNo < Node->getNumValues()) && \"Invalid result number for the given node!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1092, __PRETTY_FUNCTION__))
1092 "Invalid result number for the given node!")(((!Node || !ResNo || ResNo < Node->getNumValues()) &&
"Invalid result number for the given node!") ? static_cast<
void> (0) : __assert_fail ("(!Node || !ResNo || ResNo < Node->getNumValues()) && \"Invalid result number for the given node!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1092, __PRETTY_FUNCTION__))
;
1093 assert(ResNo < -2U && "Cannot use result numbers reserved for DenseMaps.")((ResNo < -2U && "Cannot use result numbers reserved for DenseMaps."
) ? static_cast<void> (0) : __assert_fail ("ResNo < -2U && \"Cannot use result numbers reserved for DenseMaps.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1093, __PRETTY_FUNCTION__))
;
1094}
1095
1096inline unsigned SDValue::getOpcode() const {
1097 return Node->getOpcode();
1098}
1099
1100inline EVT SDValue::getValueType() const {
1101 return Node->getValueType(ResNo);
43
Called C++ object pointer is null
1102}
1103
1104inline unsigned SDValue::getNumOperands() const {
1105 return Node->getNumOperands();
1106}
1107
1108inline const SDValue &SDValue::getOperand(unsigned i) const {
1109 return Node->getOperand(i);
1110}
1111
1112inline uint64_t SDValue::getConstantOperandVal(unsigned i) const {
1113 return Node->getConstantOperandVal(i);
1114}
1115
1116inline const APInt &SDValue::getConstantOperandAPInt(unsigned i) const {
1117 return Node->getConstantOperandAPInt(i);
1118}
1119
1120inline bool SDValue::isTargetOpcode() const {
1121 return Node->isTargetOpcode();
1122}
1123
1124inline bool SDValue::isTargetMemoryOpcode() const {
1125 return Node->isTargetMemoryOpcode();
1126}
1127
1128inline bool SDValue::isMachineOpcode() const {
1129 return Node->isMachineOpcode();
1130}
1131
1132inline unsigned SDValue::getMachineOpcode() const {
1133 return Node->getMachineOpcode();
1134}
1135
1136inline bool SDValue::isUndef() const {
1137 return Node->isUndef();
1138}
1139
1140inline bool SDValue::use_empty() const {
1141 return !Node->hasAnyUseOfValue(ResNo);
1142}
1143
1144inline bool SDValue::hasOneUse() const {
1145 return Node->hasNUsesOfValue(1, ResNo);
1146}
1147
1148inline const DebugLoc &SDValue::getDebugLoc() const {
1149 return Node->getDebugLoc();
1150}
1151
1152inline void SDValue::dump() const {
1153 return Node->dump();
1154}
1155
1156inline void SDValue::dump(const SelectionDAG *G) const {
1157 return Node->dump(G);
1158}
1159
1160inline void SDValue::dumpr() const {
1161 return Node->dumpr();
1162}
1163
1164inline void SDValue::dumpr(const SelectionDAG *G) const {
1165 return Node->dumpr(G);
1166}
1167
1168// Define inline functions from the SDUse class.
1169
1170inline void SDUse::set(const SDValue &V) {
1171 if (Val.getNode()) removeFromList();
1172 Val = V;
1173 if (V.getNode()) V.getNode()->addUse(*this);
1174}
1175
1176inline void SDUse::setInitial(const SDValue &V) {
1177 Val = V;
1178 V.getNode()->addUse(*this);
1179}
1180
1181inline void SDUse::setNode(SDNode *N) {
1182 if (Val.getNode()) removeFromList();
1183 Val.setNode(N);
1184 if (N) N->addUse(*this);
1185}
1186
1187/// This class is used to form a handle around another node that
1188/// is persistent and is updated across invocations of replaceAllUsesWith on its
1189/// operand. This node should be directly created by end-users and not added to
1190/// the AllNodes list.
1191class HandleSDNode : public SDNode {
1192 SDUse Op;
1193
1194public:
1195 explicit HandleSDNode(SDValue X)
1196 : SDNode(ISD::HANDLENODE, 0, DebugLoc(), getSDVTList(MVT::Other)) {
1197 // HandleSDNodes are never inserted into the DAG, so they won't be
1198 // auto-numbered. Use ID 65535 as a sentinel.
1199 PersistentId = 0xffff;
1200
1201 // Manually set up the operand list. This node type is special in that it's
1202 // always stack allocated and SelectionDAG does not manage its operands.
1203 // TODO: This should either (a) not be in the SDNode hierarchy, or (b) not
1204 // be so special.
1205 Op.setUser(this);
1206 Op.setInitial(X);
1207 NumOperands = 1;
1208 OperandList = &Op;
1209 }
1210 ~HandleSDNode();
1211
1212 const SDValue &getValue() const { return Op; }
1213};
1214
1215class AddrSpaceCastSDNode : public SDNode {
1216private:
1217 unsigned SrcAddrSpace;
1218 unsigned DestAddrSpace;
1219
1220public:
1221 AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, EVT VT,
1222 unsigned SrcAS, unsigned DestAS);
1223
1224 unsigned getSrcAddressSpace() const { return SrcAddrSpace; }
1225 unsigned getDestAddressSpace() const { return DestAddrSpace; }
1226
1227 static bool classof(const SDNode *N) {
1228 return N->getOpcode() == ISD::ADDRSPACECAST;
1229 }
1230};
1231
1232/// This is an abstract virtual class for memory operations.
1233class MemSDNode : public SDNode {
1234private:
1235 // VT of in-memory value.
1236 EVT MemoryVT;
1237
1238protected:
1239 /// Memory reference information.
1240 MachineMemOperand *MMO;
1241
1242public:
1243 MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs,
1244 EVT memvt, MachineMemOperand *MMO);
1245
1246 bool readMem() const { return MMO->isLoad(); }
1247 bool writeMem() const { return MMO->isStore(); }
1248
1249 /// Returns alignment and volatility of the memory access
1250 Align getOriginalAlign() const { return MMO->getBaseAlign(); }
1251 Align getAlign() const { return MMO->getAlign(); }
1252 LLVM_ATTRIBUTE_DEPRECATED(unsigned getOriginalAlignment() const,unsigned getOriginalAlignment() const __attribute__((deprecated
("Use getOriginalAlign() instead")))
1253 "Use getOriginalAlign() instead")unsigned getOriginalAlignment() const __attribute__((deprecated
("Use getOriginalAlign() instead")))
{
1254 return MMO->getBaseAlign().value();
1255 }
1256 // FIXME: Remove once transition to getAlign is over.
1257 unsigned getAlignment() const { return MMO->getAlign().value(); }
1258
1259 /// Return the SubclassData value, without HasDebugValue. This contains an
1260 /// encoding of the volatile flag, as well as bits used by subclasses. This
1261 /// function should only be used to compute a FoldingSetNodeID value.
1262 /// The HasDebugValue bit is masked out because CSE map needs to match
1263 /// nodes with debug info with nodes without debug info. Same is about
1264 /// isDivergent bit.
1265 unsigned getRawSubclassData() const {
1266 uint16_t Data;
1267 union {
1268 char RawSDNodeBits[sizeof(uint16_t)];
1269 SDNodeBitfields SDNodeBits;
1270 };
1271 memcpy(&RawSDNodeBits, &this->RawSDNodeBits, sizeof(this->RawSDNodeBits));
1272 SDNodeBits.HasDebugValue = 0;
1273 SDNodeBits.IsDivergent = false;
1274 memcpy(&Data, &RawSDNodeBits, sizeof(RawSDNodeBits));
1275 return Data;
1276 }
1277
1278 bool isVolatile() const { return MemSDNodeBits.IsVolatile; }
1279 bool isNonTemporal() const { return MemSDNodeBits.IsNonTemporal; }
1280 bool isDereferenceable() const { return MemSDNodeBits.IsDereferenceable; }
1281 bool isInvariant() const { return MemSDNodeBits.IsInvariant; }
1282
1283 // Returns the offset from the location of the access.
1284 int64_t getSrcValueOffset() const { return MMO->getOffset(); }
1285
1286 /// Returns the AA info that describes the dereference.
1287 AAMDNodes getAAInfo() const { return MMO->getAAInfo(); }
1288
1289 /// Returns the Ranges that describes the dereference.
1290 const MDNode *getRanges() const { return MMO->getRanges(); }
1291
1292 /// Returns the synchronization scope ID for this memory operation.
1293 SyncScope::ID getSyncScopeID() const { return MMO->getSyncScopeID(); }
1294
1295 /// Return the atomic ordering requirements for this memory operation. For
1296 /// cmpxchg atomic operations, return the atomic ordering requirements when
1297 /// store occurs.
1298 AtomicOrdering getOrdering() const { return MMO->getOrdering(); }
1299
1300 /// Return true if the memory operation ordering is Unordered or higher.
1301 bool isAtomic() const { return MMO->isAtomic(); }
1302
1303 /// Returns true if the memory operation doesn't imply any ordering
1304 /// constraints on surrounding memory operations beyond the normal memory
1305 /// aliasing rules.
1306 bool isUnordered() const { return MMO->isUnordered(); }
1307
1308 /// Returns true if the memory operation is neither atomic or volatile.
1309 bool isSimple() const { return !isAtomic() && !isVolatile(); }
1310
1311 /// Return the type of the in-memory value.
1312 EVT getMemoryVT() const { return MemoryVT; }
1313
1314 /// Return a MachineMemOperand object describing the memory
1315 /// reference performed by operation.
1316 MachineMemOperand *getMemOperand() const { return MMO; }
1317
1318 const MachinePointerInfo &getPointerInfo() const {
1319 return MMO->getPointerInfo();
1320 }
1321
1322 /// Return the address space for the associated pointer
1323 unsigned getAddressSpace() const {
1324 return getPointerInfo().getAddrSpace();
1325 }
1326
1327 /// Update this MemSDNode's MachineMemOperand information
1328 /// to reflect the alignment of NewMMO, if it has a greater alignment.
1329 /// This must only be used when the new alignment applies to all users of
1330 /// this MachineMemOperand.
1331 void refineAlignment(const MachineMemOperand *NewMMO) {
1332 MMO->refineAlignment(NewMMO);
1333 }
1334
1335 const SDValue &getChain() const { return getOperand(0); }
1336
1337 const SDValue &getBasePtr() const {
1338 switch (getOpcode()) {
1339 case ISD::STORE:
1340 case ISD::MSTORE:
1341 return getOperand(2);
1342 case ISD::MGATHER:
1343 case ISD::MSCATTER:
1344 return getOperand(3);
1345 default:
1346 return getOperand(1);
1347 }
1348 }
1349
1350 // Methods to support isa and dyn_cast
1351 static bool classof(const SDNode *N) {
1352 // For some targets, we lower some target intrinsics to a MemIntrinsicNode
1353 // with either an intrinsic or a target opcode.
1354 return N->getOpcode() == ISD::LOAD ||
1355 N->getOpcode() == ISD::STORE ||
1356 N->getOpcode() == ISD::PREFETCH ||
1357 N->getOpcode() == ISD::ATOMIC_CMP_SWAP ||
1358 N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS ||
1359 N->getOpcode() == ISD::ATOMIC_SWAP ||
1360 N->getOpcode() == ISD::ATOMIC_LOAD_ADD ||
1361 N->getOpcode() == ISD::ATOMIC_LOAD_SUB ||
1362 N->getOpcode() == ISD::ATOMIC_LOAD_AND ||
1363 N->getOpcode() == ISD::ATOMIC_LOAD_CLR ||
1364 N->getOpcode() == ISD::ATOMIC_LOAD_OR ||
1365 N->getOpcode() == ISD::ATOMIC_LOAD_XOR ||
1366 N->getOpcode() == ISD::ATOMIC_LOAD_NAND ||
1367 N->getOpcode() == ISD::ATOMIC_LOAD_MIN ||
1368 N->getOpcode() == ISD::ATOMIC_LOAD_MAX ||
1369 N->getOpcode() == ISD::ATOMIC_LOAD_UMIN ||
1370 N->getOpcode() == ISD::ATOMIC_LOAD_UMAX ||
1371 N->getOpcode() == ISD::ATOMIC_LOAD_FADD ||
1372 N->getOpcode() == ISD::ATOMIC_LOAD_FSUB ||
1373 N->getOpcode() == ISD::ATOMIC_LOAD ||
1374 N->getOpcode() == ISD::ATOMIC_STORE ||
1375 N->getOpcode() == ISD::MLOAD ||
1376 N->getOpcode() == ISD::MSTORE ||
1377 N->getOpcode() == ISD::MGATHER ||
1378 N->getOpcode() == ISD::MSCATTER ||
1379 N->isMemIntrinsic() ||
1380 N->isTargetMemoryOpcode();
1381 }
1382};
1383
1384/// This is an SDNode representing atomic operations.
1385class AtomicSDNode : public MemSDNode {
1386public:
1387 AtomicSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTL,
1388 EVT MemVT, MachineMemOperand *MMO)
1389 : MemSDNode(Opc, Order, dl, VTL, MemVT, MMO) {
1390 assert(((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE) ||((((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE
) || MMO->isAtomic()) && "then why are we using an AtomicSDNode?"
) ? static_cast<void> (0) : __assert_fail ("((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE) || MMO->isAtomic()) && \"then why are we using an AtomicSDNode?\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1391, __PRETTY_FUNCTION__))
1391 MMO->isAtomic()) && "then why are we using an AtomicSDNode?")((((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE
) || MMO->isAtomic()) && "then why are we using an AtomicSDNode?"
) ? static_cast<void> (0) : __assert_fail ("((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE) || MMO->isAtomic()) && \"then why are we using an AtomicSDNode?\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1391, __PRETTY_FUNCTION__))
;
1392 }
1393
1394 const SDValue &getBasePtr() const { return getOperand(1); }
1395 const SDValue &getVal() const { return getOperand(2); }
1396
1397 /// Returns true if this SDNode represents cmpxchg atomic operation, false
1398 /// otherwise.
1399 bool isCompareAndSwap() const {
1400 unsigned Op = getOpcode();
1401 return Op == ISD::ATOMIC_CMP_SWAP ||
1402 Op == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS;
1403 }
1404
1405 /// For cmpxchg atomic operations, return the atomic ordering requirements
1406 /// when store does not occur.
1407 AtomicOrdering getFailureOrdering() const {
1408 assert(isCompareAndSwap() && "Must be cmpxchg operation")((isCompareAndSwap() && "Must be cmpxchg operation") ?
static_cast<void> (0) : __assert_fail ("isCompareAndSwap() && \"Must be cmpxchg operation\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1408, __PRETTY_FUNCTION__))
;
1409 return MMO->getFailureOrdering();
1410 }
1411
1412 // Methods to support isa and dyn_cast
1413 static bool classof(const SDNode *N) {
1414 return N->getOpcode() == ISD::ATOMIC_CMP_SWAP ||
1415 N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS ||
1416 N->getOpcode() == ISD::ATOMIC_SWAP ||
1417 N->getOpcode() == ISD::ATOMIC_LOAD_ADD ||
1418 N->getOpcode() == ISD::ATOMIC_LOAD_SUB ||
1419 N->getOpcode() == ISD::ATOMIC_LOAD_AND ||
1420 N->getOpcode() == ISD::ATOMIC_LOAD_CLR ||
1421 N->getOpcode() == ISD::ATOMIC_LOAD_OR ||
1422 N->getOpcode() == ISD::ATOMIC_LOAD_XOR ||
1423 N->getOpcode() == ISD::ATOMIC_LOAD_NAND ||
1424 N->getOpcode() == ISD::ATOMIC_LOAD_MIN ||
1425 N->getOpcode() == ISD::ATOMIC_LOAD_MAX ||
1426 N->getOpcode() == ISD::ATOMIC_LOAD_UMIN ||
1427 N->getOpcode() == ISD::ATOMIC_LOAD_UMAX ||
1428 N->getOpcode() == ISD::ATOMIC_LOAD_FADD ||
1429 N->getOpcode() == ISD::ATOMIC_LOAD_FSUB ||
1430 N->getOpcode() == ISD::ATOMIC_LOAD ||
1431 N->getOpcode() == ISD::ATOMIC_STORE;
1432 }
1433};
1434
1435/// This SDNode is used for target intrinsics that touch
1436/// memory and need an associated MachineMemOperand. Its opcode may be
1437/// INTRINSIC_VOID, INTRINSIC_W_CHAIN, PREFETCH, or a target-specific opcode
1438/// with a value not less than FIRST_TARGET_MEMORY_OPCODE.
1439class MemIntrinsicSDNode : public MemSDNode {
1440public:
1441 MemIntrinsicSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
1442 SDVTList VTs, EVT MemoryVT, MachineMemOperand *MMO)
1443 : MemSDNode(Opc, Order, dl, VTs, MemoryVT, MMO) {
1444 SDNodeBits.IsMemIntrinsic = true;
1445 }
1446
1447 // Methods to support isa and dyn_cast
1448 static bool classof(const SDNode *N) {
1449 // We lower some target intrinsics to their target opcode
1450 // early a node with a target opcode can be of this class
1451 return N->isMemIntrinsic() ||
1452 N->getOpcode() == ISD::PREFETCH ||
1453 N->isTargetMemoryOpcode();
1454 }
1455};
1456
1457/// This SDNode is used to implement the code generator
1458/// support for the llvm IR shufflevector instruction. It combines elements
1459/// from two input vectors into a new input vector, with the selection and
1460/// ordering of elements determined by an array of integers, referred to as
1461/// the shuffle mask. For input vectors of width N, mask indices of 0..N-1
1462/// refer to elements from the LHS input, and indices from N to 2N-1 the RHS.
1463/// An index of -1 is treated as undef, such that the code generator may put
1464/// any value in the corresponding element of the result.
1465class ShuffleVectorSDNode : public SDNode {
1466 // The memory for Mask is owned by the SelectionDAG's OperandAllocator, and
1467 // is freed when the SelectionDAG object is destroyed.
1468 const int *Mask;
1469
1470protected:
1471 friend class SelectionDAG;
1472
1473 ShuffleVectorSDNode(EVT VT, unsigned Order, const DebugLoc &dl, const int *M)
1474 : SDNode(ISD::VECTOR_SHUFFLE, Order, dl, getSDVTList(VT)), Mask(M) {}
1475
1476public:
1477 ArrayRef<int> getMask() const {
1478 EVT VT = getValueType(0);
1479 return makeArrayRef(Mask, VT.getVectorNumElements());
1480 }
1481
1482 int getMaskElt(unsigned Idx) const {
1483 assert(Idx < getValueType(0).getVectorNumElements() && "Idx out of range!")((Idx < getValueType(0).getVectorNumElements() && "Idx out of range!"
) ? static_cast<void> (0) : __assert_fail ("Idx < getValueType(0).getVectorNumElements() && \"Idx out of range!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1483, __PRETTY_FUNCTION__))
;
1484 return Mask[Idx];
1485 }
1486
1487 bool isSplat() const { return isSplatMask(Mask, getValueType(0)); }
1488
1489 int getSplatIndex() const {
1490 assert(isSplat() && "Cannot get splat index for non-splat!")((isSplat() && "Cannot get splat index for non-splat!"
) ? static_cast<void> (0) : __assert_fail ("isSplat() && \"Cannot get splat index for non-splat!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1490, __PRETTY_FUNCTION__))
;
1491 EVT VT = getValueType(0);
1492 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1493 if (Mask[i] >= 0)
1494 return Mask[i];
1495
1496 // We can choose any index value here and be correct because all elements
1497 // are undefined. Return 0 for better potential for callers to simplify.
1498 return 0;
1499 }
1500
1501 static bool isSplatMask(const int *Mask, EVT VT);
1502
1503 /// Change values in a shuffle permute mask assuming
1504 /// the two vector operands have swapped position.
1505 static void commuteMask(MutableArrayRef<int> Mask) {
1506 unsigned NumElems = Mask.size();
1507 for (unsigned i = 0; i != NumElems; ++i) {
1508 int idx = Mask[i];
1509 if (idx < 0)
1510 continue;
1511 else if (idx < (int)NumElems)
1512 Mask[i] = idx + NumElems;
1513 else
1514 Mask[i] = idx - NumElems;
1515 }
1516 }
1517
1518 static bool classof(const SDNode *N) {
1519 return N->getOpcode() == ISD::VECTOR_SHUFFLE;
1520 }
1521};
1522
1523class ConstantSDNode : public SDNode {
1524 friend class SelectionDAG;
1525
1526 const ConstantInt *Value;
1527
1528 ConstantSDNode(bool isTarget, bool isOpaque, const ConstantInt *val, EVT VT)
1529 : SDNode(isTarget ? ISD::TargetConstant : ISD::Constant, 0, DebugLoc(),
1530 getSDVTList(VT)),
1531 Value(val) {
1532 ConstantSDNodeBits.IsOpaque = isOpaque;
1533 }
1534
1535public:
1536 const ConstantInt *getConstantIntValue() const { return Value; }
1537 const APInt &getAPIntValue() const { return Value->getValue(); }
1538 uint64_t getZExtValue() const { return Value->getZExtValue(); }
1539 int64_t getSExtValue() const { return Value->getSExtValue(); }
1540 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX(18446744073709551615UL)) {
1541 return Value->getLimitedValue(Limit);
1542 }
1543 MaybeAlign getMaybeAlignValue() const { return Value->getMaybeAlignValue(); }
1544 Align getAlignValue() const { return Value->getAlignValue(); }
1545
1546 bool isOne() const { return Value->isOne(); }
1547 bool isNullValue() const { return Value->isZero(); }
1548 bool isAllOnesValue() const { return Value->isMinusOne(); }
1549
1550 bool isOpaque() const { return ConstantSDNodeBits.IsOpaque; }
1551
1552 static bool classof(const SDNode *N) {
1553 return N->getOpcode() == ISD::Constant ||
1554 N->getOpcode() == ISD::TargetConstant;
1555 }
1556};
1557
1558uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
1559 return cast<ConstantSDNode>(getOperand(Num))->getZExtValue();
1560}
1561
1562const APInt &SDNode::getConstantOperandAPInt(unsigned Num) const {
1563 return cast<ConstantSDNode>(getOperand(Num))->getAPIntValue();
1564}
1565
1566class ConstantFPSDNode : public SDNode {
1567 friend class SelectionDAG;
1568
1569 const ConstantFP *Value;
1570
1571 ConstantFPSDNode(bool isTarget, const ConstantFP *val, EVT VT)
1572 : SDNode(isTarget ? ISD::TargetConstantFP : ISD::ConstantFP, 0,
1573 DebugLoc(), getSDVTList(VT)),
1574 Value(val) {}
1575
1576public:
1577 const APFloat& getValueAPF() const { return Value->getValueAPF(); }
1578 const ConstantFP *getConstantFPValue() const { return Value; }
1579
1580 /// Return true if the value is positive or negative zero.
1581 bool isZero() const { return Value->isZero(); }
1582
1583 /// Return true if the value is a NaN.
1584 bool isNaN() const { return Value->isNaN(); }
1585
1586 /// Return true if the value is an infinity
1587 bool isInfinity() const { return Value->isInfinity(); }
1588
1589 /// Return true if the value is negative.
1590 bool isNegative() const { return Value->isNegative(); }
1591
1592 /// We don't rely on operator== working on double values, as
1593 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
1594 /// As such, this method can be used to do an exact bit-for-bit comparison of
1595 /// two floating point values.
1596
1597 /// We leave the version with the double argument here because it's just so
1598 /// convenient to write "2.0" and the like. Without this function we'd
1599 /// have to duplicate its logic everywhere it's called.
1600 bool isExactlyValue(double V) const {
1601 return Value->getValueAPF().isExactlyValue(V);
1602 }
1603 bool isExactlyValue(const APFloat& V) const;
1604
1605 static bool isValueValidForType(EVT VT, const APFloat& Val);
1606
1607 static bool classof(const SDNode *N) {
1608 return N->getOpcode() == ISD::ConstantFP ||
1609 N->getOpcode() == ISD::TargetConstantFP;
1610 }
1611};
1612
1613/// Returns true if \p V is a constant integer zero.
1614bool isNullConstant(SDValue V);
1615
1616/// Returns true if \p V is an FP constant with a value of positive zero.
1617bool isNullFPConstant(SDValue V);
1618
1619/// Returns true if \p V is an integer constant with all bits set.
1620bool isAllOnesConstant(SDValue V);
1621
1622/// Returns true if \p V is a constant integer one.
1623bool isOneConstant(SDValue V);
1624
1625/// Return the non-bitcasted source operand of \p V if it exists.
1626/// If \p V is not a bitcasted value, it is returned as-is.
1627SDValue peekThroughBitcasts(SDValue V);
1628
1629/// Return the non-bitcasted and one-use source operand of \p V if it exists.
1630/// If \p V is not a bitcasted one-use value, it is returned as-is.
1631SDValue peekThroughOneUseBitcasts(SDValue V);
1632
1633/// Return the non-extracted vector source operand of \p V if it exists.
1634/// If \p V is not an extracted subvector, it is returned as-is.
1635SDValue peekThroughExtractSubvectors(SDValue V);
1636
1637/// Returns true if \p V is a bitwise not operation. Assumes that an all ones
1638/// constant is canonicalized to be operand 1.
1639bool isBitwiseNot(SDValue V, bool AllowUndefs = false);
1640
1641/// Returns the SDNode if it is a constant splat BuildVector or constant int.
1642ConstantSDNode *isConstOrConstSplat(SDValue N, bool AllowUndefs = false,
1643 bool AllowTruncation = false);
1644
1645/// Returns the SDNode if it is a demanded constant splat BuildVector or
1646/// constant int.
1647ConstantSDNode *isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
1648 bool AllowUndefs = false,
1649 bool AllowTruncation = false);
1650
1651/// Returns the SDNode if it is a constant splat BuildVector or constant float.
1652ConstantFPSDNode *isConstOrConstSplatFP(SDValue N, bool AllowUndefs = false);
1653
1654/// Returns the SDNode if it is a demanded constant splat BuildVector or
1655/// constant float.
1656ConstantFPSDNode *isConstOrConstSplatFP(SDValue N, const APInt &DemandedElts,
1657 bool AllowUndefs = false);
1658
1659/// Return true if the value is a constant 0 integer or a splatted vector of
1660/// a constant 0 integer (with no undefs by default).
1661/// Build vector implicit truncation is not an issue for null values.
1662bool isNullOrNullSplat(SDValue V, bool AllowUndefs = false);
1663
1664/// Return true if the value is a constant 1 integer or a splatted vector of a
1665/// constant 1 integer (with no undefs).
1666/// Does not permit build vector implicit truncation.
1667bool isOneOrOneSplat(SDValue V);
1668
1669/// Return true if the value is a constant -1 integer or a splatted vector of a
1670/// constant -1 integer (with no undefs).
1671/// Does not permit build vector implicit truncation.
1672bool isAllOnesOrAllOnesSplat(SDValue V);
1673
1674class GlobalAddressSDNode : public SDNode {
1675 friend class SelectionDAG;
1676
1677 const GlobalValue *TheGlobal;
1678 int64_t Offset;
1679 unsigned TargetFlags;
1680
1681 GlobalAddressSDNode(unsigned Opc, unsigned Order, const DebugLoc &DL,
1682 const GlobalValue *GA, EVT VT, int64_t o,
1683 unsigned TF);
1684
1685public:
1686 const GlobalValue *getGlobal() const { return TheGlobal; }
1687 int64_t getOffset() const { return Offset; }
1688 unsigned getTargetFlags() const { return TargetFlags; }
1689 // Return the address space this GlobalAddress belongs to.
1690 unsigned getAddressSpace() const;
1691
1692 static bool classof(const SDNode *N) {
1693 return N->getOpcode() == ISD::GlobalAddress ||
1694 N->getOpcode() == ISD::TargetGlobalAddress ||
1695 N->getOpcode() == ISD::GlobalTLSAddress ||
1696 N->getOpcode() == ISD::TargetGlobalTLSAddress;
1697 }
1698};
1699
1700class FrameIndexSDNode : public SDNode {
1701 friend class SelectionDAG;
1702
1703 int FI;
1704
1705 FrameIndexSDNode(int fi, EVT VT, bool isTarg)
1706 : SDNode(isTarg ? ISD::TargetFrameIndex : ISD::FrameIndex,
1707 0, DebugLoc(), getSDVTList(VT)), FI(fi) {
1708 }
1709
1710public:
1711 int getIndex() const { return FI; }
1712
1713 static bool classof(const SDNode *N) {
1714 return N->getOpcode() == ISD::FrameIndex ||
1715 N->getOpcode() == ISD::TargetFrameIndex;
1716 }
1717};
1718
1719/// This SDNode is used for LIFETIME_START/LIFETIME_END values, which indicate
1720/// the offet and size that are started/ended in the underlying FrameIndex.
1721class LifetimeSDNode : public SDNode {
1722 friend class SelectionDAG;
1723 int64_t Size;
1724 int64_t Offset; // -1 if offset is unknown.
1725
1726 LifetimeSDNode(unsigned Opcode, unsigned Order, const DebugLoc &dl,
1727 SDVTList VTs, int64_t Size, int64_t Offset)
1728 : SDNode(Opcode, Order, dl, VTs), Size(Size), Offset(Offset) {}
1729public:
1730 int64_t getFrameIndex() const {
1731 return cast<FrameIndexSDNode>(getOperand(1))->getIndex();
1732 }
1733
1734 bool hasOffset() const { return Offset >= 0; }
1735 int64_t getOffset() const {
1736 assert(hasOffset() && "offset is unknown")((hasOffset() && "offset is unknown") ? static_cast<
void> (0) : __assert_fail ("hasOffset() && \"offset is unknown\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1736, __PRETTY_FUNCTION__))
;
1737 return Offset;
1738 }
1739 int64_t getSize() const {
1740 assert(hasOffset() && "offset is unknown")((hasOffset() && "offset is unknown") ? static_cast<
void> (0) : __assert_fail ("hasOffset() && \"offset is unknown\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1740, __PRETTY_FUNCTION__))
;
1741 return Size;
1742 }
1743
1744 // Methods to support isa and dyn_cast
1745 static bool classof(const SDNode *N) {
1746 return N->getOpcode() == ISD::LIFETIME_START ||
1747 N->getOpcode() == ISD::LIFETIME_END;
1748 }
1749};
1750
1751class JumpTableSDNode : public SDNode {
1752 friend class SelectionDAG;
1753
1754 int JTI;
1755 unsigned TargetFlags;
1756
1757 JumpTableSDNode(int jti, EVT VT, bool isTarg, unsigned TF)
1758 : SDNode(isTarg ? ISD::TargetJumpTable : ISD::JumpTable,
1759 0, DebugLoc(), getSDVTList(VT)), JTI(jti), TargetFlags(TF) {
1760 }
1761
1762public:
1763 int getIndex() const { return JTI; }
1764 unsigned getTargetFlags() const { return TargetFlags; }
1765
1766 static bool classof(const SDNode *N) {
1767 return N->getOpcode() == ISD::JumpTable ||
1768 N->getOpcode() == ISD::TargetJumpTable;
1769 }
1770};
1771
1772class ConstantPoolSDNode : public SDNode {
1773 friend class SelectionDAG;
1774
1775 union {
1776 const Constant *ConstVal;
1777 MachineConstantPoolValue *MachineCPVal;
1778 } Val;
1779 int Offset; // It's a MachineConstantPoolValue if top bit is set.
1780 Align Alignment; // Minimum alignment requirement of CP.
1781 unsigned TargetFlags;
1782
1783 ConstantPoolSDNode(bool isTarget, const Constant *c, EVT VT, int o,
1784 Align Alignment, unsigned TF)
1785 : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1786 DebugLoc(), getSDVTList(VT)),
1787 Offset(o), Alignment(Alignment), TargetFlags(TF) {
1788 assert(Offset >= 0 && "Offset is too large")((Offset >= 0 && "Offset is too large") ? static_cast
<void> (0) : __assert_fail ("Offset >= 0 && \"Offset is too large\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1788, __PRETTY_FUNCTION__))
;
1789 Val.ConstVal = c;
1790 }
1791
1792 ConstantPoolSDNode(bool isTarget, MachineConstantPoolValue *v, EVT VT, int o,
1793 Align Alignment, unsigned TF)
1794 : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1795 DebugLoc(), getSDVTList(VT)),
1796 Offset(o), Alignment(Alignment), TargetFlags(TF) {
1797 assert(Offset >= 0 && "Offset is too large")((Offset >= 0 && "Offset is too large") ? static_cast
<void> (0) : __assert_fail ("Offset >= 0 && \"Offset is too large\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1797, __PRETTY_FUNCTION__))
;
1798 Val.MachineCPVal = v;
1799 Offset |= 1 << (sizeof(unsigned)*CHAR_BIT8-1);
1800 }
1801
1802public:
1803 bool isMachineConstantPoolEntry() const {
1804 return Offset < 0;
1805 }
1806
1807 const Constant *getConstVal() const {
1808 assert(!isMachineConstantPoolEntry() && "Wrong constantpool type")((!isMachineConstantPoolEntry() && "Wrong constantpool type"
) ? static_cast<void> (0) : __assert_fail ("!isMachineConstantPoolEntry() && \"Wrong constantpool type\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1808, __PRETTY_FUNCTION__))
;
1809 return Val.ConstVal;
1810 }
1811
1812 MachineConstantPoolValue *getMachineCPVal() const {
1813 assert(isMachineConstantPoolEntry() && "Wrong constantpool type")((isMachineConstantPoolEntry() && "Wrong constantpool type"
) ? static_cast<void> (0) : __assert_fail ("isMachineConstantPoolEntry() && \"Wrong constantpool type\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1813, __PRETTY_FUNCTION__))
;
1814 return Val.MachineCPVal;
1815 }
1816
1817 int getOffset() const {
1818 return Offset & ~(1 << (sizeof(unsigned)*CHAR_BIT8-1));
1819 }
1820
1821 // Return the alignment of this constant pool object, which is either 0 (for
1822 // default alignment) or the desired value.
1823 Align getAlign() const { return Alignment; }
1824 unsigned getTargetFlags() const { return TargetFlags; }
1825
1826 Type *getType() const;
1827
1828 static bool classof(const SDNode *N) {
1829 return N->getOpcode() == ISD::ConstantPool ||
1830 N->getOpcode() == ISD::TargetConstantPool;
1831 }
1832};
1833
1834/// Completely target-dependent object reference.
1835class TargetIndexSDNode : public SDNode {
1836 friend class SelectionDAG;
1837
1838 unsigned TargetFlags;
1839 int Index;
1840 int64_t Offset;
1841
1842public:
1843 TargetIndexSDNode(int Idx, EVT VT, int64_t Ofs, unsigned TF)
1844 : SDNode(ISD::TargetIndex, 0, DebugLoc(), getSDVTList(VT)),
1845 TargetFlags(TF), Index(Idx), Offset(Ofs) {}
1846
1847 unsigned getTargetFlags() const { return TargetFlags; }
1848 int getIndex() const { return Index; }
1849 int64_t getOffset() const { return Offset; }
1850
1851 static bool classof(const SDNode *N) {
1852 return N->getOpcode() == ISD::TargetIndex;
1853 }
1854};
1855
1856class BasicBlockSDNode : public SDNode {
1857 friend class SelectionDAG;
1858
1859 MachineBasicBlock *MBB;
1860
1861 /// Debug info is meaningful and potentially useful here, but we create
1862 /// blocks out of order when they're jumped to, which makes it a bit
1863 /// harder. Let's see if we need it first.
1864 explicit BasicBlockSDNode(MachineBasicBlock *mbb)
1865 : SDNode(ISD::BasicBlock, 0, DebugLoc(), getSDVTList(MVT::Other)), MBB(mbb)
1866 {}
1867
1868public:
1869 MachineBasicBlock *getBasicBlock() const { return MBB; }
1870
1871 static bool classof(const SDNode *N) {
1872 return N->getOpcode() == ISD::BasicBlock;
1873 }
1874};
1875
1876/// A "pseudo-class" with methods for operating on BUILD_VECTORs.
1877class BuildVectorSDNode : public SDNode {
1878public:
1879 // These are constructed as SDNodes and then cast to BuildVectorSDNodes.
1880 explicit BuildVectorSDNode() = delete;
1881
1882 /// Check if this is a constant splat, and if so, find the
1883 /// smallest element size that splats the vector. If MinSplatBits is
1884 /// nonzero, the element size must be at least that large. Note that the
1885 /// splat element may be the entire vector (i.e., a one element vector).
1886 /// Returns the splat element value in SplatValue. Any undefined bits in
1887 /// that value are zero, and the corresponding bits in the SplatUndef mask
1888 /// are set. The SplatBitSize value is set to the splat element size in
1889 /// bits. HasAnyUndefs is set to true if any bits in the vector are
1890 /// undefined. isBigEndian describes the endianness of the target.
1891 bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
1892 unsigned &SplatBitSize, bool &HasAnyUndefs,
1893 unsigned MinSplatBits = 0,
1894 bool isBigEndian = false) const;
1895
1896 /// Returns the demanded splatted value or a null value if this is not a
1897 /// splat.
1898 ///
1899 /// The DemandedElts mask indicates the elements that must be in the splat.
1900 /// If passed a non-null UndefElements bitvector, it will resize it to match
1901 /// the vector width and set the bits where elements are undef.
1902 SDValue getSplatValue(const APInt &DemandedElts,
1903 BitVector *UndefElements = nullptr) const;
1904
1905 /// Returns the splatted value or a null value if this is not a splat.
1906 ///
1907 /// If passed a non-null UndefElements bitvector, it will resize it to match
1908 /// the vector width and set the bits where elements are undef.
1909 SDValue getSplatValue(BitVector *UndefElements = nullptr) const;
1910
1911 /// Returns the demanded splatted constant or null if this is not a constant
1912 /// splat.
1913 ///
1914 /// The DemandedElts mask indicates the elements that must be in the splat.
1915 /// If passed a non-null UndefElements bitvector, it will resize it to match
1916 /// the vector width and set the bits where elements are undef.
1917 ConstantSDNode *
1918 getConstantSplatNode(const APInt &DemandedElts,
1919 BitVector *UndefElements = nullptr) const;
1920
1921 /// Returns the splatted constant or null if this is not a constant
1922 /// splat.
1923 ///
1924 /// If passed a non-null UndefElements bitvector, it will resize it to match
1925 /// the vector width and set the bits where elements are undef.
1926 ConstantSDNode *
1927 getConstantSplatNode(BitVector *UndefElements = nullptr) const;
1928
1929 /// Returns the demanded splatted constant FP or null if this is not a
1930 /// constant FP splat.
1931 ///
1932 /// The DemandedElts mask indicates the elements that must be in the splat.
1933 /// If passed a non-null UndefElements bitvector, it will resize it to match
1934 /// the vector width and set the bits where elements are undef.
1935 ConstantFPSDNode *
1936 getConstantFPSplatNode(const APInt &DemandedElts,
1937 BitVector *UndefElements = nullptr) const;
1938
1939 /// Returns the splatted constant FP or null if this is not a constant
1940 /// FP splat.
1941 ///
1942 /// If passed a non-null UndefElements bitvector, it will resize it to match
1943 /// the vector width and set the bits where elements are undef.
1944 ConstantFPSDNode *
1945 getConstantFPSplatNode(BitVector *UndefElements = nullptr) const;
1946
1947 /// If this is a constant FP splat and the splatted constant FP is an
1948 /// exact power or 2, return the log base 2 integer value. Otherwise,
1949 /// return -1.
1950 ///
1951 /// The BitWidth specifies the necessary bit precision.
1952 int32_t getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
1953 uint32_t BitWidth) const;
1954
1955 bool isConstant() const;
1956
1957 static bool classof(const SDNode *N) {
1958 return N->getOpcode() == ISD::BUILD_VECTOR;
1959 }
1960};
1961
1962/// An SDNode that holds an arbitrary LLVM IR Value. This is
1963/// used when the SelectionDAG needs to make a simple reference to something
1964/// in the LLVM IR representation.
1965///
1966class SrcValueSDNode : public SDNode {
1967 friend class SelectionDAG;
1968
1969 const Value *V;
1970
1971 /// Create a SrcValue for a general value.
1972 explicit SrcValueSDNode(const Value *v)
1973 : SDNode(ISD::SRCVALUE, 0, DebugLoc(), getSDVTList(MVT::Other)), V(v) {}
1974
1975public:
1976 /// Return the contained Value.
1977 const Value *getValue() const { return V; }
1978
1979 static bool classof(const SDNode *N) {
1980 return N->getOpcode() == ISD::SRCVALUE;
1981 }
1982};
1983
1984class MDNodeSDNode : public SDNode {
1985 friend class SelectionDAG;
1986
1987 const MDNode *MD;
1988
1989 explicit MDNodeSDNode(const MDNode *md)
1990 : SDNode(ISD::MDNODE_SDNODE, 0, DebugLoc(), getSDVTList(MVT::Other)), MD(md)
1991 {}
1992
1993public:
1994 const MDNode *getMD() const { return MD; }
1995
1996 static bool classof(const SDNode *N) {
1997 return N->getOpcode() == ISD::MDNODE_SDNODE;
1998 }
1999};
2000
2001class RegisterSDNode : public SDNode {
2002 friend class SelectionDAG;
2003
2004 Register Reg;
2005
2006 RegisterSDNode(Register reg, EVT VT)
2007 : SDNode(ISD::Register, 0, DebugLoc(), getSDVTList(VT)), Reg(reg) {}
2008
2009public:
2010 Register getReg() const { return Reg; }
2011
2012 static bool classof(const SDNode *N) {
2013 return N->getOpcode() == ISD::Register;
2014 }
2015};
2016
2017class RegisterMaskSDNode : public SDNode {
2018 friend class SelectionDAG;
2019
2020 // The memory for RegMask is not owned by the node.
2021 const uint32_t *RegMask;
2022
2023 RegisterMaskSDNode(const uint32_t *mask)
2024 : SDNode(ISD::RegisterMask, 0, DebugLoc(), getSDVTList(MVT::Untyped)),
2025 RegMask(mask) {}
2026
2027public:
2028 const uint32_t *getRegMask() const { return RegMask; }
2029
2030 static bool classof(const SDNode *N) {
2031 return N->getOpcode() == ISD::RegisterMask;
2032 }
2033};
2034
2035class BlockAddressSDNode : public SDNode {
2036 friend class SelectionDAG;
2037
2038 const BlockAddress *BA;
2039 int64_t Offset;
2040 unsigned TargetFlags;
2041
2042 BlockAddressSDNode(unsigned NodeTy, EVT VT, const BlockAddress *ba,
2043 int64_t o, unsigned Flags)
2044 : SDNode(NodeTy, 0, DebugLoc(), getSDVTList(VT)),
2045 BA(ba), Offset(o), TargetFlags(Flags) {}
2046
2047public:
2048 const BlockAddress *getBlockAddress() const { return BA; }
2049 int64_t getOffset() const { return Offset; }
2050 unsigned getTargetFlags() const { return TargetFlags; }
2051
2052 static bool classof(const SDNode *N) {
2053 return N->getOpcode() == ISD::BlockAddress ||
2054 N->getOpcode() == ISD::TargetBlockAddress;
2055 }
2056};
2057
2058class LabelSDNode : public SDNode {
2059 friend class SelectionDAG;
2060
2061 MCSymbol *Label;
2062
2063 LabelSDNode(unsigned Opcode, unsigned Order, const DebugLoc &dl, MCSymbol *L)
2064 : SDNode(Opcode, Order, dl, getSDVTList(MVT::Other)), Label(L) {
2065 assert(LabelSDNode::classof(this) && "not a label opcode")((LabelSDNode::classof(this) && "not a label opcode")
? static_cast<void> (0) : __assert_fail ("LabelSDNode::classof(this) && \"not a label opcode\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2065, __PRETTY_FUNCTION__))
;
2066 }
2067
2068public:
2069 MCSymbol *getLabel() const { return Label; }
2070
2071 static bool classof(const SDNode *N) {
2072 return N->getOpcode() == ISD::EH_LABEL ||
2073 N->getOpcode() == ISD::ANNOTATION_LABEL;
2074 }
2075};
2076
2077class ExternalSymbolSDNode : public SDNode {
2078 friend class SelectionDAG;
2079
2080 const char *Symbol;
2081 unsigned TargetFlags;
2082
2083 ExternalSymbolSDNode(bool isTarget, const char *Sym, unsigned TF, EVT VT)
2084 : SDNode(isTarget ? ISD::TargetExternalSymbol : ISD::ExternalSymbol, 0,
2085 DebugLoc(), getSDVTList(VT)),
2086 Symbol(Sym), TargetFlags(TF) {}
2087
2088public:
2089 const char *getSymbol() const { return Symbol; }
2090 unsigned getTargetFlags() const { return TargetFlags; }
2091
2092 static bool classof(const SDNode *N) {
2093 return N->getOpcode() == ISD::ExternalSymbol ||
2094 N->getOpcode() == ISD::TargetExternalSymbol;
2095 }
2096};
2097
2098class MCSymbolSDNode : public SDNode {
2099 friend class SelectionDAG;
2100
2101 MCSymbol *Symbol;
2102
2103 MCSymbolSDNode(MCSymbol *Symbol, EVT VT)
2104 : SDNode(ISD::MCSymbol, 0, DebugLoc(), getSDVTList(VT)), Symbol(Symbol) {}
2105
2106public:
2107 MCSymbol *getMCSymbol() const { return Symbol; }
2108
2109 static bool classof(const SDNode *N) {
2110 return N->getOpcode() == ISD::MCSymbol;
2111 }
2112};
2113
2114class CondCodeSDNode : public SDNode {
2115 friend class SelectionDAG;
2116
2117 ISD::CondCode Condition;
2118
2119 explicit CondCodeSDNode(ISD::CondCode Cond)
2120 : SDNode(ISD::CONDCODE, 0, DebugLoc(), getSDVTList(MVT::Other)),
2121 Condition(Cond) {}
2122
2123public:
2124 ISD::CondCode get() const { return Condition; }
2125
2126 static bool classof(const SDNode *N) {
2127 return N->getOpcode() == ISD::CONDCODE;
2128 }
2129};
2130
2131/// This class is used to represent EVT's, which are used
2132/// to parameterize some operations.
2133class VTSDNode : public SDNode {
2134 friend class SelectionDAG;
2135
2136 EVT ValueType;
2137
2138 explicit VTSDNode(EVT VT)
2139 : SDNode(ISD::VALUETYPE, 0, DebugLoc(), getSDVTList(MVT::Other)),
2140 ValueType(VT) {}
2141
2142public:
2143 EVT getVT() const { return ValueType; }
2144
2145 static bool classof(const SDNode *N) {
2146 return N->getOpcode() == ISD::VALUETYPE;
2147 }
2148};
2149
2150/// Base class for LoadSDNode and StoreSDNode
2151class LSBaseSDNode : public MemSDNode {
2152public:
2153 LSBaseSDNode(ISD::NodeType NodeTy, unsigned Order, const DebugLoc &dl,
2154 SDVTList VTs, ISD::MemIndexedMode AM, EVT MemVT,
2155 MachineMemOperand *MMO)
2156 : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2157 LSBaseSDNodeBits.AddressingMode = AM;
2158 assert(getAddressingMode() == AM && "Value truncated")((getAddressingMode() == AM && "Value truncated") ? static_cast
<void> (0) : __assert_fail ("getAddressingMode() == AM && \"Value truncated\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2158, __PRETTY_FUNCTION__))
;
2159 }
2160
2161 const SDValue &getOffset() const {
2162 return getOperand(getOpcode() == ISD::LOAD ? 2 : 3);
2163 }
2164
2165 /// Return the addressing mode for this load or store:
2166 /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
2167 ISD::MemIndexedMode getAddressingMode() const {
2168 return static_cast<ISD::MemIndexedMode>(LSBaseSDNodeBits.AddressingMode);
2169 }
2170
2171 /// Return true if this is a pre/post inc/dec load/store.
2172 bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
2173
2174 /// Return true if this is NOT a pre/post inc/dec load/store.
2175 bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
2176
2177 static bool classof(const SDNode *N) {
2178 return N->getOpcode() == ISD::LOAD ||
2179 N->getOpcode() == ISD::STORE;
2180 }
2181};
2182
2183/// This class is used to represent ISD::LOAD nodes.
2184class LoadSDNode : public LSBaseSDNode {
2185 friend class SelectionDAG;
2186
2187 LoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2188 ISD::MemIndexedMode AM, ISD::LoadExtType ETy, EVT MemVT,
2189 MachineMemOperand *MMO)
2190 : LSBaseSDNode(ISD::LOAD, Order, dl, VTs, AM, MemVT, MMO) {
2191 LoadSDNodeBits.ExtTy = ETy;
2192 assert(readMem() && "Load MachineMemOperand is not a load!")((readMem() && "Load MachineMemOperand is not a load!"
) ? static_cast<void> (0) : __assert_fail ("readMem() && \"Load MachineMemOperand is not a load!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2192, __PRETTY_FUNCTION__))
;
2193 assert(!writeMem() && "Load MachineMemOperand is a store!")((!writeMem() && "Load MachineMemOperand is a store!"
) ? static_cast<void> (0) : __assert_fail ("!writeMem() && \"Load MachineMemOperand is a store!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2193, __PRETTY_FUNCTION__))
;
2194 }
2195
2196public:
2197 /// Return whether this is a plain node,
2198 /// or one of the varieties of value-extending loads.
2199 ISD::LoadExtType getExtensionType() const {
2200 return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy);
2201 }
2202
2203 const SDValue &getBasePtr() const { return getOperand(1); }
2204 const SDValue &getOffset() const { return getOperand(2); }
2205
2206 static bool classof(const SDNode *N) {
2207 return N->getOpcode() == ISD::LOAD;
2208 }
2209};
2210
2211/// This class is used to represent ISD::STORE nodes.
2212class StoreSDNode : public LSBaseSDNode {
2213 friend class SelectionDAG;
2214
2215 StoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2216 ISD::MemIndexedMode AM, bool isTrunc, EVT MemVT,
2217 MachineMemOperand *MMO)
2218 : LSBaseSDNode(ISD::STORE, Order, dl, VTs, AM, MemVT, MMO) {
2219 StoreSDNodeBits.IsTruncating = isTrunc;
2220 assert(!readMem() && "Store MachineMemOperand is a load!")((!readMem() && "Store MachineMemOperand is a load!")
? static_cast<void> (0) : __assert_fail ("!readMem() && \"Store MachineMemOperand is a load!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2220, __PRETTY_FUNCTION__))
;
2221 assert(writeMem() && "Store MachineMemOperand is not a store!")((writeMem() && "Store MachineMemOperand is not a store!"
) ? static_cast<void> (0) : __assert_fail ("writeMem() && \"Store MachineMemOperand is not a store!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2221, __PRETTY_FUNCTION__))
;
2222 }
2223
2224public:
2225 /// Return true if the op does a truncation before store.
2226 /// For integers this is the same as doing a TRUNCATE and storing the result.
2227 /// For floats, it is the same as doing an FP_ROUND and storing the result.
2228 bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2229 void setTruncatingStore(bool Truncating) {
2230 StoreSDNodeBits.IsTruncating = Truncating;
2231 }
2232
2233 const SDValue &getValue() const { return getOperand(1); }
2234 const SDValue &getBasePtr() const { return getOperand(2); }
2235 const SDValue &getOffset() const { return getOperand(3); }
2236
2237 static bool classof(const SDNode *N) {
2238 return N->getOpcode() == ISD::STORE;
2239 }
2240};
2241
2242/// This base class is used to represent MLOAD and MSTORE nodes
2243class MaskedLoadStoreSDNode : public MemSDNode {
2244public:
2245 friend class SelectionDAG;
2246
2247 MaskedLoadStoreSDNode(ISD::NodeType NodeTy, unsigned Order,
2248 const DebugLoc &dl, SDVTList VTs,
2249 ISD::MemIndexedMode AM, EVT MemVT,
2250 MachineMemOperand *MMO)
2251 : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2252 LSBaseSDNodeBits.AddressingMode = AM;
2253 assert(getAddressingMode() == AM && "Value truncated")((getAddressingMode() == AM && "Value truncated") ? static_cast
<void> (0) : __assert_fail ("getAddressingMode() == AM && \"Value truncated\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2253, __PRETTY_FUNCTION__))
;
2254 }
2255
2256 // MaskedLoadSDNode (Chain, ptr, offset, mask, passthru)
2257 // MaskedStoreSDNode (Chain, data, ptr, offset, mask)
2258 // Mask is a vector of i1 elements
2259 const SDValue &getOffset() const {
2260 return getOperand(getOpcode() == ISD::MLOAD ? 2 : 3);
2261 }
2262 const SDValue &getMask() const {
2263 return getOperand(getOpcode() == ISD::MLOAD ? 3 : 4);
2264 }
2265
2266 /// Return the addressing mode for this load or store:
2267 /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
2268 ISD::MemIndexedMode getAddressingMode() const {
2269 return static_cast<ISD::MemIndexedMode>(LSBaseSDNodeBits.AddressingMode);
2270 }
2271
2272 /// Return true if this is a pre/post inc/dec load/store.
2273 bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
2274
2275 /// Return true if this is NOT a pre/post inc/dec load/store.
2276 bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
2277
2278 static bool classof(const SDNode *N) {
2279 return N->getOpcode() == ISD::MLOAD ||
2280 N->getOpcode() == ISD::MSTORE;
2281 }
2282};
2283
2284/// This class is used to represent an MLOAD node
2285class MaskedLoadSDNode : public MaskedLoadStoreSDNode {
2286public:
2287 friend class SelectionDAG;
2288
2289 MaskedLoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2290 ISD::MemIndexedMode AM, ISD::LoadExtType ETy,
2291 bool IsExpanding, EVT MemVT, MachineMemOperand *MMO)
2292 : MaskedLoadStoreSDNode(ISD::MLOAD, Order, dl, VTs, AM, MemVT, MMO) {
2293 LoadSDNodeBits.ExtTy = ETy;
2294 LoadSDNodeBits.IsExpanding = IsExpanding;
2295 }
2296
2297 ISD::LoadExtType getExtensionType() const {
2298 return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy);
2299 }
2300
2301 const SDValue &getBasePtr() const { return getOperand(1); }
2302 const SDValue &getOffset() const { return getOperand(2); }
2303 const SDValue &getMask() const { return getOperand(3); }
2304 const SDValue &getPassThru() const { return getOperand(4); }
2305
2306 static bool classof(const SDNode *N) {
2307 return N->getOpcode() == ISD::MLOAD;
2308 }
2309
2310 bool isExpandingLoad() const { return LoadSDNodeBits.IsExpanding; }
2311};
2312
2313/// This class is used to represent an MSTORE node
2314class MaskedStoreSDNode : public MaskedLoadStoreSDNode {
2315public:
2316 friend class SelectionDAG;
2317
2318 MaskedStoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2319 ISD::MemIndexedMode AM, bool isTrunc, bool isCompressing,
2320 EVT MemVT, MachineMemOperand *MMO)
2321 : MaskedLoadStoreSDNode(ISD::MSTORE, Order, dl, VTs, AM, MemVT, MMO) {
2322 StoreSDNodeBits.IsTruncating = isTrunc;
2323 StoreSDNodeBits.IsCompressing = isCompressing;
2324 }
2325
2326 /// Return true if the op does a truncation before store.
2327 /// For integers this is the same as doing a TRUNCATE and storing the result.
2328 /// For floats, it is the same as doing an FP_ROUND and storing the result.
2329 bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2330
2331 /// Returns true if the op does a compression to the vector before storing.
2332 /// The node contiguously stores the active elements (integers or floats)
2333 /// in src (those with their respective bit set in writemask k) to unaligned
2334 /// memory at base_addr.
2335 bool isCompressingStore() const { return StoreSDNodeBits.IsCompressing; }
2336
2337 const SDValue &getValue() const { return getOperand(1); }
2338 const SDValue &getBasePtr() const { return getOperand(2); }
2339 const SDValue &getOffset() const { return getOperand(3); }
2340 const SDValue &getMask() const { return getOperand(4); }
2341
2342 static bool classof(const SDNode *N) {
2343 return N->getOpcode() == ISD::MSTORE;
2344 }
2345};
2346
2347/// This is a base class used to represent
2348/// MGATHER and MSCATTER nodes
2349///
2350class MaskedGatherScatterSDNode : public MemSDNode {
2351public:
2352 friend class SelectionDAG;
2353
2354 MaskedGatherScatterSDNode(ISD::NodeType NodeTy, unsigned Order,
2355 const DebugLoc &dl, SDVTList VTs, EVT MemVT,
2356 MachineMemOperand *MMO, ISD::MemIndexType IndexType)
2357 : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2358 LSBaseSDNodeBits.AddressingMode = IndexType;
2359 assert(getIndexType() == IndexType && "Value truncated")((getIndexType() == IndexType && "Value truncated") ?
static_cast<void> (0) : __assert_fail ("getIndexType() == IndexType && \"Value truncated\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2359, __PRETTY_FUNCTION__))
;
2360 }
2361
2362 /// How is Index applied to BasePtr when computing addresses.
2363 ISD::MemIndexType getIndexType() const {
2364 return static_cast<ISD::MemIndexType>(LSBaseSDNodeBits.AddressingMode);
2365 }
2366 bool isIndexScaled() const {
2367 return (getIndexType() == ISD::SIGNED_SCALED) ||
2368 (getIndexType() == ISD::UNSIGNED_SCALED);
2369 }
2370 bool isIndexSigned() const {
2371 return (getIndexType() == ISD::SIGNED_SCALED) ||
2372 (getIndexType() == ISD::SIGNED_UNSCALED);
2373 }
2374
2375 // In the both nodes address is Op1, mask is Op2:
2376 // MaskedGatherSDNode (Chain, passthru, mask, base, index, scale)
2377 // MaskedScatterSDNode (Chain, value, mask, base, index, scale)
2378 // Mask is a vector of i1 elements
2379 const SDValue &getBasePtr() const { return getOperand(3); }
2380 const SDValue &getIndex() const { return getOperand(4); }
2381 const SDValue &getMask() const { return getOperand(2); }
2382 const SDValue &getScale() const { return getOperand(5); }
2383
2384 static bool classof(const SDNode *N) {
2385 return N->getOpcode() == ISD::MGATHER ||
2386 N->getOpcode() == ISD::MSCATTER;
2387 }
2388};
2389
2390/// This class is used to represent an MGATHER node
2391///
2392class MaskedGatherSDNode : public MaskedGatherScatterSDNode {
2393public:
2394 friend class SelectionDAG;
2395
2396 MaskedGatherSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2397 EVT MemVT, MachineMemOperand *MMO,
2398 ISD::MemIndexType IndexType)
2399 : MaskedGatherScatterSDNode(ISD::MGATHER, Order, dl, VTs, MemVT, MMO,
2400 IndexType) {}
2401
2402 const SDValue &getPassThru() const { return getOperand(1); }
2403
2404 static bool classof(const SDNode *N) {
2405 return N->getOpcode() == ISD::MGATHER;
2406 }
2407};
2408
2409/// This class is used to represent an MSCATTER node
2410///
2411class MaskedScatterSDNode : public MaskedGatherScatterSDNode {
2412public:
2413 friend class SelectionDAG;
2414
2415 MaskedScatterSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2416 EVT MemVT, MachineMemOperand *MMO,
2417 ISD::MemIndexType IndexType)
2418 : MaskedGatherScatterSDNode(ISD::MSCATTER, Order, dl, VTs, MemVT, MMO,
2419 IndexType) {}
2420
2421 const SDValue &getValue() const { return getOperand(1); }
2422
2423 static bool classof(const SDNode *N) {
2424 return N->getOpcode() == ISD::MSCATTER;
2425 }
2426};
2427
2428/// An SDNode that represents everything that will be needed
2429/// to construct a MachineInstr. These nodes are created during the
2430/// instruction selection proper phase.
2431///
2432/// Note that the only supported way to set the `memoperands` is by calling the
2433/// `SelectionDAG::setNodeMemRefs` function as the memory management happens
2434/// inside the DAG rather than in the node.
2435class MachineSDNode : public SDNode {
2436private:
2437 friend class SelectionDAG;
2438
2439 MachineSDNode(unsigned Opc, unsigned Order, const DebugLoc &DL, SDVTList VTs)
2440 : SDNode(Opc, Order, DL, VTs) {}
2441
2442 // We use a pointer union between a single `MachineMemOperand` pointer and
2443 // a pointer to an array of `MachineMemOperand` pointers. This is null when
2444 // the number of these is zero, the single pointer variant used when the
2445 // number is one, and the array is used for larger numbers.
2446 //
2447 // The array is allocated via the `SelectionDAG`'s allocator and so will
2448 // always live until the DAG is cleaned up and doesn't require ownership here.
2449 //
2450 // We can't use something simpler like `TinyPtrVector` here because `SDNode`
2451 // subclasses aren't managed in a conforming C++ manner. See the comments on
2452 // `SelectionDAG::MorphNodeTo` which details what all goes on, but the
2453 // constraint here is that these don't manage memory with their constructor or
2454 // destructor and can be initialized to a good state even if they start off
2455 // uninitialized.
2456 PointerUnion<MachineMemOperand *, MachineMemOperand **> MemRefs = {};
2457
2458 // Note that this could be folded into the above `MemRefs` member if doing so
2459 // is advantageous at some point. We don't need to store this in most cases.
2460 // However, at the moment this doesn't appear to make the allocation any
2461 // smaller and makes the code somewhat simpler to read.
2462 int NumMemRefs = 0;
2463
2464public:
2465 using mmo_iterator = ArrayRef<MachineMemOperand *>::const_iterator;
2466
2467 ArrayRef<MachineMemOperand *> memoperands() const {
2468 // Special case the common cases.
2469 if (NumMemRefs == 0)
2470 return {};
2471 if (NumMemRefs == 1)
2472 return makeArrayRef(MemRefs.getAddrOfPtr1(), 1);
2473
2474 // Otherwise we have an actual array.
2475 return makeArrayRef(MemRefs.get<MachineMemOperand **>(), NumMemRefs);
2476 }
2477 mmo_iterator memoperands_begin() const { return memoperands().begin(); }
2478 mmo_iterator memoperands_end() const { return memoperands().end(); }
2479 bool memoperands_empty() const { return memoperands().empty(); }
2480
2481 /// Clear out the memory reference descriptor list.
2482 void clearMemRefs() {
2483 MemRefs = nullptr;
2484 NumMemRefs = 0;
2485 }
2486
2487 static bool classof(const SDNode *N) {
2488 return N->isMachineOpcode();
2489 }
2490};
2491
2492/// An SDNode that records if a register contains a value that is guaranteed to
2493/// be aligned accordingly.
2494class AssertAlignSDNode : public SDNode {
2495 Align Alignment;
2496
2497public:
2498 AssertAlignSDNode(unsigned Order, const DebugLoc &DL, EVT VT, Align A)
2499 : SDNode(ISD::AssertAlign, Order, DL, getSDVTList(VT)), Alignment(A) {}
2500
2501 Align getAlign() const { return Alignment; }
2502
2503 static bool classof(const SDNode *N) {
2504 return N->getOpcode() == ISD::AssertAlign;
2505 }
2506};
2507
2508class SDNodeIterator : public std::iterator<std::forward_iterator_tag,
2509 SDNode, ptrdiff_t> {
2510 const SDNode *Node;
2511 unsigned Operand;
2512
2513 SDNodeIterator(const SDNode *N, unsigned Op) : Node(N), Operand(Op) {}
2514
2515public:
2516 bool operator==(const SDNodeIterator& x) const {
2517 return Operand == x.Operand;
2518 }
2519 bool operator!=(const SDNodeIterator& x) const { return !operator==(x); }
2520
2521 pointer operator*() const {
2522 return Node->getOperand(Operand).getNode();
2523 }
2524 pointer operator->() const { return operator*(); }
2525
2526 SDNodeIterator& operator++() { // Preincrement
2527 ++Operand;
2528 return *this;
2529 }
2530 SDNodeIterator operator++(int) { // Postincrement
2531 SDNodeIterator tmp = *this; ++*this; return tmp;
2532 }
2533 size_t operator-(SDNodeIterator Other) const {
2534 assert(Node == Other.Node &&((Node == Other.Node && "Cannot compare iterators of two different nodes!"
) ? static_cast<void> (0) : __assert_fail ("Node == Other.Node && \"Cannot compare iterators of two different nodes!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2535, __PRETTY_FUNCTION__))
2535 "Cannot compare iterators of two different nodes!")((Node == Other.Node && "Cannot compare iterators of two different nodes!"
) ? static_cast<void> (0) : __assert_fail ("Node == Other.Node && \"Cannot compare iterators of two different nodes!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2535, __PRETTY_FUNCTION__))
;
2536 return Operand - Other.Operand;
2537 }
2538
2539 static SDNodeIterator begin(const SDNode *N) { return SDNodeIterator(N, 0); }
2540 static SDNodeIterator end (const SDNode *N) {
2541 return SDNodeIterator(N, N->getNumOperands());
2542 }
2543
2544 unsigned getOperand() const { return Operand; }
2545 const SDNode *getNode() const { return Node; }
2546};
2547
2548template <> struct GraphTraits<SDNode*> {
2549 using NodeRef = SDNode *;
2550 using ChildIteratorType = SDNodeIterator;
2551
2552 static NodeRef getEntryNode(SDNode *N) { return N; }
2553
2554 static ChildIteratorType child_begin(NodeRef N) {
2555 return SDNodeIterator::begin(N);
2556 }
2557
2558 static ChildIteratorType child_end(NodeRef N) {
2559 return SDNodeIterator::end(N);
2560 }
2561};
2562
2563/// A representation of the largest SDNode, for use in sizeof().
2564///
2565/// This needs to be a union because the largest node differs on 32 bit systems
2566/// with 4 and 8 byte pointer alignment, respectively.
2567using LargestSDNode = AlignedCharArrayUnion<AtomicSDNode, TargetIndexSDNode,
2568 BlockAddressSDNode,
2569 GlobalAddressSDNode>;
2570
2571/// The SDNode class with the greatest alignment requirement.
2572using MostAlignedSDNode = GlobalAddressSDNode;
2573
2574namespace ISD {
2575
2576 /// Returns true if the specified node is a non-extending and unindexed load.
2577 inline bool isNormalLoad(const SDNode *N) {
2578 const LoadSDNode *Ld = dyn_cast<LoadSDNode>(N);
2579 return Ld && Ld->getExtensionType() == ISD::NON_EXTLOAD &&
2580 Ld->getAddressingMode() == ISD::UNINDEXED;
2581 }
2582
2583 /// Returns true if the specified node is a non-extending load.
2584 inline bool isNON_EXTLoad(const SDNode *N) {
2585 return isa<LoadSDNode>(N) &&
2586 cast<LoadSDNode>(N)->getExtensionType() == ISD::NON_EXTLOAD;
2587 }
2588
2589 /// Returns true if the specified node is a EXTLOAD.
2590 inline bool isEXTLoad(const SDNode *N) {
2591 return isa<LoadSDNode>(N) &&
2592 cast<LoadSDNode>(N)->getExtensionType() == ISD::EXTLOAD;
2593 }
2594
2595 /// Returns true if the specified node is a SEXTLOAD.
2596 inline bool isSEXTLoad(const SDNode *N) {
2597 return isa<LoadSDNode>(N) &&
2598 cast<LoadSDNode>(N)->getExtensionType() == ISD::SEXTLOAD;
2599 }
2600
2601 /// Returns true if the specified node is a ZEXTLOAD.
2602 inline bool isZEXTLoad(const SDNode *N) {
2603 return isa<LoadSDNode>(N) &&
2604 cast<LoadSDNode>(N)->getExtensionType() == ISD::ZEXTLOAD;
2605 }
2606
2607 /// Returns true if the specified node is an unindexed load.
2608 inline bool isUNINDEXEDLoad(const SDNode *N) {
2609 return isa<LoadSDNode>(N) &&
2610 cast<LoadSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
2611 }
2612
2613 /// Returns true if the specified node is a non-truncating
2614 /// and unindexed store.
2615 inline bool isNormalStore(const SDNode *N) {
2616 const StoreSDNode *St = dyn_cast<StoreSDNode>(N);
2617 return St && !St->isTruncatingStore() &&
2618 St->getAddressingMode() == ISD::UNINDEXED;
2619 }
2620
2621 /// Returns true if the specified node is a non-truncating store.
2622 inline bool isNON_TRUNCStore(const SDNode *N) {
2623 return isa<StoreSDNode>(N) && !cast<StoreSDNode>(N)->isTruncatingStore();
2624 }
2625
2626 /// Returns true if the specified node is a truncating store.
2627 inline bool isTRUNCStore(const SDNode *N) {
2628 return isa<StoreSDNode>(N) && cast<StoreSDNode>(N)->isTruncatingStore();
2629 }
2630
2631 /// Returns true if the specified node is an unindexed store.
2632 inline bool isUNINDEXEDStore(const SDNode *N) {
2633 return isa<StoreSDNode>(N) &&
2634 cast<StoreSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
2635 }
2636
2637 /// Attempt to match a unary predicate against a scalar/splat constant or
2638 /// every element of a constant BUILD_VECTOR.
2639 /// If AllowUndef is true, then UNDEF elements will pass nullptr to Match.
2640 bool matchUnaryPredicate(SDValue Op,
2641 std::function<bool(ConstantSDNode *)> Match,
2642 bool AllowUndefs = false);
2643
2644 /// Attempt to match a binary predicate against a pair of scalar/splat
2645 /// constants or every element of a pair of constant BUILD_VECTORs.
2646 /// If AllowUndef is true, then UNDEF elements will pass nullptr to Match.
2647 /// If AllowTypeMismatch is true then RetType + ArgTypes don't need to match.
2648 bool matchBinaryPredicate(
2649 SDValue LHS, SDValue RHS,
2650 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
2651 bool AllowUndefs = false, bool AllowTypeMismatch = false);
2652
2653 /// Returns true if the specified value is the overflow result from one
2654 /// of the overflow intrinsic nodes.
2655 inline bool isOverflowIntrOpRes(SDValue Op) {
2656 unsigned Opc = Op.getOpcode();
2657 return (Op.getResNo() == 1 &&
2658 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2659 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2660 }
2661
2662} // end namespace ISD
2663
2664} // end namespace llvm
2665
2666#endif // LLVM_CODEGEN_SELECTIONDAGNODES_H