Bug Summary

File:llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp
Warning:line 1135, column 42
The result of the right shift is undefined due to shifting by '32', which is greater or equal to the width of type 'uint32_t'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name HexagonISelDAGToDAG.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 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/Target/Hexagon -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/lib/Target/Hexagon -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility hidden -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp

1//===-- HexagonISelDAGToDAG.cpp - A dag to dag inst selector for Hexagon --===//
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 an instruction selector for the Hexagon target.
10//
11//===----------------------------------------------------------------------===//
12
13#include "HexagonISelDAGToDAG.h"
14#include "Hexagon.h"
15#include "HexagonISelLowering.h"
16#include "HexagonMachineFunctionInfo.h"
17#include "HexagonTargetMachine.h"
18#include "llvm/CodeGen/FunctionLoweringInfo.h"
19#include "llvm/CodeGen/MachineInstrBuilder.h"
20#include "llvm/CodeGen/SelectionDAGISel.h"
21#include "llvm/IR/Intrinsics.h"
22#include "llvm/IR/IntrinsicsHexagon.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/Debug.h"
25using namespace llvm;
26
27#define DEBUG_TYPE"hexagon-isel" "hexagon-isel"
28
29static
30cl::opt<bool>
31EnableAddressRebalancing("isel-rebalance-addr", cl::Hidden, cl::init(true),
32 cl::desc("Rebalance address calculation trees to improve "
33 "instruction selection"));
34
35// Rebalance only if this allows e.g. combining a GA with an offset or
36// factoring out a shift.
37static
38cl::opt<bool>
39RebalanceOnlyForOptimizations("rebalance-only-opt", cl::Hidden, cl::init(false),
40 cl::desc("Rebalance address tree only if this allows optimizations"));
41
42static
43cl::opt<bool>
44RebalanceOnlyImbalancedTrees("rebalance-only-imbal", cl::Hidden,
45 cl::init(false), cl::desc("Rebalance address tree only if it is imbalanced"));
46
47static cl::opt<bool> CheckSingleUse("hexagon-isel-su", cl::Hidden,
48 cl::init(true), cl::desc("Enable checking of SDNode's single-use status"));
49
50//===----------------------------------------------------------------------===//
51// Instruction Selector Implementation
52//===----------------------------------------------------------------------===//
53
54#define GET_DAGISEL_BODY HexagonDAGToDAGISel
55#include "HexagonGenDAGISel.inc"
56
57/// createHexagonISelDag - This pass converts a legalized DAG into a
58/// Hexagon-specific DAG, ready for instruction scheduling.
59///
60namespace llvm {
61FunctionPass *createHexagonISelDag(HexagonTargetMachine &TM,
62 CodeGenOpt::Level OptLevel) {
63 return new HexagonDAGToDAGISel(TM, OptLevel);
64}
65}
66
67void HexagonDAGToDAGISel::SelectIndexedLoad(LoadSDNode *LD, const SDLoc &dl) {
68 SDValue Chain = LD->getChain();
69 SDValue Base = LD->getBasePtr();
70 SDValue Offset = LD->getOffset();
71 int32_t Inc = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
72 EVT LoadedVT = LD->getMemoryVT();
73 unsigned Opcode = 0;
74
75 // Check for zero extended loads. Treat any-extend loads as zero extended
76 // loads.
77 ISD::LoadExtType ExtType = LD->getExtensionType();
78 bool IsZeroExt = (ExtType == ISD::ZEXTLOAD || ExtType == ISD::EXTLOAD);
79 bool IsValidInc = HII->isValidAutoIncImm(LoadedVT, Inc);
80
81 assert(LoadedVT.isSimple())((LoadedVT.isSimple()) ? static_cast<void> (0) : __assert_fail
("LoadedVT.isSimple()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 81, __PRETTY_FUNCTION__))
;
82 switch (LoadedVT.getSimpleVT().SimpleTy) {
83 case MVT::i8:
84 if (IsZeroExt)
85 Opcode = IsValidInc ? Hexagon::L2_loadrub_pi : Hexagon::L2_loadrub_io;
86 else
87 Opcode = IsValidInc ? Hexagon::L2_loadrb_pi : Hexagon::L2_loadrb_io;
88 break;
89 case MVT::i16:
90 if (IsZeroExt)
91 Opcode = IsValidInc ? Hexagon::L2_loadruh_pi : Hexagon::L2_loadruh_io;
92 else
93 Opcode = IsValidInc ? Hexagon::L2_loadrh_pi : Hexagon::L2_loadrh_io;
94 break;
95 case MVT::i32:
96 case MVT::f32:
97 case MVT::v2i16:
98 case MVT::v4i8:
99 Opcode = IsValidInc ? Hexagon::L2_loadri_pi : Hexagon::L2_loadri_io;
100 break;
101 case MVT::i64:
102 case MVT::f64:
103 case MVT::v2i32:
104 case MVT::v4i16:
105 case MVT::v8i8:
106 Opcode = IsValidInc ? Hexagon::L2_loadrd_pi : Hexagon::L2_loadrd_io;
107 break;
108 case MVT::v64i8:
109 case MVT::v32i16:
110 case MVT::v16i32:
111 case MVT::v8i64:
112 case MVT::v128i8:
113 case MVT::v64i16:
114 case MVT::v32i32:
115 case MVT::v16i64:
116 if (isAlignedMemNode(LD)) {
117 if (LD->isNonTemporal())
118 Opcode = IsValidInc ? Hexagon::V6_vL32b_nt_pi : Hexagon::V6_vL32b_nt_ai;
119 else
120 Opcode = IsValidInc ? Hexagon::V6_vL32b_pi : Hexagon::V6_vL32b_ai;
121 } else {
122 Opcode = IsValidInc ? Hexagon::V6_vL32Ub_pi : Hexagon::V6_vL32Ub_ai;
123 }
124 break;
125 default:
126 llvm_unreachable("Unexpected memory type in indexed load")::llvm::llvm_unreachable_internal("Unexpected memory type in indexed load"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 126)
;
127 }
128
129 SDValue IncV = CurDAG->getTargetConstant(Inc, dl, MVT::i32);
130 MachineMemOperand *MemOp = LD->getMemOperand();
131
132 auto getExt64 = [this,ExtType] (MachineSDNode *N, const SDLoc &dl)
133 -> MachineSDNode* {
134 if (ExtType == ISD::ZEXTLOAD || ExtType == ISD::EXTLOAD) {
135 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
136 return CurDAG->getMachineNode(Hexagon::A4_combineir, dl, MVT::i64,
137 Zero, SDValue(N, 0));
138 }
139 if (ExtType == ISD::SEXTLOAD)
140 return CurDAG->getMachineNode(Hexagon::A2_sxtw, dl, MVT::i64,
141 SDValue(N, 0));
142 return N;
143 };
144
145 // Loaded value Next address Chain
146 SDValue From[3] = { SDValue(LD,0), SDValue(LD,1), SDValue(LD,2) };
147 SDValue To[3];
148
149 EVT ValueVT = LD->getValueType(0);
150 if (ValueVT == MVT::i64 && ExtType != ISD::NON_EXTLOAD) {
151 // A load extending to i64 will actually produce i32, which will then
152 // need to be extended to i64.
153 assert(LoadedVT.getSizeInBits() <= 32)((LoadedVT.getSizeInBits() <= 32) ? static_cast<void>
(0) : __assert_fail ("LoadedVT.getSizeInBits() <= 32", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 153, __PRETTY_FUNCTION__))
;
154 ValueVT = MVT::i32;
155 }
156
157 if (IsValidInc) {
158 MachineSDNode *L = CurDAG->getMachineNode(Opcode, dl, ValueVT,
159 MVT::i32, MVT::Other, Base,
160 IncV, Chain);
161 CurDAG->setNodeMemRefs(L, {MemOp});
162 To[1] = SDValue(L, 1); // Next address.
163 To[2] = SDValue(L, 2); // Chain.
164 // Handle special case for extension to i64.
165 if (LD->getValueType(0) == MVT::i64)
166 L = getExt64(L, dl);
167 To[0] = SDValue(L, 0); // Loaded (extended) value.
168 } else {
169 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
170 MachineSDNode *L = CurDAG->getMachineNode(Opcode, dl, ValueVT, MVT::Other,
171 Base, Zero, Chain);
172 CurDAG->setNodeMemRefs(L, {MemOp});
173 To[2] = SDValue(L, 1); // Chain.
174 MachineSDNode *A = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
175 Base, IncV);
176 To[1] = SDValue(A, 0); // Next address.
177 // Handle special case for extension to i64.
178 if (LD->getValueType(0) == MVT::i64)
179 L = getExt64(L, dl);
180 To[0] = SDValue(L, 0); // Loaded (extended) value.
181 }
182 ReplaceUses(From, To, 3);
183 CurDAG->RemoveDeadNode(LD);
184}
185
186MachineSDNode *HexagonDAGToDAGISel::LoadInstrForLoadIntrinsic(SDNode *IntN) {
187 if (IntN->getOpcode() != ISD::INTRINSIC_W_CHAIN)
188 return nullptr;
189
190 SDLoc dl(IntN);
191 unsigned IntNo = cast<ConstantSDNode>(IntN->getOperand(1))->getZExtValue();
192
193 static std::map<unsigned,unsigned> LoadPciMap = {
194 { Intrinsic::hexagon_circ_ldb, Hexagon::L2_loadrb_pci },
195 { Intrinsic::hexagon_circ_ldub, Hexagon::L2_loadrub_pci },
196 { Intrinsic::hexagon_circ_ldh, Hexagon::L2_loadrh_pci },
197 { Intrinsic::hexagon_circ_lduh, Hexagon::L2_loadruh_pci },
198 { Intrinsic::hexagon_circ_ldw, Hexagon::L2_loadri_pci },
199 { Intrinsic::hexagon_circ_ldd, Hexagon::L2_loadrd_pci },
200 };
201 auto FLC = LoadPciMap.find(IntNo);
202 if (FLC != LoadPciMap.end()) {
203 EVT ValTy = (IntNo == Intrinsic::hexagon_circ_ldd) ? MVT::i64 : MVT::i32;
204 EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
205 // Operands: { Base, Increment, Modifier, Chain }
206 auto Inc = cast<ConstantSDNode>(IntN->getOperand(5));
207 SDValue I = CurDAG->getTargetConstant(Inc->getSExtValue(), dl, MVT::i32);
208 MachineSDNode *Res = CurDAG->getMachineNode(FLC->second, dl, RTys,
209 { IntN->getOperand(2), I, IntN->getOperand(4),
210 IntN->getOperand(0) });
211 return Res;
212 }
213
214 return nullptr;
215}
216
217SDNode *HexagonDAGToDAGISel::StoreInstrForLoadIntrinsic(MachineSDNode *LoadN,
218 SDNode *IntN) {
219 // The "LoadN" is just a machine load instruction. The intrinsic also
220 // involves storing it. Generate an appropriate store to the location
221 // given in the intrinsic's operand(3).
222 uint64_t F = HII->get(LoadN->getMachineOpcode()).TSFlags;
223 unsigned SizeBits = (F >> HexagonII::MemAccessSizePos) &
224 HexagonII::MemAccesSizeMask;
225 unsigned Size = 1U << (SizeBits-1);
226
227 SDLoc dl(IntN);
228 MachinePointerInfo PI;
229 SDValue TS;
230 SDValue Loc = IntN->getOperand(3);
231
232 if (Size >= 4)
233 TS = CurDAG->getStore(SDValue(LoadN, 2), dl, SDValue(LoadN, 0), Loc, PI,
234 Size);
235 else
236 TS = CurDAG->getTruncStore(SDValue(LoadN, 2), dl, SDValue(LoadN, 0), Loc,
237 PI, MVT::getIntegerVT(Size * 8), Size);
238
239 SDNode *StoreN;
240 {
241 HandleSDNode Handle(TS);
242 SelectStore(TS.getNode());
243 StoreN = Handle.getValue().getNode();
244 }
245
246 // Load's results are { Loaded value, Updated pointer, Chain }
247 ReplaceUses(SDValue(IntN, 0), SDValue(LoadN, 1));
248 ReplaceUses(SDValue(IntN, 1), SDValue(StoreN, 0));
249 return StoreN;
250}
251
252bool HexagonDAGToDAGISel::tryLoadOfLoadIntrinsic(LoadSDNode *N) {
253 // The intrinsics for load circ/brev perform two operations:
254 // 1. Load a value V from the specified location, using the addressing
255 // mode corresponding to the intrinsic.
256 // 2. Store V into a specified location. This location is typically a
257 // local, temporary object.
258 // In many cases, the program using these intrinsics will immediately
259 // load V again from the local object. In those cases, when certain
260 // conditions are met, the last load can be removed.
261 // This function identifies and optimizes this pattern. If the pattern
262 // cannot be optimized, it returns nullptr, which will cause the load
263 // to be selected separately from the intrinsic (which will be handled
264 // in SelectIntrinsicWChain).
265
266 SDValue Ch = N->getOperand(0);
267 SDValue Loc = N->getOperand(1);
268
269 // Assume that the load and the intrinsic are connected directly with a
270 // chain:
271 // t1: i32,ch = int.load ..., ..., ..., Loc, ... // <-- C
272 // t2: i32,ch = load t1:1, Loc, ...
273 SDNode *C = Ch.getNode();
274
275 if (C->getOpcode() != ISD::INTRINSIC_W_CHAIN)
276 return false;
277
278 // The second load can only be eliminated if its extension type matches
279 // that of the load instruction corresponding to the intrinsic. The user
280 // can provide an address of an unsigned variable to store the result of
281 // a sign-extending intrinsic into (or the other way around).
282 ISD::LoadExtType IntExt;
283 switch (cast<ConstantSDNode>(C->getOperand(1))->getZExtValue()) {
284 case Intrinsic::hexagon_circ_ldub:
285 case Intrinsic::hexagon_circ_lduh:
286 IntExt = ISD::ZEXTLOAD;
287 break;
288 case Intrinsic::hexagon_circ_ldw:
289 case Intrinsic::hexagon_circ_ldd:
290 IntExt = ISD::NON_EXTLOAD;
291 break;
292 default:
293 IntExt = ISD::SEXTLOAD;
294 break;
295 }
296 if (N->getExtensionType() != IntExt)
297 return false;
298
299 // Make sure the target location for the loaded value in the load intrinsic
300 // is the location from which LD (or N) is loading.
301 if (C->getNumOperands() < 4 || Loc.getNode() != C->getOperand(3).getNode())
302 return false;
303
304 if (MachineSDNode *L = LoadInstrForLoadIntrinsic(C)) {
305 SDNode *S = StoreInstrForLoadIntrinsic(L, C);
306 SDValue F[] = { SDValue(N,0), SDValue(N,1), SDValue(C,0), SDValue(C,1) };
307 SDValue T[] = { SDValue(L,0), SDValue(S,0), SDValue(L,1), SDValue(S,0) };
308 ReplaceUses(F, T, array_lengthof(T));
309 // This transformation will leave the intrinsic dead. If it remains in
310 // the DAG, the selection code will see it again, but without the load,
311 // and it will generate a store that is normally required for it.
312 CurDAG->RemoveDeadNode(C);
313 return true;
314 }
315 return false;
316}
317
318// Convert the bit-reverse load intrinsic to appropriate target instruction.
319bool HexagonDAGToDAGISel::SelectBrevLdIntrinsic(SDNode *IntN) {
320 if (IntN->getOpcode() != ISD::INTRINSIC_W_CHAIN)
321 return false;
322
323 const SDLoc &dl(IntN);
324 unsigned IntNo = cast<ConstantSDNode>(IntN->getOperand(1))->getZExtValue();
325
326 static const std::map<unsigned, unsigned> LoadBrevMap = {
327 { Intrinsic::hexagon_L2_loadrb_pbr, Hexagon::L2_loadrb_pbr },
328 { Intrinsic::hexagon_L2_loadrub_pbr, Hexagon::L2_loadrub_pbr },
329 { Intrinsic::hexagon_L2_loadrh_pbr, Hexagon::L2_loadrh_pbr },
330 { Intrinsic::hexagon_L2_loadruh_pbr, Hexagon::L2_loadruh_pbr },
331 { Intrinsic::hexagon_L2_loadri_pbr, Hexagon::L2_loadri_pbr },
332 { Intrinsic::hexagon_L2_loadrd_pbr, Hexagon::L2_loadrd_pbr }
333 };
334 auto FLI = LoadBrevMap.find(IntNo);
335 if (FLI != LoadBrevMap.end()) {
336 EVT ValTy =
337 (IntNo == Intrinsic::hexagon_L2_loadrd_pbr) ? MVT::i64 : MVT::i32;
338 EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
339 // Operands of Intrinsic: {chain, enum ID of intrinsic, baseptr,
340 // modifier}.
341 // Operands of target instruction: { Base, Modifier, Chain }.
342 MachineSDNode *Res = CurDAG->getMachineNode(
343 FLI->second, dl, RTys,
344 {IntN->getOperand(2), IntN->getOperand(3), IntN->getOperand(0)});
345
346 MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(IntN)->getMemOperand();
347 CurDAG->setNodeMemRefs(Res, {MemOp});
348
349 ReplaceUses(SDValue(IntN, 0), SDValue(Res, 0));
350 ReplaceUses(SDValue(IntN, 1), SDValue(Res, 1));
351 ReplaceUses(SDValue(IntN, 2), SDValue(Res, 2));
352 CurDAG->RemoveDeadNode(IntN);
353 return true;
354 }
355 return false;
356}
357
358/// Generate a machine instruction node for the new circlar buffer intrinsics.
359/// The new versions use a CSx register instead of the K field.
360bool HexagonDAGToDAGISel::SelectNewCircIntrinsic(SDNode *IntN) {
361 if (IntN->getOpcode() != ISD::INTRINSIC_W_CHAIN)
362 return false;
363
364 SDLoc DL(IntN);
365 unsigned IntNo = cast<ConstantSDNode>(IntN->getOperand(1))->getZExtValue();
366 SmallVector<SDValue, 7> Ops;
367
368 static std::map<unsigned,unsigned> LoadNPcMap = {
369 { Intrinsic::hexagon_L2_loadrub_pci, Hexagon::PS_loadrub_pci },
370 { Intrinsic::hexagon_L2_loadrb_pci, Hexagon::PS_loadrb_pci },
371 { Intrinsic::hexagon_L2_loadruh_pci, Hexagon::PS_loadruh_pci },
372 { Intrinsic::hexagon_L2_loadrh_pci, Hexagon::PS_loadrh_pci },
373 { Intrinsic::hexagon_L2_loadri_pci, Hexagon::PS_loadri_pci },
374 { Intrinsic::hexagon_L2_loadrd_pci, Hexagon::PS_loadrd_pci },
375 { Intrinsic::hexagon_L2_loadrub_pcr, Hexagon::PS_loadrub_pcr },
376 { Intrinsic::hexagon_L2_loadrb_pcr, Hexagon::PS_loadrb_pcr },
377 { Intrinsic::hexagon_L2_loadruh_pcr, Hexagon::PS_loadruh_pcr },
378 { Intrinsic::hexagon_L2_loadrh_pcr, Hexagon::PS_loadrh_pcr },
379 { Intrinsic::hexagon_L2_loadri_pcr, Hexagon::PS_loadri_pcr },
380 { Intrinsic::hexagon_L2_loadrd_pcr, Hexagon::PS_loadrd_pcr }
381 };
382 auto FLI = LoadNPcMap.find (IntNo);
383 if (FLI != LoadNPcMap.end()) {
384 EVT ValTy = MVT::i32;
385 if (IntNo == Intrinsic::hexagon_L2_loadrd_pci ||
386 IntNo == Intrinsic::hexagon_L2_loadrd_pcr)
387 ValTy = MVT::i64;
388 EVT RTys[] = { ValTy, MVT::i32, MVT::Other };
389 // Handle load.*_pci case which has 6 operands.
390 if (IntN->getNumOperands() == 6) {
391 auto Inc = cast<ConstantSDNode>(IntN->getOperand(3));
392 SDValue I = CurDAG->getTargetConstant(Inc->getSExtValue(), DL, MVT::i32);
393 // Operands: { Base, Increment, Modifier, Start, Chain }.
394 Ops = { IntN->getOperand(2), I, IntN->getOperand(4), IntN->getOperand(5),
395 IntN->getOperand(0) };
396 } else
397 // Handle load.*_pcr case which has 5 operands.
398 // Operands: { Base, Modifier, Start, Chain }.
399 Ops = { IntN->getOperand(2), IntN->getOperand(3), IntN->getOperand(4),
400 IntN->getOperand(0) };
401 MachineSDNode *Res = CurDAG->getMachineNode(FLI->second, DL, RTys, Ops);
402 ReplaceUses(SDValue(IntN, 0), SDValue(Res, 0));
403 ReplaceUses(SDValue(IntN, 1), SDValue(Res, 1));
404 ReplaceUses(SDValue(IntN, 2), SDValue(Res, 2));
405 CurDAG->RemoveDeadNode(IntN);
406 return true;
407 }
408
409 static std::map<unsigned,unsigned> StoreNPcMap = {
410 { Intrinsic::hexagon_S2_storerb_pci, Hexagon::PS_storerb_pci },
411 { Intrinsic::hexagon_S2_storerh_pci, Hexagon::PS_storerh_pci },
412 { Intrinsic::hexagon_S2_storerf_pci, Hexagon::PS_storerf_pci },
413 { Intrinsic::hexagon_S2_storeri_pci, Hexagon::PS_storeri_pci },
414 { Intrinsic::hexagon_S2_storerd_pci, Hexagon::PS_storerd_pci },
415 { Intrinsic::hexagon_S2_storerb_pcr, Hexagon::PS_storerb_pcr },
416 { Intrinsic::hexagon_S2_storerh_pcr, Hexagon::PS_storerh_pcr },
417 { Intrinsic::hexagon_S2_storerf_pcr, Hexagon::PS_storerf_pcr },
418 { Intrinsic::hexagon_S2_storeri_pcr, Hexagon::PS_storeri_pcr },
419 { Intrinsic::hexagon_S2_storerd_pcr, Hexagon::PS_storerd_pcr }
420 };
421 auto FSI = StoreNPcMap.find (IntNo);
422 if (FSI != StoreNPcMap.end()) {
423 EVT RTys[] = { MVT::i32, MVT::Other };
424 // Handle store.*_pci case which has 7 operands.
425 if (IntN->getNumOperands() == 7) {
426 auto Inc = cast<ConstantSDNode>(IntN->getOperand(3));
427 SDValue I = CurDAG->getTargetConstant(Inc->getSExtValue(), DL, MVT::i32);
428 // Operands: { Base, Increment, Modifier, Value, Start, Chain }.
429 Ops = { IntN->getOperand(2), I, IntN->getOperand(4), IntN->getOperand(5),
430 IntN->getOperand(6), IntN->getOperand(0) };
431 } else
432 // Handle store.*_pcr case which has 6 operands.
433 // Operands: { Base, Modifier, Value, Start, Chain }.
434 Ops = { IntN->getOperand(2), IntN->getOperand(3), IntN->getOperand(4),
435 IntN->getOperand(5), IntN->getOperand(0) };
436 MachineSDNode *Res = CurDAG->getMachineNode(FSI->second, DL, RTys, Ops);
437 ReplaceUses(SDValue(IntN, 0), SDValue(Res, 0));
438 ReplaceUses(SDValue(IntN, 1), SDValue(Res, 1));
439 CurDAG->RemoveDeadNode(IntN);
440 return true;
441 }
442
443 return false;
444}
445
446void HexagonDAGToDAGISel::SelectLoad(SDNode *N) {
447 SDLoc dl(N);
448 LoadSDNode *LD = cast<LoadSDNode>(N);
449
450 // Handle indexed loads.
451 ISD::MemIndexedMode AM = LD->getAddressingMode();
452 if (AM != ISD::UNINDEXED) {
453 SelectIndexedLoad(LD, dl);
454 return;
455 }
456
457 // Handle patterns using circ/brev load intrinsics.
458 if (tryLoadOfLoadIntrinsic(LD))
459 return;
460
461 SelectCode(LD);
462}
463
464void HexagonDAGToDAGISel::SelectIndexedStore(StoreSDNode *ST, const SDLoc &dl) {
465 SDValue Chain = ST->getChain();
466 SDValue Base = ST->getBasePtr();
467 SDValue Offset = ST->getOffset();
468 SDValue Value = ST->getValue();
469 // Get the constant value.
470 int32_t Inc = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
471 EVT StoredVT = ST->getMemoryVT();
472 EVT ValueVT = Value.getValueType();
473
474 bool IsValidInc = HII->isValidAutoIncImm(StoredVT, Inc);
475 unsigned Opcode = 0;
476
477 assert(StoredVT.isSimple())((StoredVT.isSimple()) ? static_cast<void> (0) : __assert_fail
("StoredVT.isSimple()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 477, __PRETTY_FUNCTION__))
;
478 switch (StoredVT.getSimpleVT().SimpleTy) {
479 case MVT::i8:
480 Opcode = IsValidInc ? Hexagon::S2_storerb_pi : Hexagon::S2_storerb_io;
481 break;
482 case MVT::i16:
483 Opcode = IsValidInc ? Hexagon::S2_storerh_pi : Hexagon::S2_storerh_io;
484 break;
485 case MVT::i32:
486 case MVT::f32:
487 case MVT::v2i16:
488 case MVT::v4i8:
489 Opcode = IsValidInc ? Hexagon::S2_storeri_pi : Hexagon::S2_storeri_io;
490 break;
491 case MVT::i64:
492 case MVT::f64:
493 case MVT::v2i32:
494 case MVT::v4i16:
495 case MVT::v8i8:
496 Opcode = IsValidInc ? Hexagon::S2_storerd_pi : Hexagon::S2_storerd_io;
497 break;
498 case MVT::v64i8:
499 case MVT::v32i16:
500 case MVT::v16i32:
501 case MVT::v8i64:
502 case MVT::v128i8:
503 case MVT::v64i16:
504 case MVT::v32i32:
505 case MVT::v16i64:
506 if (isAlignedMemNode(ST)) {
507 if (ST->isNonTemporal())
508 Opcode = IsValidInc ? Hexagon::V6_vS32b_nt_pi : Hexagon::V6_vS32b_nt_ai;
509 else
510 Opcode = IsValidInc ? Hexagon::V6_vS32b_pi : Hexagon::V6_vS32b_ai;
511 } else {
512 Opcode = IsValidInc ? Hexagon::V6_vS32Ub_pi : Hexagon::V6_vS32Ub_ai;
513 }
514 break;
515 default:
516 llvm_unreachable("Unexpected memory type in indexed store")::llvm::llvm_unreachable_internal("Unexpected memory type in indexed store"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 516)
;
517 }
518
519 if (ST->isTruncatingStore() && ValueVT.getSizeInBits() == 64) {
520 assert(StoredVT.getSizeInBits() < 64 && "Not a truncating store")((StoredVT.getSizeInBits() < 64 && "Not a truncating store"
) ? static_cast<void> (0) : __assert_fail ("StoredVT.getSizeInBits() < 64 && \"Not a truncating store\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 520, __PRETTY_FUNCTION__))
;
521 Value = CurDAG->getTargetExtractSubreg(Hexagon::isub_lo,
522 dl, MVT::i32, Value);
523 }
524
525 SDValue IncV = CurDAG->getTargetConstant(Inc, dl, MVT::i32);
526 MachineMemOperand *MemOp = ST->getMemOperand();
527
528 // Next address Chain
529 SDValue From[2] = { SDValue(ST,0), SDValue(ST,1) };
530 SDValue To[2];
531
532 if (IsValidInc) {
533 // Build post increment store.
534 SDValue Ops[] = { Base, IncV, Value, Chain };
535 MachineSDNode *S = CurDAG->getMachineNode(Opcode, dl, MVT::i32, MVT::Other,
536 Ops);
537 CurDAG->setNodeMemRefs(S, {MemOp});
538 To[0] = SDValue(S, 0);
539 To[1] = SDValue(S, 1);
540 } else {
541 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
542 SDValue Ops[] = { Base, Zero, Value, Chain };
543 MachineSDNode *S = CurDAG->getMachineNode(Opcode, dl, MVT::Other, Ops);
544 CurDAG->setNodeMemRefs(S, {MemOp});
545 To[1] = SDValue(S, 0);
546 MachineSDNode *A = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
547 Base, IncV);
548 To[0] = SDValue(A, 0);
549 }
550
551 ReplaceUses(From, To, 2);
552 CurDAG->RemoveDeadNode(ST);
553}
554
555void HexagonDAGToDAGISel::SelectStore(SDNode *N) {
556 SDLoc dl(N);
557 StoreSDNode *ST = cast<StoreSDNode>(N);
558
559 // Handle indexed stores.
560 ISD::MemIndexedMode AM = ST->getAddressingMode();
561 if (AM != ISD::UNINDEXED) {
562 SelectIndexedStore(ST, dl);
563 return;
564 }
565
566 SelectCode(ST);
567}
568
569void HexagonDAGToDAGISel::SelectSHL(SDNode *N) {
570 SDLoc dl(N);
571 SDValue Shl_0 = N->getOperand(0);
572 SDValue Shl_1 = N->getOperand(1);
573
574 auto Default = [this,N] () -> void { SelectCode(N); };
575
576 if (N->getValueType(0) != MVT::i32 || Shl_1.getOpcode() != ISD::Constant)
577 return Default();
578
579 // RHS is const.
580 int32_t ShlConst = cast<ConstantSDNode>(Shl_1)->getSExtValue();
581
582 if (Shl_0.getOpcode() == ISD::MUL) {
583 SDValue Mul_0 = Shl_0.getOperand(0); // Val
584 SDValue Mul_1 = Shl_0.getOperand(1); // Const
585 // RHS of mul is const.
586 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mul_1)) {
587 int32_t ValConst = C->getSExtValue() << ShlConst;
588 if (isInt<9>(ValConst)) {
589 SDValue Val = CurDAG->getTargetConstant(ValConst, dl, MVT::i32);
590 SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
591 MVT::i32, Mul_0, Val);
592 ReplaceNode(N, Result);
593 return;
594 }
595 }
596 return Default();
597 }
598
599 if (Shl_0.getOpcode() == ISD::SUB) {
600 SDValue Sub_0 = Shl_0.getOperand(0); // Const 0
601 SDValue Sub_1 = Shl_0.getOperand(1); // Val
602 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(Sub_0)) {
603 if (C1->getSExtValue() != 0 || Sub_1.getOpcode() != ISD::SHL)
604 return Default();
605 SDValue Shl2_0 = Sub_1.getOperand(0); // Val
606 SDValue Shl2_1 = Sub_1.getOperand(1); // Const
607 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(Shl2_1)) {
608 int32_t ValConst = 1 << (ShlConst + C2->getSExtValue());
609 if (isInt<9>(-ValConst)) {
610 SDValue Val = CurDAG->getTargetConstant(-ValConst, dl, MVT::i32);
611 SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
612 MVT::i32, Shl2_0, Val);
613 ReplaceNode(N, Result);
614 return;
615 }
616 }
617 }
618 }
619
620 return Default();
621}
622
623//
624// Handling intrinsics for circular load and bitreverse load.
625//
626void HexagonDAGToDAGISel::SelectIntrinsicWChain(SDNode *N) {
627 if (MachineSDNode *L = LoadInstrForLoadIntrinsic(N)) {
628 StoreInstrForLoadIntrinsic(L, N);
629 CurDAG->RemoveDeadNode(N);
630 return;
631 }
632
633 // Handle bit-reverse load intrinsics.
634 if (SelectBrevLdIntrinsic(N))
635 return;
636
637 if (SelectNewCircIntrinsic(N))
638 return;
639
640 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
641 if (IntNo == Intrinsic::hexagon_V6_vgathermw ||
642 IntNo == Intrinsic::hexagon_V6_vgathermw_128B ||
643 IntNo == Intrinsic::hexagon_V6_vgathermh ||
644 IntNo == Intrinsic::hexagon_V6_vgathermh_128B ||
645 IntNo == Intrinsic::hexagon_V6_vgathermhw ||
646 IntNo == Intrinsic::hexagon_V6_vgathermhw_128B) {
647 SelectV65Gather(N);
648 return;
649 }
650 if (IntNo == Intrinsic::hexagon_V6_vgathermwq ||
651 IntNo == Intrinsic::hexagon_V6_vgathermwq_128B ||
652 IntNo == Intrinsic::hexagon_V6_vgathermhq ||
653 IntNo == Intrinsic::hexagon_V6_vgathermhq_128B ||
654 IntNo == Intrinsic::hexagon_V6_vgathermhwq ||
655 IntNo == Intrinsic::hexagon_V6_vgathermhwq_128B) {
656 SelectV65GatherPred(N);
657 return;
658 }
659
660 SelectCode(N);
661}
662
663void HexagonDAGToDAGISel::SelectIntrinsicWOChain(SDNode *N) {
664 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
665 unsigned Bits;
666 switch (IID) {
667 case Intrinsic::hexagon_S2_vsplatrb:
668 Bits = 8;
669 break;
670 case Intrinsic::hexagon_S2_vsplatrh:
671 Bits = 16;
672 break;
673 case Intrinsic::hexagon_V6_vaddcarry:
674 case Intrinsic::hexagon_V6_vaddcarry_128B:
675 case Intrinsic::hexagon_V6_vsubcarry:
676 case Intrinsic::hexagon_V6_vsubcarry_128B:
677 SelectHVXDualOutput(N);
678 return;
679 default:
680 SelectCode(N);
681 return;
682 }
683
684 SDValue V = N->getOperand(1);
685 SDValue U;
686 if (keepsLowBits(V, Bits, U)) {
687 SDValue R = CurDAG->getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
688 N->getOperand(0), U);
689 ReplaceNode(N, R.getNode());
690 SelectCode(R.getNode());
691 return;
692 }
693 SelectCode(N);
694}
695
696//
697// Map floating point constant values.
698//
699void HexagonDAGToDAGISel::SelectConstantFP(SDNode *N) {
700 SDLoc dl(N);
701 auto *CN = cast<ConstantFPSDNode>(N);
702 APInt A = CN->getValueAPF().bitcastToAPInt();
703 if (N->getValueType(0) == MVT::f32) {
704 SDValue V = CurDAG->getTargetConstant(A.getZExtValue(), dl, MVT::i32);
705 ReplaceNode(N, CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::f32, V));
706 return;
707 }
708 if (N->getValueType(0) == MVT::f64) {
709 SDValue V = CurDAG->getTargetConstant(A.getZExtValue(), dl, MVT::i64);
710 ReplaceNode(N, CurDAG->getMachineNode(Hexagon::CONST64, dl, MVT::f64, V));
711 return;
712 }
713
714 SelectCode(N);
715}
716
717//
718// Map boolean values.
719//
720void HexagonDAGToDAGISel::SelectConstant(SDNode *N) {
721 if (N->getValueType(0) == MVT::i1) {
722 assert(!(cast<ConstantSDNode>(N)->getZExtValue() >> 1))((!(cast<ConstantSDNode>(N)->getZExtValue() >>
1)) ? static_cast<void> (0) : __assert_fail ("!(cast<ConstantSDNode>(N)->getZExtValue() >> 1)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 722, __PRETTY_FUNCTION__))
;
723 unsigned Opc = (cast<ConstantSDNode>(N)->getSExtValue() != 0)
724 ? Hexagon::PS_true
725 : Hexagon::PS_false;
726 ReplaceNode(N, CurDAG->getMachineNode(Opc, SDLoc(N), MVT::i1));
727 return;
728 }
729
730 SelectCode(N);
731}
732
733void HexagonDAGToDAGISel::SelectFrameIndex(SDNode *N) {
734 MachineFrameInfo &MFI = MF->getFrameInfo();
735 const HexagonFrameLowering *HFI = HST->getFrameLowering();
736 int FX = cast<FrameIndexSDNode>(N)->getIndex();
737 unsigned StkA = HFI->getStackAlignment();
738 unsigned MaxA = MFI.getMaxAlignment();
739 SDValue FI = CurDAG->getTargetFrameIndex(FX, MVT::i32);
740 SDLoc DL(N);
741 SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
742 SDNode *R = nullptr;
743
744 // Use PS_fi when:
745 // - the object is fixed, or
746 // - there are no objects with higher-than-default alignment, or
747 // - there are no dynamically allocated objects.
748 // Otherwise, use PS_fia.
749 if (FX < 0 || MaxA <= StkA || !MFI.hasVarSizedObjects()) {
750 R = CurDAG->getMachineNode(Hexagon::PS_fi, DL, MVT::i32, FI, Zero);
751 } else {
752 auto &HMFI = *MF->getInfo<HexagonMachineFunctionInfo>();
753 unsigned AR = HMFI.getStackAlignBaseVReg();
754 SDValue CH = CurDAG->getEntryNode();
755 SDValue Ops[] = { CurDAG->getCopyFromReg(CH, DL, AR, MVT::i32), FI, Zero };
756 R = CurDAG->getMachineNode(Hexagon::PS_fia, DL, MVT::i32, Ops);
757 }
758
759 ReplaceNode(N, R);
760}
761
762void HexagonDAGToDAGISel::SelectAddSubCarry(SDNode *N) {
763 unsigned OpcCarry = N->getOpcode() == HexagonISD::ADDC ? Hexagon::A4_addp_c
764 : Hexagon::A4_subp_c;
765 SDNode *C = CurDAG->getMachineNode(OpcCarry, SDLoc(N), N->getVTList(),
766 { N->getOperand(0), N->getOperand(1),
767 N->getOperand(2) });
768 ReplaceNode(N, C);
769}
770
771void HexagonDAGToDAGISel::SelectVAlign(SDNode *N) {
772 MVT ResTy = N->getValueType(0).getSimpleVT();
773 if (HST->isHVXVectorType(ResTy, true))
774 return SelectHvxVAlign(N);
775
776 const SDLoc &dl(N);
777 unsigned VecLen = ResTy.getSizeInBits();
778 if (VecLen == 32) {
779 SDValue Ops[] = {
780 CurDAG->getTargetConstant(Hexagon::DoubleRegsRegClassID, dl, MVT::i32),
781 N->getOperand(0),
782 CurDAG->getTargetConstant(Hexagon::isub_hi, dl, MVT::i32),
783 N->getOperand(1),
784 CurDAG->getTargetConstant(Hexagon::isub_lo, dl, MVT::i32)
785 };
786 SDNode *R = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl,
787 MVT::i64, Ops);
788
789 // Shift right by "(Addr & 0x3) * 8" bytes.
790 SDNode *C;
791 SDValue M0 = CurDAG->getTargetConstant(0x18, dl, MVT::i32);
792 SDValue M1 = CurDAG->getTargetConstant(0x03, dl, MVT::i32);
793 if (HST->useCompound()) {
794 C = CurDAG->getMachineNode(Hexagon::S4_andi_asl_ri, dl, MVT::i32,
795 M0, N->getOperand(2), M1);
796 } else {
797 SDNode *T = CurDAG->getMachineNode(Hexagon::S2_asl_i_r, dl, MVT::i32,
798 N->getOperand(2), M1);
799 C = CurDAG->getMachineNode(Hexagon::A2_andir, dl, MVT::i32,
800 SDValue(T, 0), M0);
801 }
802 SDNode *S = CurDAG->getMachineNode(Hexagon::S2_lsr_r_p, dl, MVT::i64,
803 SDValue(R, 0), SDValue(C, 0));
804 SDValue E = CurDAG->getTargetExtractSubreg(Hexagon::isub_lo, dl, ResTy,
805 SDValue(S, 0));
806 ReplaceNode(N, E.getNode());
807 } else {
808 assert(VecLen == 64)((VecLen == 64) ? static_cast<void> (0) : __assert_fail
("VecLen == 64", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 808, __PRETTY_FUNCTION__))
;
809 SDNode *Pu = CurDAG->getMachineNode(Hexagon::C2_tfrrp, dl, MVT::v8i1,
810 N->getOperand(2));
811 SDNode *VA = CurDAG->getMachineNode(Hexagon::S2_valignrb, dl, ResTy,
812 N->getOperand(0), N->getOperand(1),
813 SDValue(Pu,0));
814 ReplaceNode(N, VA);
815 }
816}
817
818void HexagonDAGToDAGISel::SelectVAlignAddr(SDNode *N) {
819 const SDLoc &dl(N);
820 SDValue A = N->getOperand(1);
821 int Mask = -cast<ConstantSDNode>(A.getNode())->getSExtValue();
822 assert(isPowerOf2_32(-Mask))((isPowerOf2_32(-Mask)) ? static_cast<void> (0) : __assert_fail
("isPowerOf2_32(-Mask)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 822, __PRETTY_FUNCTION__))
;
823
824 SDValue M = CurDAG->getTargetConstant(Mask, dl, MVT::i32);
825 SDNode *AA = CurDAG->getMachineNode(Hexagon::A2_andir, dl, MVT::i32,
826 N->getOperand(0), M);
827 ReplaceNode(N, AA);
828}
829
830// Handle these nodes here to avoid having to write patterns for all
831// combinations of input/output types. In all cases, the resulting
832// instruction is the same.
833void HexagonDAGToDAGISel::SelectTypecast(SDNode *N) {
834 SDValue Op = N->getOperand(0);
835 MVT OpTy = Op.getValueType().getSimpleVT();
836 SDNode *T = CurDAG->MorphNodeTo(N, N->getOpcode(),
837 CurDAG->getVTList(OpTy), {Op});
838 ReplaceNode(T, Op.getNode());
839}
840
841void HexagonDAGToDAGISel::SelectP2D(SDNode *N) {
842 MVT ResTy = N->getValueType(0).getSimpleVT();
843 SDNode *T = CurDAG->getMachineNode(Hexagon::C2_mask, SDLoc(N), ResTy,
844 N->getOperand(0));
845 ReplaceNode(N, T);
846}
847
848void HexagonDAGToDAGISel::SelectD2P(SDNode *N) {
849 const SDLoc &dl(N);
850 MVT ResTy = N->getValueType(0).getSimpleVT();
851 SDValue Zero = CurDAG->getTargetConstant(0, dl, MVT::i32);
852 SDNode *T = CurDAG->getMachineNode(Hexagon::A4_vcmpbgtui, dl, ResTy,
853 N->getOperand(0), Zero);
854 ReplaceNode(N, T);
855}
856
857void HexagonDAGToDAGISel::SelectV2Q(SDNode *N) {
858 const SDLoc &dl(N);
859 MVT ResTy = N->getValueType(0).getSimpleVT();
860 // The argument to V2Q should be a single vector.
861 MVT OpTy = N->getOperand(0).getValueType().getSimpleVT(); (void)OpTy;
862 assert(HST->getVectorLength() * 8 == OpTy.getSizeInBits())((HST->getVectorLength() * 8 == OpTy.getSizeInBits()) ? static_cast
<void> (0) : __assert_fail ("HST->getVectorLength() * 8 == OpTy.getSizeInBits()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 862, __PRETTY_FUNCTION__))
;
863
864 SDValue C = CurDAG->getTargetConstant(-1, dl, MVT::i32);
865 SDNode *R = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::i32, C);
866 SDNode *T = CurDAG->getMachineNode(Hexagon::V6_vandvrt, dl, ResTy,
867 N->getOperand(0), SDValue(R,0));
868 ReplaceNode(N, T);
869}
870
871void HexagonDAGToDAGISel::SelectQ2V(SDNode *N) {
872 const SDLoc &dl(N);
873 MVT ResTy = N->getValueType(0).getSimpleVT();
874 // The result of V2Q should be a single vector.
875 assert(HST->getVectorLength() * 8 == ResTy.getSizeInBits())((HST->getVectorLength() * 8 == ResTy.getSizeInBits()) ? static_cast
<void> (0) : __assert_fail ("HST->getVectorLength() * 8 == ResTy.getSizeInBits()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 875, __PRETTY_FUNCTION__))
;
876
877 SDValue C = CurDAG->getTargetConstant(-1, dl, MVT::i32);
878 SDNode *R = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::i32, C);
879 SDNode *T = CurDAG->getMachineNode(Hexagon::V6_vandqrt, dl, ResTy,
880 N->getOperand(0), SDValue(R,0));
881 ReplaceNode(N, T);
882}
883
884void HexagonDAGToDAGISel::Select(SDNode *N) {
885 if (N->isMachineOpcode())
886 return N->setNodeId(-1); // Already selected.
887
888 switch (N->getOpcode()) {
889 case ISD::Constant: return SelectConstant(N);
890 case ISD::ConstantFP: return SelectConstantFP(N);
891 case ISD::FrameIndex: return SelectFrameIndex(N);
892 case ISD::SHL: return SelectSHL(N);
893 case ISD::LOAD: return SelectLoad(N);
894 case ISD::STORE: return SelectStore(N);
895 case ISD::INTRINSIC_W_CHAIN: return SelectIntrinsicWChain(N);
896 case ISD::INTRINSIC_WO_CHAIN: return SelectIntrinsicWOChain(N);
897
898 case HexagonISD::ADDC:
899 case HexagonISD::SUBC: return SelectAddSubCarry(N);
900 case HexagonISD::VALIGN: return SelectVAlign(N);
901 case HexagonISD::VALIGNADDR: return SelectVAlignAddr(N);
902 case HexagonISD::TYPECAST: return SelectTypecast(N);
903 case HexagonISD::P2D: return SelectP2D(N);
904 case HexagonISD::D2P: return SelectD2P(N);
905 case HexagonISD::Q2V: return SelectQ2V(N);
906 case HexagonISD::V2Q: return SelectV2Q(N);
907 }
908
909 if (HST->useHVXOps()) {
910 switch (N->getOpcode()) {
911 case ISD::VECTOR_SHUFFLE: return SelectHvxShuffle(N);
912 case HexagonISD::VROR: return SelectHvxRor(N);
913 }
914 }
915
916 SelectCode(N);
917}
918
919bool HexagonDAGToDAGISel::
920SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
921 std::vector<SDValue> &OutOps) {
922 SDValue Inp = Op, Res;
923
924 switch (ConstraintID) {
925 default:
926 return true;
927 case InlineAsm::Constraint_o: // Offsetable.
928 case InlineAsm::Constraint_v: // Not offsetable.
929 case InlineAsm::Constraint_m: // Memory.
930 if (SelectAddrFI(Inp, Res))
931 OutOps.push_back(Res);
932 else
933 OutOps.push_back(Inp);
934 break;
935 }
936
937 OutOps.push_back(CurDAG->getTargetConstant(0, SDLoc(Op), MVT::i32));
938 return false;
939}
940
941
942static bool isMemOPCandidate(SDNode *I, SDNode *U) {
943 // I is an operand of U. Check if U is an arithmetic (binary) operation
944 // usable in a memop, where the other operand is a loaded value, and the
945 // result of U is stored in the same location.
946
947 if (!U->hasOneUse())
948 return false;
949 unsigned Opc = U->getOpcode();
950 switch (Opc) {
951 case ISD::ADD:
952 case ISD::SUB:
953 case ISD::AND:
954 case ISD::OR:
955 break;
956 default:
957 return false;
958 }
959
960 SDValue S0 = U->getOperand(0);
961 SDValue S1 = U->getOperand(1);
962 SDValue SY = (S0.getNode() == I) ? S1 : S0;
963
964 SDNode *UUse = *U->use_begin();
965 if (UUse->getNumValues() != 1)
966 return false;
967
968 // Check if one of the inputs to U is a load instruction and the output
969 // is used by a store instruction. If so and they also have the same
970 // base pointer, then don't preoprocess this node sequence as it
971 // can be matched to a memop.
972 SDNode *SYNode = SY.getNode();
973 if (UUse->getOpcode() == ISD::STORE && SYNode->getOpcode() == ISD::LOAD) {
974 SDValue LDBasePtr = cast<MemSDNode>(SYNode)->getBasePtr();
975 SDValue STBasePtr = cast<MemSDNode>(UUse)->getBasePtr();
976 if (LDBasePtr == STBasePtr)
977 return true;
978 }
979 return false;
980}
981
982
983// Transform: (or (select c x 0) z) -> (select c (or x z) z)
984// (or (select c 0 y) z) -> (select c z (or y z))
985void HexagonDAGToDAGISel::ppSimplifyOrSelect0(std::vector<SDNode*> &&Nodes) {
986 SelectionDAG &DAG = *CurDAG;
987
988 for (auto I : Nodes) {
989 if (I->getOpcode() != ISD::OR)
990 continue;
991
992 auto IsZero = [] (const SDValue &V) -> bool {
993 if (ConstantSDNode *SC = dyn_cast<ConstantSDNode>(V.getNode()))
994 return SC->isNullValue();
995 return false;
996 };
997 auto IsSelect0 = [IsZero] (const SDValue &Op) -> bool {
998 if (Op.getOpcode() != ISD::SELECT)
999 return false;
1000 return IsZero(Op.getOperand(1)) || IsZero(Op.getOperand(2));
1001 };
1002
1003 SDValue N0 = I->getOperand(0), N1 = I->getOperand(1);
1004 EVT VT = I->getValueType(0);
1005 bool SelN0 = IsSelect0(N0);
1006 SDValue SOp = SelN0 ? N0 : N1;
1007 SDValue VOp = SelN0 ? N1 : N0;
1008
1009 if (SOp.getOpcode() == ISD::SELECT && SOp.getNode()->hasOneUse()) {
1010 SDValue SC = SOp.getOperand(0);
1011 SDValue SX = SOp.getOperand(1);
1012 SDValue SY = SOp.getOperand(2);
1013 SDLoc DLS = SOp;
1014 if (IsZero(SY)) {
1015 SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SX, VOp);
1016 SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, NewOr, VOp);
1017 DAG.ReplaceAllUsesWith(I, NewSel.getNode());
1018 } else if (IsZero(SX)) {
1019 SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SY, VOp);
1020 SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, VOp, NewOr);
1021 DAG.ReplaceAllUsesWith(I, NewSel.getNode());
1022 }
1023 }
1024 }
1025}
1026
1027// Transform: (store ch val (add x (add (shl y c) e)))
1028// to: (store ch val (add x (shl (add y d) c))),
1029// where e = (shl d c) for some integer d.
1030// The purpose of this is to enable generation of loads/stores with
1031// shifted addressing mode, i.e. mem(x+y<<#c). For that, the shift
1032// value c must be 0, 1 or 2.
1033void HexagonDAGToDAGISel::ppAddrReorderAddShl(std::vector<SDNode*> &&Nodes) {
1034 SelectionDAG &DAG = *CurDAG;
1035
1036 for (auto I : Nodes) {
1037 if (I->getOpcode() != ISD::STORE)
1038 continue;
1039
1040 // I matched: (store ch val Off)
1041 SDValue Off = I->getOperand(2);
1042 // Off needs to match: (add x (add (shl y c) (shl d c))))
1043 if (Off.getOpcode() != ISD::ADD)
1044 continue;
1045 // Off matched: (add x T0)
1046 SDValue T0 = Off.getOperand(1);
1047 // T0 needs to match: (add T1 T2):
1048 if (T0.getOpcode() != ISD::ADD)
1049 continue;
1050 // T0 matched: (add T1 T2)
1051 SDValue T1 = T0.getOperand(0);
1052 SDValue T2 = T0.getOperand(1);
1053 // T1 needs to match: (shl y c)
1054 if (T1.getOpcode() != ISD::SHL)
1055 continue;
1056 SDValue C = T1.getOperand(1);
1057 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(C.getNode());
1058 if (CN == nullptr)
1059 continue;
1060 unsigned CV = CN->getZExtValue();
1061 if (CV > 2)
1062 continue;
1063 // T2 needs to match e, where e = (shl d c) for some d.
1064 ConstantSDNode *EN = dyn_cast<ConstantSDNode>(T2.getNode());
1065 if (EN == nullptr)
1066 continue;
1067 unsigned EV = EN->getZExtValue();
1068 if (EV % (1 << CV) != 0)
1069 continue;
1070 unsigned DV = EV / (1 << CV);
1071
1072 // Replace T0 with: (shl (add y d) c)
1073 SDLoc DL = SDLoc(I);
1074 EVT VT = T0.getValueType();
1075 SDValue D = DAG.getConstant(DV, DL, VT);
1076 // NewAdd = (add y d)
1077 SDValue NewAdd = DAG.getNode(ISD::ADD, DL, VT, T1.getOperand(0), D);
1078 // NewShl = (shl NewAdd c)
1079 SDValue NewShl = DAG.getNode(ISD::SHL, DL, VT, NewAdd, C);
1080 ReplaceNode(T0.getNode(), NewShl.getNode());
1081 }
1082}
1083
1084// Transform: (load ch (add x (and (srl y c) Mask)))
1085// to: (load ch (add x (shl (srl y d) d-c)))
1086// where
1087// Mask = 00..0 111..1 0.0
1088// | | +-- d-c 0s, and d-c is 0, 1 or 2.
1089// | +-------- 1s
1090// +-------------- at most c 0s
1091// Motivating example:
1092// DAG combiner optimizes (add x (shl (srl y 5) 2))
1093// to (add x (and (srl y 3) 1FFFFFFC))
1094// which results in a constant-extended and(##...,lsr). This transformation
1095// undoes this simplification for cases where the shl can be folded into
1096// an addressing mode.
1097void HexagonDAGToDAGISel::ppAddrRewriteAndSrl(std::vector<SDNode*> &&Nodes) {
1098 SelectionDAG &DAG = *CurDAG;
1099
1100 for (SDNode *N : Nodes) {
1101 unsigned Opc = N->getOpcode();
1102 if (Opc != ISD::LOAD && Opc != ISD::STORE)
2
Assuming 'Opc' is equal to LOAD
1103 continue;
1104 SDValue Addr = Opc
2.1
'Opc' is equal to LOAD
2.1
'Opc' is equal to LOAD
== ISD::LOAD ? N->getOperand(1) : N->getOperand(2);
3
'?' condition is true
1105 // Addr must match: (add x T0)
1106 if (Addr.getOpcode() != ISD::ADD)
4
Assuming the condition is false
5
Taking false branch
1107 continue;
1108 SDValue T0 = Addr.getOperand(1);
1109 // T0 must match: (and T1 Mask)
1110 if (T0.getOpcode() != ISD::AND)
6
Assuming the condition is false
7
Taking false branch
1111 continue;
1112
1113 // We have an AND.
1114 //
1115 // Check the first operand. It must be: (srl y c).
1116 SDValue S = T0.getOperand(0);
1117 if (S.getOpcode() != ISD::SRL)
8
Assuming the condition is false
9
Taking false branch
1118 continue;
1119 ConstantSDNode *SN = dyn_cast<ConstantSDNode>(S.getOperand(1).getNode());
10
Assuming the object is a 'ConstantSDNode'
1120 if (SN == nullptr)
11
Taking false branch
1121 continue;
1122 if (SN->getAPIntValue().getBitWidth() != 32)
12
Assuming the condition is false
13
Taking false branch
1123 continue;
1124 uint32_t CV = SN->getZExtValue();
1125
1126 // Check the second operand: the supposed mask.
1127 ConstantSDNode *MN = dyn_cast<ConstantSDNode>(T0.getOperand(1).getNode());
14
Assuming the object is a 'ConstantSDNode'
1128 if (MN == nullptr)
15
Taking false branch
1129 continue;
1130 if (MN->getAPIntValue().getBitWidth() != 32)
16
Assuming the condition is false
17
Taking false branch
1131 continue;
1132 uint32_t Mask = MN->getZExtValue();
1133 // Examine the mask.
1134 uint32_t TZ = countTrailingZeros(Mask);
18
Calling 'countTrailingZeros<unsigned int>'
25
Returning from 'countTrailingZeros<unsigned int>'
26
'TZ' initialized to 32
1135 uint32_t M1 = countTrailingOnes(Mask >> TZ);
27
The result of the right shift is undefined due to shifting by '32', which is greater or equal to the width of type 'uint32_t'
1136 uint32_t LZ = countLeadingZeros(Mask);
1137 // Trailing zeros + middle ones + leading zeros must equal the width.
1138 if (TZ + M1 + LZ != 32)
1139 continue;
1140 // The number of trailing zeros will be encoded in the addressing mode.
1141 if (TZ > 2)
1142 continue;
1143 // The number of leading zeros must be at most c.
1144 if (LZ > CV)
1145 continue;
1146
1147 // All looks good.
1148 SDValue Y = S.getOperand(0);
1149 EVT VT = Addr.getValueType();
1150 SDLoc dl(S);
1151 // TZ = D-C, so D = TZ+C.
1152 SDValue D = DAG.getConstant(TZ+CV, dl, VT);
1153 SDValue DC = DAG.getConstant(TZ, dl, VT);
1154 SDValue NewSrl = DAG.getNode(ISD::SRL, dl, VT, Y, D);
1155 SDValue NewShl = DAG.getNode(ISD::SHL, dl, VT, NewSrl, DC);
1156 ReplaceNode(T0.getNode(), NewShl.getNode());
1157 }
1158}
1159
1160// Transform: (op ... (zext i1 c) ...) -> (select c (op ... 0 ...)
1161// (op ... 1 ...))
1162void HexagonDAGToDAGISel::ppHoistZextI1(std::vector<SDNode*> &&Nodes) {
1163 SelectionDAG &DAG = *CurDAG;
1164
1165 for (SDNode *N : Nodes) {
1166 unsigned Opc = N->getOpcode();
1167 if (Opc != ISD::ZERO_EXTEND)
1168 continue;
1169 SDValue OpI1 = N->getOperand(0);
1170 EVT OpVT = OpI1.getValueType();
1171 if (!OpVT.isSimple() || OpVT.getSimpleVT() != MVT::i1)
1172 continue;
1173 for (auto I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1174 SDNode *U = *I;
1175 if (U->getNumValues() != 1)
1176 continue;
1177 EVT UVT = U->getValueType(0);
1178 if (!UVT.isSimple() || !UVT.isInteger() || UVT.getSimpleVT() == MVT::i1)
1179 continue;
1180 if (isMemOPCandidate(N, U))
1181 continue;
1182
1183 // Potentially simplifiable operation.
1184 unsigned I1N = I.getOperandNo();
1185 SmallVector<SDValue,2> Ops(U->getNumOperands());
1186 for (unsigned i = 0, n = U->getNumOperands(); i != n; ++i)
1187 Ops[i] = U->getOperand(i);
1188 EVT BVT = Ops[I1N].getValueType();
1189
1190 const SDLoc &dl(U);
1191 SDValue C0 = DAG.getConstant(0, dl, BVT);
1192 SDValue C1 = DAG.getConstant(1, dl, BVT);
1193 SDValue If0, If1;
1194
1195 if (isa<MachineSDNode>(U)) {
1196 unsigned UseOpc = U->getMachineOpcode();
1197 Ops[I1N] = C0;
1198 If0 = SDValue(DAG.getMachineNode(UseOpc, dl, UVT, Ops), 0);
1199 Ops[I1N] = C1;
1200 If1 = SDValue(DAG.getMachineNode(UseOpc, dl, UVT, Ops), 0);
1201 } else {
1202 unsigned UseOpc = U->getOpcode();
1203 Ops[I1N] = C0;
1204 If0 = DAG.getNode(UseOpc, dl, UVT, Ops);
1205 Ops[I1N] = C1;
1206 If1 = DAG.getNode(UseOpc, dl, UVT, Ops);
1207 }
1208 // We're generating a SELECT way after legalization, so keep the types
1209 // simple.
1210 unsigned UW = UVT.getSizeInBits();
1211 EVT SVT = (UW == 32 || UW == 64) ? MVT::getIntegerVT(UW) : UVT;
1212 SDValue Sel = DAG.getNode(ISD::SELECT, dl, SVT, OpI1,
1213 DAG.getBitcast(SVT, If1),
1214 DAG.getBitcast(SVT, If0));
1215 SDValue Ret = DAG.getBitcast(UVT, Sel);
1216 DAG.ReplaceAllUsesWith(U, Ret.getNode());
1217 }
1218 }
1219}
1220
1221void HexagonDAGToDAGISel::PreprocessISelDAG() {
1222 // Repack all nodes before calling each preprocessing function,
1223 // because each of them can modify the set of nodes.
1224 auto getNodes = [this] () -> std::vector<SDNode*> {
1225 std::vector<SDNode*> T;
1226 T.reserve(CurDAG->allnodes_size());
1227 for (SDNode &N : CurDAG->allnodes())
1228 T.push_back(&N);
1229 return T;
1230 };
1231
1232 // Transform: (or (select c x 0) z) -> (select c (or x z) z)
1233 // (or (select c 0 y) z) -> (select c z (or y z))
1234 ppSimplifyOrSelect0(getNodes());
1235
1236 // Transform: (store ch val (add x (add (shl y c) e)))
1237 // to: (store ch val (add x (shl (add y d) c))),
1238 // where e = (shl d c) for some integer d.
1239 // The purpose of this is to enable generation of loads/stores with
1240 // shifted addressing mode, i.e. mem(x+y<<#c). For that, the shift
1241 // value c must be 0, 1 or 2.
1242 ppAddrReorderAddShl(getNodes());
1243
1244 // Transform: (load ch (add x (and (srl y c) Mask)))
1245 // to: (load ch (add x (shl (srl y d) d-c)))
1246 // where
1247 // Mask = 00..0 111..1 0.0
1248 // | | +-- d-c 0s, and d-c is 0, 1 or 2.
1249 // | +-------- 1s
1250 // +-------------- at most c 0s
1251 // Motivating example:
1252 // DAG combiner optimizes (add x (shl (srl y 5) 2))
1253 // to (add x (and (srl y 3) 1FFFFFFC))
1254 // which results in a constant-extended and(##...,lsr). This transformation
1255 // undoes this simplification for cases where the shl can be folded into
1256 // an addressing mode.
1257 ppAddrRewriteAndSrl(getNodes());
1
Calling 'HexagonDAGToDAGISel::ppAddrRewriteAndSrl'
1258
1259 // Transform: (op ... (zext i1 c) ...) -> (select c (op ... 0 ...)
1260 // (op ... 1 ...))
1261 ppHoistZextI1(getNodes());
1262
1263 DEBUG_WITH_TYPE("isel", {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { { dbgs() << "Preprocessed (Hexagon) selection DAG:"
; CurDAG->dump(); }; } } while (false)
1264 dbgs() << "Preprocessed (Hexagon) selection DAG:";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { { dbgs() << "Preprocessed (Hexagon) selection DAG:"
; CurDAG->dump(); }; } } while (false)
1265 CurDAG->dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { { dbgs() << "Preprocessed (Hexagon) selection DAG:"
; CurDAG->dump(); }; } } while (false)
1266 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { { dbgs() << "Preprocessed (Hexagon) selection DAG:"
; CurDAG->dump(); }; } } while (false)
;
1267
1268 if (EnableAddressRebalancing) {
1269 rebalanceAddressTrees();
1270
1271 DEBUG_WITH_TYPE("isel", {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { { dbgs() << "Address tree balanced selection DAG:"
; CurDAG->dump(); }; } } while (false)
1272 dbgs() << "Address tree balanced selection DAG:";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { { dbgs() << "Address tree balanced selection DAG:"
; CurDAG->dump(); }; } } while (false)
1273 CurDAG->dump();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { { dbgs() << "Address tree balanced selection DAG:"
; CurDAG->dump(); }; } } while (false)
1274 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { { dbgs() << "Address tree balanced selection DAG:"
; CurDAG->dump(); }; } } while (false)
;
1275 }
1276}
1277
1278void HexagonDAGToDAGISel::emitFunctionEntryCode() {
1279 auto &HST = MF->getSubtarget<HexagonSubtarget>();
1280 auto &HFI = *HST.getFrameLowering();
1281 if (!HFI.needsAligna(*MF))
1282 return;
1283
1284 MachineFrameInfo &MFI = MF->getFrameInfo();
1285 MachineBasicBlock *EntryBB = &MF->front();
1286 unsigned AR = FuncInfo->CreateReg(MVT::i32);
1287 unsigned EntryMaxA = MFI.getMaxAlignment();
1288 BuildMI(EntryBB, DebugLoc(), HII->get(Hexagon::PS_aligna), AR)
1289 .addImm(EntryMaxA);
1290 MF->getInfo<HexagonMachineFunctionInfo>()->setStackAlignBaseVReg(AR);
1291}
1292
1293void HexagonDAGToDAGISel::updateAligna() {
1294 auto &HFI = *MF->getSubtarget<HexagonSubtarget>().getFrameLowering();
1295 if (!HFI.needsAligna(*MF))
1296 return;
1297 auto *AlignaI = const_cast<MachineInstr*>(HFI.getAlignaInstr(*MF));
1298 assert(AlignaI != nullptr)((AlignaI != nullptr) ? static_cast<void> (0) : __assert_fail
("AlignaI != nullptr", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 1298, __PRETTY_FUNCTION__))
;
1299 unsigned MaxA = MF->getFrameInfo().getMaxAlignment();
1300 if (AlignaI->getOperand(1).getImm() < MaxA)
1301 AlignaI->getOperand(1).setImm(MaxA);
1302}
1303
1304// Match a frame index that can be used in an addressing mode.
1305bool HexagonDAGToDAGISel::SelectAddrFI(SDValue &N, SDValue &R) {
1306 if (N.getOpcode() != ISD::FrameIndex)
1307 return false;
1308 auto &HFI = *HST->getFrameLowering();
1309 MachineFrameInfo &MFI = MF->getFrameInfo();
1310 int FX = cast<FrameIndexSDNode>(N)->getIndex();
1311 if (!MFI.isFixedObjectIndex(FX) && HFI.needsAligna(*MF))
1312 return false;
1313 R = CurDAG->getTargetFrameIndex(FX, MVT::i32);
1314 return true;
1315}
1316
1317inline bool HexagonDAGToDAGISel::SelectAddrGA(SDValue &N, SDValue &R) {
1318 return SelectGlobalAddress(N, R, false, 0);
1319}
1320
1321inline bool HexagonDAGToDAGISel::SelectAddrGP(SDValue &N, SDValue &R) {
1322 return SelectGlobalAddress(N, R, true, 0);
1323}
1324
1325inline bool HexagonDAGToDAGISel::SelectAnyImm(SDValue &N, SDValue &R) {
1326 return SelectAnyImmediate(N, R, 0);
1327}
1328
1329inline bool HexagonDAGToDAGISel::SelectAnyImm0(SDValue &N, SDValue &R) {
1330 return SelectAnyImmediate(N, R, 0);
1331}
1332inline bool HexagonDAGToDAGISel::SelectAnyImm1(SDValue &N, SDValue &R) {
1333 return SelectAnyImmediate(N, R, 1);
1334}
1335inline bool HexagonDAGToDAGISel::SelectAnyImm2(SDValue &N, SDValue &R) {
1336 return SelectAnyImmediate(N, R, 2);
1337}
1338inline bool HexagonDAGToDAGISel::SelectAnyImm3(SDValue &N, SDValue &R) {
1339 return SelectAnyImmediate(N, R, 3);
1340}
1341
1342inline bool HexagonDAGToDAGISel::SelectAnyInt(SDValue &N, SDValue &R) {
1343 EVT T = N.getValueType();
1344 if (!T.isInteger() || T.getSizeInBits() != 32 || !isa<ConstantSDNode>(N))
1345 return false;
1346 R = N;
1347 return true;
1348}
1349
1350bool HexagonDAGToDAGISel::SelectAnyImmediate(SDValue &N, SDValue &R,
1351 uint32_t LogAlign) {
1352 auto IsAligned = [LogAlign] (uint64_t V) -> bool {
1353 return alignTo(V, (uint64_t)1 << LogAlign) == V;
1354 };
1355
1356 switch (N.getOpcode()) {
1357 case ISD::Constant: {
1358 if (N.getValueType() != MVT::i32)
1359 return false;
1360 int32_t V = cast<const ConstantSDNode>(N)->getZExtValue();
1361 if (!IsAligned(V))
1362 return false;
1363 R = CurDAG->getTargetConstant(V, SDLoc(N), N.getValueType());
1364 return true;
1365 }
1366 case HexagonISD::JT:
1367 case HexagonISD::CP:
1368 // These are assumed to always be aligned at least 8-byte boundary.
1369 if (LogAlign > 3)
1370 return false;
1371 R = N.getOperand(0);
1372 return true;
1373 case ISD::ExternalSymbol:
1374 // Symbols may be aligned at any boundary.
1375 if (LogAlign > 0)
1376 return false;
1377 R = N;
1378 return true;
1379 case ISD::BlockAddress:
1380 // Block address is always aligned at least 4-byte boundary.
1381 if (LogAlign > 2 || !IsAligned(cast<BlockAddressSDNode>(N)->getOffset()))
1382 return false;
1383 R = N;
1384 return true;
1385 }
1386
1387 if (SelectGlobalAddress(N, R, false, LogAlign) ||
1388 SelectGlobalAddress(N, R, true, LogAlign))
1389 return true;
1390
1391 return false;
1392}
1393
1394bool HexagonDAGToDAGISel::SelectGlobalAddress(SDValue &N, SDValue &R,
1395 bool UseGP, uint32_t LogAlign) {
1396 auto IsAligned = [LogAlign] (uint64_t V) -> bool {
1397 return alignTo(V, (uint64_t)1 << LogAlign) == V;
1398 };
1399
1400 switch (N.getOpcode()) {
1401 case ISD::ADD: {
1402 SDValue N0 = N.getOperand(0);
1403 SDValue N1 = N.getOperand(1);
1404 unsigned GAOpc = N0.getOpcode();
1405 if (UseGP && GAOpc != HexagonISD::CONST32_GP)
1406 return false;
1407 if (!UseGP && GAOpc != HexagonISD::CONST32)
1408 return false;
1409 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N1)) {
1410 SDValue Addr = N0.getOperand(0);
1411 // For the purpose of alignment, sextvalue and zextvalue are the same.
1412 if (!IsAligned(Const->getZExtValue()))
1413 return false;
1414 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Addr)) {
1415 if (GA->getOpcode() == ISD::TargetGlobalAddress) {
1416 uint64_t NewOff = GA->getOffset() + (uint64_t)Const->getSExtValue();
1417 R = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(Const),
1418 N.getValueType(), NewOff);
1419 return true;
1420 }
1421 }
1422 }
1423 break;
1424 }
1425 case HexagonISD::CP:
1426 case HexagonISD::JT:
1427 case HexagonISD::CONST32:
1428 // The operand(0) of CONST32 is TargetGlobalAddress, which is what we
1429 // want in the instruction.
1430 if (!UseGP)
1431 R = N.getOperand(0);
1432 return !UseGP;
1433 case HexagonISD::CONST32_GP:
1434 if (UseGP)
1435 R = N.getOperand(0);
1436 return UseGP;
1437 default:
1438 return false;
1439 }
1440
1441 return false;
1442}
1443
1444bool HexagonDAGToDAGISel::DetectUseSxtw(SDValue &N, SDValue &R) {
1445 // This (complex pattern) function is meant to detect a sign-extension
1446 // i32->i64 on a per-operand basis. This would allow writing single
1447 // patterns that would cover a number of combinations of different ways
1448 // a sign-extensions could be written. For example:
1449 // (mul (DetectUseSxtw x) (DetectUseSxtw y)) -> (M2_dpmpyss_s0 x y)
1450 // could match either one of these:
1451 // (mul (sext x) (sext_inreg y))
1452 // (mul (sext-load *p) (sext_inreg y))
1453 // (mul (sext_inreg x) (sext y))
1454 // etc.
1455 //
1456 // The returned value will have type i64 and its low word will
1457 // contain the value being extended. The high bits are not specified.
1458 // The returned type is i64 because the original type of N was i64,
1459 // but the users of this function should only use the low-word of the
1460 // result, e.g.
1461 // (mul sxtw:x, sxtw:y) -> (M2_dpmpyss_s0 (LoReg sxtw:x), (LoReg sxtw:y))
1462
1463 if (N.getValueType() != MVT::i64)
1464 return false;
1465 unsigned Opc = N.getOpcode();
1466 switch (Opc) {
1467 case ISD::SIGN_EXTEND:
1468 case ISD::SIGN_EXTEND_INREG: {
1469 // sext_inreg has the source type as a separate operand.
1470 EVT T = Opc == ISD::SIGN_EXTEND
1471 ? N.getOperand(0).getValueType()
1472 : cast<VTSDNode>(N.getOperand(1))->getVT();
1473 unsigned SW = T.getSizeInBits();
1474 if (SW == 32)
1475 R = N.getOperand(0);
1476 else if (SW < 32)
1477 R = N;
1478 else
1479 return false;
1480 break;
1481 }
1482 case ISD::LOAD: {
1483 LoadSDNode *L = cast<LoadSDNode>(N);
1484 if (L->getExtensionType() != ISD::SEXTLOAD)
1485 return false;
1486 // All extending loads extend to i32, so even if the value in
1487 // memory is shorter than 32 bits, it will be i32 after the load.
1488 if (L->getMemoryVT().getSizeInBits() > 32)
1489 return false;
1490 R = N;
1491 break;
1492 }
1493 case ISD::SRA: {
1494 auto *S = dyn_cast<ConstantSDNode>(N.getOperand(1));
1495 if (!S || S->getZExtValue() != 32)
1496 return false;
1497 R = N;
1498 break;
1499 }
1500 default:
1501 return false;
1502 }
1503 EVT RT = R.getValueType();
1504 if (RT == MVT::i64)
1505 return true;
1506 assert(RT == MVT::i32)((RT == MVT::i32) ? static_cast<void> (0) : __assert_fail
("RT == MVT::i32", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 1506, __PRETTY_FUNCTION__))
;
1507 // This is only to produce a value of type i64. Do not rely on the
1508 // high bits produced by this.
1509 const SDLoc &dl(N);
1510 SDValue Ops[] = {
1511 CurDAG->getTargetConstant(Hexagon::DoubleRegsRegClassID, dl, MVT::i32),
1512 R, CurDAG->getTargetConstant(Hexagon::isub_hi, dl, MVT::i32),
1513 R, CurDAG->getTargetConstant(Hexagon::isub_lo, dl, MVT::i32)
1514 };
1515 SDNode *T = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl,
1516 MVT::i64, Ops);
1517 R = SDValue(T, 0);
1518 return true;
1519}
1520
1521bool HexagonDAGToDAGISel::keepsLowBits(const SDValue &Val, unsigned NumBits,
1522 SDValue &Src) {
1523 unsigned Opc = Val.getOpcode();
1524 switch (Opc) {
1525 case ISD::SIGN_EXTEND:
1526 case ISD::ZERO_EXTEND:
1527 case ISD::ANY_EXTEND: {
1528 const SDValue &Op0 = Val.getOperand(0);
1529 EVT T = Op0.getValueType();
1530 if (T.isInteger() && T.getSizeInBits() == NumBits) {
1531 Src = Op0;
1532 return true;
1533 }
1534 break;
1535 }
1536 case ISD::SIGN_EXTEND_INREG:
1537 case ISD::AssertSext:
1538 case ISD::AssertZext:
1539 if (Val.getOperand(0).getValueType().isInteger()) {
1540 VTSDNode *T = cast<VTSDNode>(Val.getOperand(1));
1541 if (T->getVT().getSizeInBits() == NumBits) {
1542 Src = Val.getOperand(0);
1543 return true;
1544 }
1545 }
1546 break;
1547 case ISD::AND: {
1548 // Check if this is an AND with NumBits of lower bits set to 1.
1549 uint64_t Mask = (1 << NumBits) - 1;
1550 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
1551 if (C->getZExtValue() == Mask) {
1552 Src = Val.getOperand(1);
1553 return true;
1554 }
1555 }
1556 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
1557 if (C->getZExtValue() == Mask) {
1558 Src = Val.getOperand(0);
1559 return true;
1560 }
1561 }
1562 break;
1563 }
1564 case ISD::OR:
1565 case ISD::XOR: {
1566 // OR/XOR with the lower NumBits bits set to 0.
1567 uint64_t Mask = (1 << NumBits) - 1;
1568 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
1569 if ((C->getZExtValue() & Mask) == 0) {
1570 Src = Val.getOperand(1);
1571 return true;
1572 }
1573 }
1574 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
1575 if ((C->getZExtValue() & Mask) == 0) {
1576 Src = Val.getOperand(0);
1577 return true;
1578 }
1579 }
1580 break;
1581 }
1582 default:
1583 break;
1584 }
1585 return false;
1586}
1587
1588bool HexagonDAGToDAGISel::isAlignedMemNode(const MemSDNode *N) const {
1589 return N->getAlignment() >= N->getMemoryVT().getStoreSize();
1590}
1591
1592bool HexagonDAGToDAGISel::isSmallStackStore(const StoreSDNode *N) const {
1593 unsigned StackSize = MF->getFrameInfo().estimateStackSize(*MF);
1594 switch (N->getMemoryVT().getStoreSize()) {
1595 case 1:
1596 return StackSize <= 56; // 1*2^6 - 8
1597 case 2:
1598 return StackSize <= 120; // 2*2^6 - 8
1599 case 4:
1600 return StackSize <= 248; // 4*2^6 - 8
1601 default:
1602 return false;
1603 }
1604}
1605
1606// Return true when the given node fits in a positive half word.
1607bool HexagonDAGToDAGISel::isPositiveHalfWord(const SDNode *N) const {
1608 if (const ConstantSDNode *CN = dyn_cast<const ConstantSDNode>(N)) {
1609 int64_t V = CN->getSExtValue();
1610 return V > 0 && isInt<16>(V);
1611 }
1612 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG) {
1613 const VTSDNode *VN = dyn_cast<const VTSDNode>(N->getOperand(1));
1614 return VN->getVT().getSizeInBits() <= 16;
1615 }
1616 return false;
1617}
1618
1619bool HexagonDAGToDAGISel::hasOneUse(const SDNode *N) const {
1620 return !CheckSingleUse || N->hasOneUse();
1621}
1622
1623////////////////////////////////////////////////////////////////////////////////
1624// Rebalancing of address calculation trees
1625
1626static bool isOpcodeHandled(const SDNode *N) {
1627 switch (N->getOpcode()) {
1628 case ISD::ADD:
1629 case ISD::MUL:
1630 return true;
1631 case ISD::SHL:
1632 // We only handle constant shifts because these can be easily flattened
1633 // into multiplications by 2^Op1.
1634 return isa<ConstantSDNode>(N->getOperand(1).getNode());
1635 default:
1636 return false;
1637 }
1638}
1639
1640/// Return the weight of an SDNode
1641int HexagonDAGToDAGISel::getWeight(SDNode *N) {
1642 if (!isOpcodeHandled(N))
1643 return 1;
1644 assert(RootWeights.count(N) && "Cannot get weight of unseen root!")((RootWeights.count(N) && "Cannot get weight of unseen root!"
) ? static_cast<void> (0) : __assert_fail ("RootWeights.count(N) && \"Cannot get weight of unseen root!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 1644, __PRETTY_FUNCTION__))
;
1645 assert(RootWeights[N] != -1 && "Cannot get weight of unvisited root!")((RootWeights[N] != -1 && "Cannot get weight of unvisited root!"
) ? static_cast<void> (0) : __assert_fail ("RootWeights[N] != -1 && \"Cannot get weight of unvisited root!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 1645, __PRETTY_FUNCTION__))
;
1646 assert(RootWeights[N] != -2 && "Cannot get weight of RAWU'd root!")((RootWeights[N] != -2 && "Cannot get weight of RAWU'd root!"
) ? static_cast<void> (0) : __assert_fail ("RootWeights[N] != -2 && \"Cannot get weight of RAWU'd root!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 1646, __PRETTY_FUNCTION__))
;
1647 return RootWeights[N];
1648}
1649
1650int HexagonDAGToDAGISel::getHeight(SDNode *N) {
1651 if (!isOpcodeHandled(N))
1652 return 0;
1653 assert(RootWeights.count(N) && RootWeights[N] >= 0 &&((RootWeights.count(N) && RootWeights[N] >= 0 &&
"Cannot query height of unvisited/RAUW'd node!") ? static_cast
<void> (0) : __assert_fail ("RootWeights.count(N) && RootWeights[N] >= 0 && \"Cannot query height of unvisited/RAUW'd node!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 1654, __PRETTY_FUNCTION__))
1654 "Cannot query height of unvisited/RAUW'd node!")((RootWeights.count(N) && RootWeights[N] >= 0 &&
"Cannot query height of unvisited/RAUW'd node!") ? static_cast
<void> (0) : __assert_fail ("RootWeights.count(N) && RootWeights[N] >= 0 && \"Cannot query height of unvisited/RAUW'd node!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 1654, __PRETTY_FUNCTION__))
;
1655 return RootHeights[N];
1656}
1657
1658namespace {
1659struct WeightedLeaf {
1660 SDValue Value;
1661 int Weight;
1662 int InsertionOrder;
1663
1664 WeightedLeaf() : Value(SDValue()) { }
1665
1666 WeightedLeaf(SDValue Value, int Weight, int InsertionOrder) :
1667 Value(Value), Weight(Weight), InsertionOrder(InsertionOrder) {
1668 assert(Weight >= 0 && "Weight must be >= 0")((Weight >= 0 && "Weight must be >= 0") ? static_cast
<void> (0) : __assert_fail ("Weight >= 0 && \"Weight must be >= 0\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 1668, __PRETTY_FUNCTION__))
;
1669 }
1670
1671 static bool Compare(const WeightedLeaf &A, const WeightedLeaf &B) {
1672 assert(A.Value.getNode() && B.Value.getNode())((A.Value.getNode() && B.Value.getNode()) ? static_cast
<void> (0) : __assert_fail ("A.Value.getNode() && B.Value.getNode()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 1672, __PRETTY_FUNCTION__))
;
1673 return A.Weight == B.Weight ?
1674 (A.InsertionOrder > B.InsertionOrder) :
1675 (A.Weight > B.Weight);
1676 }
1677};
1678
1679/// A specialized priority queue for WeigthedLeaves. It automatically folds
1680/// constants and allows removal of non-top elements while maintaining the
1681/// priority order.
1682class LeafPrioQueue {
1683 SmallVector<WeightedLeaf, 8> Q;
1684 bool HaveConst;
1685 WeightedLeaf ConstElt;
1686 unsigned Opcode;
1687
1688public:
1689 bool empty() {
1690 return (!HaveConst && Q.empty());
1691 }
1692
1693 size_t size() {
1694 return Q.size() + HaveConst;
1695 }
1696
1697 bool hasConst() {
1698 return HaveConst;
1699 }
1700
1701 const WeightedLeaf &top() {
1702 if (HaveConst)
1703 return ConstElt;
1704 return Q.front();
1705 }
1706
1707 WeightedLeaf pop() {
1708 if (HaveConst) {
1709 HaveConst = false;
1710 return ConstElt;
1711 }
1712 std::pop_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1713 return Q.pop_back_val();
1714 }
1715
1716 void push(WeightedLeaf L, bool SeparateConst=true) {
1717 if (!HaveConst && SeparateConst && isa<ConstantSDNode>(L.Value)) {
1718 if (Opcode == ISD::MUL &&
1719 cast<ConstantSDNode>(L.Value)->getSExtValue() == 1)
1720 return;
1721 if (Opcode == ISD::ADD &&
1722 cast<ConstantSDNode>(L.Value)->getSExtValue() == 0)
1723 return;
1724
1725 HaveConst = true;
1726 ConstElt = L;
1727 } else {
1728 Q.push_back(L);
1729 std::push_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1730 }
1731 }
1732
1733 /// Push L to the bottom of the queue regardless of its weight. If L is
1734 /// constant, it will not be folded with other constants in the queue.
1735 void pushToBottom(WeightedLeaf L) {
1736 L.Weight = 1000;
1737 push(L, false);
1738 }
1739
1740 /// Search for a SHL(x, [<=MaxAmount]) subtree in the queue, return the one of
1741 /// lowest weight and remove it from the queue.
1742 WeightedLeaf findSHL(uint64_t MaxAmount);
1743
1744 WeightedLeaf findMULbyConst();
1745
1746 LeafPrioQueue(unsigned Opcode) :
1747 HaveConst(false), Opcode(Opcode) { }
1748};
1749} // end anonymous namespace
1750
1751WeightedLeaf LeafPrioQueue::findSHL(uint64_t MaxAmount) {
1752 int ResultPos;
1753 WeightedLeaf Result;
1754
1755 for (int Pos = 0, End = Q.size(); Pos != End; ++Pos) {
1756 const WeightedLeaf &L = Q[Pos];
1757 const SDValue &Val = L.Value;
1758 if (Val.getOpcode() != ISD::SHL ||
1759 !isa<ConstantSDNode>(Val.getOperand(1)) ||
1760 Val.getConstantOperandVal(1) > MaxAmount)
1761 continue;
1762 if (!Result.Value.getNode() || Result.Weight > L.Weight ||
1763 (Result.Weight == L.Weight && Result.InsertionOrder > L.InsertionOrder))
1764 {
1765 Result = L;
1766 ResultPos = Pos;
1767 }
1768 }
1769
1770 if (Result.Value.getNode()) {
1771 Q.erase(&Q[ResultPos]);
1772 std::make_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1773 }
1774
1775 return Result;
1776}
1777
1778WeightedLeaf LeafPrioQueue::findMULbyConst() {
1779 int ResultPos;
1780 WeightedLeaf Result;
1781
1782 for (int Pos = 0, End = Q.size(); Pos != End; ++Pos) {
1783 const WeightedLeaf &L = Q[Pos];
1784 const SDValue &Val = L.Value;
1785 if (Val.getOpcode() != ISD::MUL ||
1786 !isa<ConstantSDNode>(Val.getOperand(1)) ||
1787 Val.getConstantOperandVal(1) > 127)
1788 continue;
1789 if (!Result.Value.getNode() || Result.Weight > L.Weight ||
1790 (Result.Weight == L.Weight && Result.InsertionOrder > L.InsertionOrder))
1791 {
1792 Result = L;
1793 ResultPos = Pos;
1794 }
1795 }
1796
1797 if (Result.Value.getNode()) {
1798 Q.erase(&Q[ResultPos]);
1799 std::make_heap(Q.begin(), Q.end(), WeightedLeaf::Compare);
1800 }
1801
1802 return Result;
1803}
1804
1805SDValue HexagonDAGToDAGISel::getMultiplierForSHL(SDNode *N) {
1806 uint64_t MulFactor = 1ull << N->getConstantOperandVal(1);
1807 return CurDAG->getConstant(MulFactor, SDLoc(N),
1808 N->getOperand(1).getValueType());
1809}
1810
1811/// @returns the value x for which 2^x is a factor of Val
1812static unsigned getPowerOf2Factor(SDValue Val) {
1813 if (Val.getOpcode() == ISD::MUL) {
1814 unsigned MaxFactor = 0;
1815 for (int i = 0; i < 2; ++i) {
1816 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(i));
1817 if (!C)
1818 continue;
1819 const APInt &CInt = C->getAPIntValue();
1820 if (CInt.getBoolValue())
1821 MaxFactor = CInt.countTrailingZeros();
1822 }
1823 return MaxFactor;
1824 }
1825 if (Val.getOpcode() == ISD::SHL) {
1826 if (!isa<ConstantSDNode>(Val.getOperand(1).getNode()))
1827 return 0;
1828 return (unsigned) Val.getConstantOperandVal(1);
1829 }
1830
1831 return 0;
1832}
1833
1834/// @returns true if V>>Amount will eliminate V's operation on its child
1835static bool willShiftRightEliminate(SDValue V, unsigned Amount) {
1836 if (V.getOpcode() == ISD::MUL) {
1837 SDValue Ops[] = { V.getOperand(0), V.getOperand(1) };
1838 for (int i = 0; i < 2; ++i)
1839 if (isa<ConstantSDNode>(Ops[i].getNode()) &&
1840 V.getConstantOperandVal(i) % (1ULL << Amount) == 0) {
1841 uint64_t NewConst = V.getConstantOperandVal(i) >> Amount;
1842 return (NewConst == 1);
1843 }
1844 } else if (V.getOpcode() == ISD::SHL) {
1845 return (Amount == V.getConstantOperandVal(1));
1846 }
1847
1848 return false;
1849}
1850
1851SDValue HexagonDAGToDAGISel::factorOutPowerOf2(SDValue V, unsigned Power) {
1852 SDValue Ops[] = { V.getOperand(0), V.getOperand(1) };
1853 if (V.getOpcode() == ISD::MUL) {
1854 for (int i=0; i < 2; ++i) {
1855 if (isa<ConstantSDNode>(Ops[i].getNode()) &&
1856 V.getConstantOperandVal(i) % ((uint64_t)1 << Power) == 0) {
1857 uint64_t NewConst = V.getConstantOperandVal(i) >> Power;
1858 if (NewConst == 1)
1859 return Ops[!i];
1860 Ops[i] = CurDAG->getConstant(NewConst,
1861 SDLoc(V), V.getValueType());
1862 break;
1863 }
1864 }
1865 } else if (V.getOpcode() == ISD::SHL) {
1866 uint64_t ShiftAmount = V.getConstantOperandVal(1);
1867 if (ShiftAmount == Power)
1868 return Ops[0];
1869 Ops[1] = CurDAG->getConstant(ShiftAmount - Power,
1870 SDLoc(V), V.getValueType());
1871 }
1872
1873 return CurDAG->getNode(V.getOpcode(), SDLoc(V), V.getValueType(), Ops);
1874}
1875
1876static bool isTargetConstant(const SDValue &V) {
1877 return V.getOpcode() == HexagonISD::CONST32 ||
1878 V.getOpcode() == HexagonISD::CONST32_GP;
1879}
1880
1881unsigned HexagonDAGToDAGISel::getUsesInFunction(const Value *V) {
1882 if (GAUsesInFunction.count(V))
1883 return GAUsesInFunction[V];
1884
1885 unsigned Result = 0;
1886 const Function &CurF = CurDAG->getMachineFunction().getFunction();
1887 for (const User *U : V->users()) {
1888 if (isa<Instruction>(U) &&
1889 cast<Instruction>(U)->getParent()->getParent() == &CurF)
1890 ++Result;
1891 }
1892
1893 GAUsesInFunction[V] = Result;
1894
1895 return Result;
1896}
1897
1898/// Note - After calling this, N may be dead. It may have been replaced by a
1899/// new node, so always use the returned value in place of N.
1900///
1901/// @returns The SDValue taking the place of N (which could be N if it is
1902/// unchanged)
1903SDValue HexagonDAGToDAGISel::balanceSubTree(SDNode *N, bool TopLevel) {
1904 assert(RootWeights.count(N) && "Cannot balance non-root node.")((RootWeights.count(N) && "Cannot balance non-root node."
) ? static_cast<void> (0) : __assert_fail ("RootWeights.count(N) && \"Cannot balance non-root node.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 1904, __PRETTY_FUNCTION__))
;
1905 assert(RootWeights[N] != -2 && "This node was RAUW'd!")((RootWeights[N] != -2 && "This node was RAUW'd!") ? static_cast
<void> (0) : __assert_fail ("RootWeights[N] != -2 && \"This node was RAUW'd!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 1905, __PRETTY_FUNCTION__))
;
1906 assert(!TopLevel || N->getOpcode() == ISD::ADD)((!TopLevel || N->getOpcode() == ISD::ADD) ? static_cast<
void> (0) : __assert_fail ("!TopLevel || N->getOpcode() == ISD::ADD"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 1906, __PRETTY_FUNCTION__))
;
1907
1908 // Return early if this node was already visited
1909 if (RootWeights[N] != -1)
1910 return SDValue(N, 0);
1911
1912 assert(isOpcodeHandled(N))((isOpcodeHandled(N)) ? static_cast<void> (0) : __assert_fail
("isOpcodeHandled(N)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 1912, __PRETTY_FUNCTION__))
;
1913
1914 SDValue Op0 = N->getOperand(0);
1915 SDValue Op1 = N->getOperand(1);
1916
1917 // Return early if the operands will remain unchanged or are all roots
1918 if ((!isOpcodeHandled(Op0.getNode()) || RootWeights.count(Op0.getNode())) &&
1919 (!isOpcodeHandled(Op1.getNode()) || RootWeights.count(Op1.getNode()))) {
1920 SDNode *Op0N = Op0.getNode();
1921 int Weight;
1922 if (isOpcodeHandled(Op0N) && RootWeights[Op0N] == -1) {
1923 Weight = getWeight(balanceSubTree(Op0N).getNode());
1924 // Weight = calculateWeight(Op0N);
1925 } else
1926 Weight = getWeight(Op0N);
1927
1928 SDNode *Op1N = N->getOperand(1).getNode(); // Op1 may have been RAUWd
1929 if (isOpcodeHandled(Op1N) && RootWeights[Op1N] == -1) {
1930 Weight += getWeight(balanceSubTree(Op1N).getNode());
1931 // Weight += calculateWeight(Op1N);
1932 } else
1933 Weight += getWeight(Op1N);
1934
1935 RootWeights[N] = Weight;
1936 RootHeights[N] = std::max(getHeight(N->getOperand(0).getNode()),
1937 getHeight(N->getOperand(1).getNode())) + 1;
1938
1939 LLVM_DEBUG(dbgs() << "--> No need to balance root (Weight=" << Weightdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "--> No need to balance root (Weight="
<< Weight << " Height=" << RootHeights[N] <<
"): "; } } while (false)
1940 << " Height=" << RootHeights[N] << "): ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "--> No need to balance root (Weight="
<< Weight << " Height=" << RootHeights[N] <<
"): "; } } while (false)
;
1941 LLVM_DEBUG(N->dump(CurDAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { N->dump(CurDAG); } } while (false)
;
1942
1943 return SDValue(N, 0);
1944 }
1945
1946 LLVM_DEBUG(dbgs() << "** Balancing root node: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "** Balancing root node: "
; } } while (false)
;
1947 LLVM_DEBUG(N->dump(CurDAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { N->dump(CurDAG); } } while (false)
;
1948
1949 unsigned NOpcode = N->getOpcode();
1950
1951 LeafPrioQueue Leaves(NOpcode);
1952 SmallVector<SDValue, 4> Worklist;
1953 Worklist.push_back(SDValue(N, 0));
1954
1955 // SHL nodes will be converted to MUL nodes
1956 if (NOpcode == ISD::SHL)
1957 NOpcode = ISD::MUL;
1958
1959 bool CanFactorize = false;
1960 WeightedLeaf Mul1, Mul2;
1961 unsigned MaxPowerOf2 = 0;
1962 WeightedLeaf GA;
1963
1964 // Do not try to factor out a shift if there is already a shift at the tip of
1965 // the tree.
1966 bool HaveTopLevelShift = false;
1967 if (TopLevel &&
1968 ((isOpcodeHandled(Op0.getNode()) && Op0.getOpcode() == ISD::SHL &&
1969 Op0.getConstantOperandVal(1) < 4) ||
1970 (isOpcodeHandled(Op1.getNode()) && Op1.getOpcode() == ISD::SHL &&
1971 Op1.getConstantOperandVal(1) < 4)))
1972 HaveTopLevelShift = true;
1973
1974 // Flatten the subtree into an ordered list of leaves; at the same time
1975 // determine whether the tree is already balanced.
1976 int InsertionOrder = 0;
1977 SmallDenseMap<SDValue, int> NodeHeights;
1978 bool Imbalanced = false;
1979 int CurrentWeight = 0;
1980 while (!Worklist.empty()) {
1981 SDValue Child = Worklist.pop_back_val();
1982
1983 if (Child.getNode() != N && RootWeights.count(Child.getNode())) {
1984 // CASE 1: Child is a root note
1985
1986 int Weight = RootWeights[Child.getNode()];
1987 if (Weight == -1) {
1988 Child = balanceSubTree(Child.getNode());
1989 // calculateWeight(Child.getNode());
1990 Weight = getWeight(Child.getNode());
1991 } else if (Weight == -2) {
1992 // Whoops, this node was RAUWd by one of the balanceSubTree calls we
1993 // made. Our worklist isn't up to date anymore.
1994 // Restart the whole process.
1995 LLVM_DEBUG(dbgs() << "--> Subtree was RAUWd. Restarting...\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "--> Subtree was RAUWd. Restarting...\n"
; } } while (false)
;
1996 return balanceSubTree(N, TopLevel);
1997 }
1998
1999 NodeHeights[Child] = 1;
2000 CurrentWeight += Weight;
2001
2002 unsigned PowerOf2;
2003 if (TopLevel && !CanFactorize && !HaveTopLevelShift &&
2004 (Child.getOpcode() == ISD::MUL || Child.getOpcode() == ISD::SHL) &&
2005 Child.hasOneUse() && (PowerOf2 = getPowerOf2Factor(Child))) {
2006 // Try to identify two factorizable MUL/SHL children greedily. Leave
2007 // them out of the priority queue for now so we can deal with them
2008 // after.
2009 if (!Mul1.Value.getNode()) {
2010 Mul1 = WeightedLeaf(Child, Weight, InsertionOrder++);
2011 MaxPowerOf2 = PowerOf2;
2012 } else {
2013 Mul2 = WeightedLeaf(Child, Weight, InsertionOrder++);
2014 MaxPowerOf2 = std::min(MaxPowerOf2, PowerOf2);
2015
2016 // Our addressing modes can only shift by a maximum of 3
2017 if (MaxPowerOf2 > 3)
2018 MaxPowerOf2 = 3;
2019
2020 CanFactorize = true;
2021 }
2022 } else
2023 Leaves.push(WeightedLeaf(Child, Weight, InsertionOrder++));
2024 } else if (!isOpcodeHandled(Child.getNode())) {
2025 // CASE 2: Child is an unhandled kind of node (e.g. constant)
2026 int Weight = getWeight(Child.getNode());
2027
2028 NodeHeights[Child] = getHeight(Child.getNode());
2029 CurrentWeight += Weight;
2030
2031 if (isTargetConstant(Child) && !GA.Value.getNode())
2032 GA = WeightedLeaf(Child, Weight, InsertionOrder++);
2033 else
2034 Leaves.push(WeightedLeaf(Child, Weight, InsertionOrder++));
2035 } else {
2036 // CASE 3: Child is a subtree of same opcode
2037 // Visit children first, then flatten.
2038 unsigned ChildOpcode = Child.getOpcode();
2039 assert(ChildOpcode == NOpcode ||((ChildOpcode == NOpcode || (NOpcode == ISD::MUL && ChildOpcode
== ISD::SHL)) ? static_cast<void> (0) : __assert_fail (
"ChildOpcode == NOpcode || (NOpcode == ISD::MUL && ChildOpcode == ISD::SHL)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 2040, __PRETTY_FUNCTION__))
2040 (NOpcode == ISD::MUL && ChildOpcode == ISD::SHL))((ChildOpcode == NOpcode || (NOpcode == ISD::MUL && ChildOpcode
== ISD::SHL)) ? static_cast<void> (0) : __assert_fail (
"ChildOpcode == NOpcode || (NOpcode == ISD::MUL && ChildOpcode == ISD::SHL)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 2040, __PRETTY_FUNCTION__))
;
2041
2042 // Convert SHL to MUL
2043 SDValue Op1;
2044 if (ChildOpcode == ISD::SHL)
2045 Op1 = getMultiplierForSHL(Child.getNode());
2046 else
2047 Op1 = Child->getOperand(1);
2048
2049 if (!NodeHeights.count(Op1) || !NodeHeights.count(Child->getOperand(0))) {
2050 assert(!NodeHeights.count(Child) && "Parent visited before children?")((!NodeHeights.count(Child) && "Parent visited before children?"
) ? static_cast<void> (0) : __assert_fail ("!NodeHeights.count(Child) && \"Parent visited before children?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 2050, __PRETTY_FUNCTION__))
;
2051 // Visit children first, then re-visit this node
2052 Worklist.push_back(Child);
2053 Worklist.push_back(Op1);
2054 Worklist.push_back(Child->getOperand(0));
2055 } else {
2056 // Back at this node after visiting the children
2057 if (std::abs(NodeHeights[Op1] - NodeHeights[Child->getOperand(0)]) > 1)
2058 Imbalanced = true;
2059
2060 NodeHeights[Child] = std::max(NodeHeights[Op1],
2061 NodeHeights[Child->getOperand(0)]) + 1;
2062 }
2063 }
2064 }
2065
2066 LLVM_DEBUG(dbgs() << "--> Current height=" << NodeHeights[SDValue(N, 0)]do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "--> Current height=" <<
NodeHeights[SDValue(N, 0)] << " weight=" << CurrentWeight
<< " imbalanced=" << Imbalanced << "\n"; }
} while (false)
2067 << " weight=" << CurrentWeightdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "--> Current height=" <<
NodeHeights[SDValue(N, 0)] << " weight=" << CurrentWeight
<< " imbalanced=" << Imbalanced << "\n"; }
} while (false)
2068 << " imbalanced=" << Imbalanced << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "--> Current height=" <<
NodeHeights[SDValue(N, 0)] << " weight=" << CurrentWeight
<< " imbalanced=" << Imbalanced << "\n"; }
} while (false)
;
2069
2070 // Transform MUL(x, C * 2^Y) + SHL(z, Y) -> SHL(ADD(MUL(x, C), z), Y)
2071 // This factors out a shift in order to match memw(a<<Y+b).
2072 if (CanFactorize && (willShiftRightEliminate(Mul1.Value, MaxPowerOf2) ||
2073 willShiftRightEliminate(Mul2.Value, MaxPowerOf2))) {
2074 LLVM_DEBUG(dbgs() << "--> Found common factor for two MUL children!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "--> Found common factor for two MUL children!\n"
; } } while (false)
;
2075 int Weight = Mul1.Weight + Mul2.Weight;
2076 int Height = std::max(NodeHeights[Mul1.Value], NodeHeights[Mul2.Value]) + 1;
2077 SDValue Mul1Factored = factorOutPowerOf2(Mul1.Value, MaxPowerOf2);
2078 SDValue Mul2Factored = factorOutPowerOf2(Mul2.Value, MaxPowerOf2);
2079 SDValue Sum = CurDAG->getNode(ISD::ADD, SDLoc(N), Mul1.Value.getValueType(),
2080 Mul1Factored, Mul2Factored);
2081 SDValue Const = CurDAG->getConstant(MaxPowerOf2, SDLoc(N),
2082 Mul1.Value.getValueType());
2083 SDValue New = CurDAG->getNode(ISD::SHL, SDLoc(N), Mul1.Value.getValueType(),
2084 Sum, Const);
2085 NodeHeights[New] = Height;
2086 Leaves.push(WeightedLeaf(New, Weight, Mul1.InsertionOrder));
2087 } else if (Mul1.Value.getNode()) {
2088 // We failed to factorize two MULs, so now the Muls are left outside the
2089 // queue... add them back.
2090 Leaves.push(Mul1);
2091 if (Mul2.Value.getNode())
2092 Leaves.push(Mul2);
2093 CanFactorize = false;
2094 }
2095
2096 // Combine GA + Constant -> GA+Offset, but only if GA is not used elsewhere
2097 // and the root node itself is not used more than twice. This reduces the
2098 // amount of additional constant extenders introduced by this optimization.
2099 bool CombinedGA = false;
2100 if (NOpcode == ISD::ADD && GA.Value.getNode() && Leaves.hasConst() &&
2101 GA.Value.hasOneUse() && N->use_size() < 3) {
2102 GlobalAddressSDNode *GANode =
2103 cast<GlobalAddressSDNode>(GA.Value.getOperand(0));
2104 ConstantSDNode *Offset = cast<ConstantSDNode>(Leaves.top().Value);
2105
2106 if (getUsesInFunction(GANode->getGlobal()) == 1 && Offset->hasOneUse() &&
2107 getTargetLowering()->isOffsetFoldingLegal(GANode)) {
2108 LLVM_DEBUG(dbgs() << "--> Combining GA and offset ("do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "--> Combining GA and offset ("
<< Offset->getSExtValue() << "): "; } } while
(false)
2109 << Offset->getSExtValue() << "): ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "--> Combining GA and offset ("
<< Offset->getSExtValue() << "): "; } } while
(false)
;
2110 LLVM_DEBUG(GANode->dump(CurDAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { GANode->dump(CurDAG); } } while (false
)
;
2111
2112 SDValue NewTGA =
2113 CurDAG->getTargetGlobalAddress(GANode->getGlobal(), SDLoc(GA.Value),
2114 GANode->getValueType(0),
2115 GANode->getOffset() + (uint64_t)Offset->getSExtValue());
2116 GA.Value = CurDAG->getNode(GA.Value.getOpcode(), SDLoc(GA.Value),
2117 GA.Value.getValueType(), NewTGA);
2118 GA.Weight += Leaves.top().Weight;
2119
2120 NodeHeights[GA.Value] = getHeight(GA.Value.getNode());
2121 CombinedGA = true;
2122
2123 Leaves.pop(); // Remove the offset constant from the queue
2124 }
2125 }
2126
2127 if ((RebalanceOnlyForOptimizations && !CanFactorize && !CombinedGA) ||
2128 (RebalanceOnlyImbalancedTrees && !Imbalanced)) {
2129 RootWeights[N] = CurrentWeight;
2130 RootHeights[N] = NodeHeights[SDValue(N, 0)];
2131
2132 return SDValue(N, 0);
2133 }
2134
2135 // Combine GA + SHL(x, C<=31) so we will match Rx=add(#u8,asl(Rx,#U5))
2136 if (NOpcode == ISD::ADD && GA.Value.getNode()) {
2137 WeightedLeaf SHL = Leaves.findSHL(31);
2138 if (SHL.Value.getNode()) {
2139 int Height = std::max(NodeHeights[GA.Value], NodeHeights[SHL.Value]) + 1;
2140 GA.Value = CurDAG->getNode(ISD::ADD, SDLoc(GA.Value),
2141 GA.Value.getValueType(),
2142 GA.Value, SHL.Value);
2143 GA.Weight = SHL.Weight; // Specifically ignore the GA weight here
2144 NodeHeights[GA.Value] = Height;
2145 }
2146 }
2147
2148 if (GA.Value.getNode())
2149 Leaves.push(GA);
2150
2151 // If this is the top level and we haven't factored out a shift, we should try
2152 // to move a constant to the bottom to match addressing modes like memw(rX+C)
2153 if (TopLevel && !CanFactorize && Leaves.hasConst()) {
2154 LLVM_DEBUG(dbgs() << "--> Pushing constant to tip of tree.")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "--> Pushing constant to tip of tree."
; } } while (false)
;
2155 Leaves.pushToBottom(Leaves.pop());
2156 }
2157
2158 const DataLayout &DL = CurDAG->getDataLayout();
2159 const TargetLowering &TLI = *getTargetLowering();
2160
2161 // Rebuild the tree using Huffman's algorithm
2162 while (Leaves.size() > 1) {
2163 WeightedLeaf L0 = Leaves.pop();
2164
2165 // See whether we can grab a MUL to form an add(Rx,mpyi(Ry,#u6)),
2166 // otherwise just get the next leaf
2167 WeightedLeaf L1 = Leaves.findMULbyConst();
2168 if (!L1.Value.getNode())
2169 L1 = Leaves.pop();
2170
2171 assert(L0.Weight <= L1.Weight && "Priority queue is broken!")((L0.Weight <= L1.Weight && "Priority queue is broken!"
) ? static_cast<void> (0) : __assert_fail ("L0.Weight <= L1.Weight && \"Priority queue is broken!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 2171, __PRETTY_FUNCTION__))
;
2172
2173 SDValue V0 = L0.Value;
2174 int V0Weight = L0.Weight;
2175 SDValue V1 = L1.Value;
2176 int V1Weight = L1.Weight;
2177
2178 // Make sure that none of these nodes have been RAUW'd
2179 if ((RootWeights.count(V0.getNode()) && RootWeights[V0.getNode()] == -2) ||
2180 (RootWeights.count(V1.getNode()) && RootWeights[V1.getNode()] == -2)) {
2181 LLVM_DEBUG(dbgs() << "--> Subtree was RAUWd. Restarting...\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "--> Subtree was RAUWd. Restarting...\n"
; } } while (false)
;
2182 return balanceSubTree(N, TopLevel);
2183 }
2184
2185 ConstantSDNode *V0C = dyn_cast<ConstantSDNode>(V0);
2186 ConstantSDNode *V1C = dyn_cast<ConstantSDNode>(V1);
2187 EVT VT = N->getValueType(0);
2188 SDValue NewNode;
2189
2190 if (V0C && !V1C) {
2191 std::swap(V0, V1);
2192 std::swap(V0C, V1C);
2193 }
2194
2195 // Calculate height of this node
2196 assert(NodeHeights.count(V0) && NodeHeights.count(V1) &&((NodeHeights.count(V0) && NodeHeights.count(V1) &&
"Children must have been visited before re-combining them!")
? static_cast<void> (0) : __assert_fail ("NodeHeights.count(V0) && NodeHeights.count(V1) && \"Children must have been visited before re-combining them!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 2197, __PRETTY_FUNCTION__))
2197 "Children must have been visited before re-combining them!")((NodeHeights.count(V0) && NodeHeights.count(V1) &&
"Children must have been visited before re-combining them!")
? static_cast<void> (0) : __assert_fail ("NodeHeights.count(V0) && NodeHeights.count(V1) && \"Children must have been visited before re-combining them!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 2197, __PRETTY_FUNCTION__))
;
2198 int Height = std::max(NodeHeights[V0], NodeHeights[V1]) + 1;
2199
2200 // Rebuild this node (and restore SHL from MUL if needed)
2201 if (V1C && NOpcode == ISD::MUL && V1C->getAPIntValue().isPowerOf2())
2202 NewNode = CurDAG->getNode(
2203 ISD::SHL, SDLoc(V0), VT, V0,
2204 CurDAG->getConstant(
2205 V1C->getAPIntValue().logBase2(), SDLoc(N),
2206 TLI.getScalarShiftAmountTy(DL, V0.getValueType())));
2207 else
2208 NewNode = CurDAG->getNode(NOpcode, SDLoc(N), VT, V0, V1);
2209
2210 NodeHeights[NewNode] = Height;
2211
2212 int Weight = V0Weight + V1Weight;
2213 Leaves.push(WeightedLeaf(NewNode, Weight, L0.InsertionOrder));
2214
2215 LLVM_DEBUG(dbgs() << "--> Built new node (Weight=" << Weightdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "--> Built new node (Weight="
<< Weight << ",Height=" << Height <<
"):\n"; } } while (false)
2216 << ",Height=" << Height << "):\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "--> Built new node (Weight="
<< Weight << ",Height=" << Height <<
"):\n"; } } while (false)
;
2217 LLVM_DEBUG(NewNode.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { NewNode.dump(); } } while (false)
;
2218 }
2219
2220 assert(Leaves.size() == 1)((Leaves.size() == 1) ? static_cast<void> (0) : __assert_fail
("Leaves.size() == 1", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 2220, __PRETTY_FUNCTION__))
;
2221 SDValue NewRoot = Leaves.top().Value;
2222
2223 assert(NodeHeights.count(NewRoot))((NodeHeights.count(NewRoot)) ? static_cast<void> (0) :
__assert_fail ("NodeHeights.count(NewRoot)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Hexagon/HexagonISelDAGToDAG.cpp"
, 2223, __PRETTY_FUNCTION__))
;
2224 int Height = NodeHeights[NewRoot];
2225
2226 // Restore SHL if we earlier converted it to a MUL
2227 if (NewRoot.getOpcode() == ISD::MUL) {
2228 ConstantSDNode *V1C = dyn_cast<ConstantSDNode>(NewRoot.getOperand(1));
2229 if (V1C && V1C->getAPIntValue().isPowerOf2()) {
2230 EVT VT = NewRoot.getValueType();
2231 SDValue V0 = NewRoot.getOperand(0);
2232 NewRoot = CurDAG->getNode(
2233 ISD::SHL, SDLoc(NewRoot), VT, V0,
2234 CurDAG->getConstant(
2235 V1C->getAPIntValue().logBase2(), SDLoc(NewRoot),
2236 TLI.getScalarShiftAmountTy(DL, V0.getValueType())));
2237 }
2238 }
2239
2240 if (N != NewRoot.getNode()) {
2241 LLVM_DEBUG(dbgs() << "--> Root is now: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "--> Root is now: "; }
} while (false)
;
2242 LLVM_DEBUG(NewRoot.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { NewRoot.dump(); } } while (false)
;
2243
2244 // Replace all uses of old root by new root
2245 CurDAG->ReplaceAllUsesWith(N, NewRoot.getNode());
2246 // Mark that we have RAUW'd N
2247 RootWeights[N] = -2;
2248 } else {
2249 LLVM_DEBUG(dbgs() << "--> Root unchanged.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "--> Root unchanged.\n"
; } } while (false)
;
2250 }
2251
2252 RootWeights[NewRoot.getNode()] = Leaves.top().Weight;
2253 RootHeights[NewRoot.getNode()] = Height;
2254
2255 return NewRoot;
2256}
2257
2258void HexagonDAGToDAGISel::rebalanceAddressTrees() {
2259 for (auto I = CurDAG->allnodes_begin(), E = CurDAG->allnodes_end(); I != E;) {
2260 SDNode *N = &*I++;
2261 if (N->getOpcode() != ISD::LOAD && N->getOpcode() != ISD::STORE)
2262 continue;
2263
2264 SDValue BasePtr = cast<MemSDNode>(N)->getBasePtr();
2265 if (BasePtr.getOpcode() != ISD::ADD)
2266 continue;
2267
2268 // We've already processed this node
2269 if (RootWeights.count(BasePtr.getNode()))
2270 continue;
2271
2272 LLVM_DEBUG(dbgs() << "** Rebalancing address calculation in node: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "** Rebalancing address calculation in node: "
; } } while (false)
;
2273 LLVM_DEBUG(N->dump(CurDAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { N->dump(CurDAG); } } while (false)
;
2274
2275 // FindRoots
2276 SmallVector<SDNode *, 4> Worklist;
2277
2278 Worklist.push_back(BasePtr.getOperand(0).getNode());
2279 Worklist.push_back(BasePtr.getOperand(1).getNode());
2280
2281 while (!Worklist.empty()) {
2282 SDNode *N = Worklist.pop_back_val();
2283 unsigned Opcode = N->getOpcode();
2284
2285 if (!isOpcodeHandled(N))
2286 continue;
2287
2288 Worklist.push_back(N->getOperand(0).getNode());
2289 Worklist.push_back(N->getOperand(1).getNode());
2290
2291 // Not a root if it has only one use and same opcode as its parent
2292 if (N->hasOneUse() && Opcode == N->use_begin()->getOpcode())
2293 continue;
2294
2295 // This root node has already been processed
2296 if (RootWeights.count(N))
2297 continue;
2298
2299 RootWeights[N] = -1;
2300 }
2301
2302 // Balance node itself
2303 RootWeights[BasePtr.getNode()] = -1;
2304 SDValue NewBasePtr = balanceSubTree(BasePtr.getNode(), /*TopLevel=*/ true);
2305
2306 if (N->getOpcode() == ISD::LOAD)
2307 N = CurDAG->UpdateNodeOperands(N, N->getOperand(0),
2308 NewBasePtr, N->getOperand(2));
2309 else
2310 N = CurDAG->UpdateNodeOperands(N, N->getOperand(0), N->getOperand(1),
2311 NewBasePtr, N->getOperand(3));
2312
2313 LLVM_DEBUG(dbgs() << "--> Final node: ")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { dbgs() << "--> Final node: "; } }
while (false)
;
2314 LLVM_DEBUG(N->dump(CurDAG))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("hexagon-isel")) { N->dump(CurDAG); } } while (false)
;
2315 }
2316
2317 CurDAG->RemoveDeadNodes();
2318 GAUsesInFunction.clear();
2319 RootHeights.clear();
2320 RootWeights.clear();
2321}

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h

1//===-- llvm/Support/MathExtras.h - Useful math functions -------*- 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 contains some functions that are useful for math stuff.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_SUPPORT_MATHEXTRAS_H
14#define LLVM_SUPPORT_MATHEXTRAS_H
15
16#include "llvm/Support/Compiler.h"
17#include <algorithm>
18#include <cassert>
19#include <climits>
20#include <cmath>
21#include <cstdint>
22#include <cstring>
23#include <limits>
24#include <type_traits>
25
26#ifdef __ANDROID_NDK__
27#include <android/api-level.h>
28#endif
29
30#ifdef _MSC_VER
31// Declare these intrinsics manually rather including intrin.h. It's very
32// expensive, and MathExtras.h is popular.
33// #include <intrin.h>
34extern "C" {
35unsigned char _BitScanForward(unsigned long *_Index, unsigned long _Mask);
36unsigned char _BitScanForward64(unsigned long *_Index, unsigned __int64 _Mask);
37unsigned char _BitScanReverse(unsigned long *_Index, unsigned long _Mask);
38unsigned char _BitScanReverse64(unsigned long *_Index, unsigned __int64 _Mask);
39}
40#endif
41
42namespace llvm {
43
44/// The behavior an operation has on an input of 0.
45enum ZeroBehavior {
46 /// The returned value is undefined.
47 ZB_Undefined,
48 /// The returned value is numeric_limits<T>::max()
49 ZB_Max,
50 /// The returned value is numeric_limits<T>::digits
51 ZB_Width
52};
53
54/// Mathematical constants.
55namespace numbers {
56// TODO: Track C++20 std::numbers.
57// TODO: Favor using the hexadecimal FP constants (requires C++17).
58constexpr double e = 2.7182818284590452354, // (0x1.5bf0a8b145749P+1) https://oeis.org/A001113
59 egamma = .57721566490153286061, // (0x1.2788cfc6fb619P-1) https://oeis.org/A001620
60 ln2 = .69314718055994530942, // (0x1.62e42fefa39efP-1) https://oeis.org/A002162
61 ln10 = 2.3025850929940456840, // (0x1.24bb1bbb55516P+1) https://oeis.org/A002392
62 log2e = 1.4426950408889634074, // (0x1.71547652b82feP+0)
63 log10e = .43429448190325182765, // (0x1.bcb7b1526e50eP-2)
64 pi = 3.1415926535897932385, // (0x1.921fb54442d18P+1) https://oeis.org/A000796
65 inv_pi = .31830988618379067154, // (0x1.45f306bc9c883P-2) https://oeis.org/A049541
66 sqrtpi = 1.7724538509055160273, // (0x1.c5bf891b4ef6bP+0) https://oeis.org/A002161
67 inv_sqrtpi = .56418958354775628695, // (0x1.20dd750429b6dP-1) https://oeis.org/A087197
68 sqrt2 = 1.4142135623730950488, // (0x1.6a09e667f3bcdP+0) https://oeis.org/A00219
69 inv_sqrt2 = .70710678118654752440, // (0x1.6a09e667f3bcdP-1)
70 sqrt3 = 1.7320508075688772935, // (0x1.bb67ae8584caaP+0) https://oeis.org/A002194
71 inv_sqrt3 = .57735026918962576451, // (0x1.279a74590331cP-1)
72 phi = 1.6180339887498948482; // (0x1.9e3779b97f4a8P+0) https://oeis.org/A001622
73constexpr float ef = 2.71828183F, // (0x1.5bf0a8P+1) https://oeis.org/A001113
74 egammaf = .577215665F, // (0x1.2788d0P-1) https://oeis.org/A001620
75 ln2f = .693147181F, // (0x1.62e430P-1) https://oeis.org/A002162
76 ln10f = 2.30258509F, // (0x1.26bb1cP+1) https://oeis.org/A002392
77 log2ef = 1.44269504F, // (0x1.715476P+0)
78 log10ef = .434294482F, // (0x1.bcb7b2P-2)
79 pif = 3.14159265F, // (0x1.921fb6P+1) https://oeis.org/A000796
80 inv_pif = .318309886F, // (0x1.45f306P-2) https://oeis.org/A049541
81 sqrtpif = 1.77245385F, // (0x1.c5bf8aP+0) https://oeis.org/A002161
82 inv_sqrtpif = .564189584F, // (0x1.20dd76P-1) https://oeis.org/A087197
83 sqrt2f = 1.41421356F, // (0x1.6a09e6P+0) https://oeis.org/A002193
84 inv_sqrt2f = .707106781F, // (0x1.6a09e6P-1)
85 sqrt3f = 1.73205081F, // (0x1.bb67aeP+0) https://oeis.org/A002194
86 inv_sqrt3f = .577350269F, // (0x1.279a74P-1)
87 phif = 1.61803399F; // (0x1.9e377aP+0) https://oeis.org/A001622
88} // namespace numbers
89
90namespace detail {
91template <typename T, std::size_t SizeOfT> struct TrailingZerosCounter {
92 static unsigned count(T Val, ZeroBehavior) {
93 if (!Val)
94 return std::numeric_limits<T>::digits;
95 if (Val & 0x1)
96 return 0;
97
98 // Bisection method.
99 unsigned ZeroBits = 0;
100 T Shift = std::numeric_limits<T>::digits >> 1;
101 T Mask = std::numeric_limits<T>::max() >> Shift;
102 while (Shift) {
103 if ((Val & Mask) == 0) {
104 Val >>= Shift;
105 ZeroBits |= Shift;
106 }
107 Shift >>= 1;
108 Mask >>= Shift;
109 }
110 return ZeroBits;
111 }
112};
113
114#if defined(__GNUC__4) || defined(_MSC_VER)
115template <typename T> struct TrailingZerosCounter<T, 4> {
116 static unsigned count(T Val, ZeroBehavior ZB) {
117 if (ZB
19.1
'ZB' is not equal to ZB_Undefined
19.1
'ZB' is not equal to ZB_Undefined
!= ZB_Undefined && Val == 0)
20
Assuming 'Val' is equal to 0
21
Taking true branch
118 return 32;
22
Returning the value 32
119
120#if __has_builtin(__builtin_ctz)1 || defined(__GNUC__4)
121 return __builtin_ctz(Val);
122#elif defined(_MSC_VER)
123 unsigned long Index;
124 _BitScanForward(&Index, Val);
125 return Index;
126#endif
127 }
128};
129
130#if !defined(_MSC_VER) || defined(_M_X64)
131template <typename T> struct TrailingZerosCounter<T, 8> {
132 static unsigned count(T Val, ZeroBehavior ZB) {
133 if (ZB != ZB_Undefined && Val == 0)
134 return 64;
135
136#if __has_builtin(__builtin_ctzll)1 || defined(__GNUC__4)
137 return __builtin_ctzll(Val);
138#elif defined(_MSC_VER)
139 unsigned long Index;
140 _BitScanForward64(&Index, Val);
141 return Index;
142#endif
143 }
144};
145#endif
146#endif
147} // namespace detail
148
149/// Count number of 0's from the least significant bit to the most
150/// stopping at the first 1.
151///
152/// Only unsigned integral types are allowed.
153///
154/// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
155/// valid arguments.
156template <typename T>
157unsigned countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
158 static_assert(std::numeric_limits<T>::is_integer &&
159 !std::numeric_limits<T>::is_signed,
160 "Only unsigned integral types are allowed.");
161 return llvm::detail::TrailingZerosCounter<T, sizeof(T)>::count(Val, ZB);
19
Calling 'TrailingZerosCounter::count'
23
Returning from 'TrailingZerosCounter::count'
24
Returning the value 32
162}
163
164namespace detail {
165template <typename T, std::size_t SizeOfT> struct LeadingZerosCounter {
166 static unsigned count(T Val, ZeroBehavior) {
167 if (!Val)
168 return std::numeric_limits<T>::digits;
169
170 // Bisection method.
171 unsigned ZeroBits = 0;
172 for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
173 T Tmp = Val >> Shift;
174 if (Tmp)
175 Val = Tmp;
176 else
177 ZeroBits |= Shift;
178 }
179 return ZeroBits;
180 }
181};
182
183#if defined(__GNUC__4) || defined(_MSC_VER)
184template <typename T> struct LeadingZerosCounter<T, 4> {
185 static unsigned count(T Val, ZeroBehavior ZB) {
186 if (ZB != ZB_Undefined && Val == 0)
187 return 32;
188
189#if __has_builtin(__builtin_clz)1 || defined(__GNUC__4)
190 return __builtin_clz(Val);
191#elif defined(_MSC_VER)
192 unsigned long Index;
193 _BitScanReverse(&Index, Val);
194 return Index ^ 31;
195#endif
196 }
197};
198
199#if !defined(_MSC_VER) || defined(_M_X64)
200template <typename T> struct LeadingZerosCounter<T, 8> {
201 static unsigned count(T Val, ZeroBehavior ZB) {
202 if (ZB != ZB_Undefined && Val == 0)
203 return 64;
204
205#if __has_builtin(__builtin_clzll)1 || defined(__GNUC__4)
206 return __builtin_clzll(Val);
207#elif defined(_MSC_VER)
208 unsigned long Index;
209 _BitScanReverse64(&Index, Val);
210 return Index ^ 63;
211#endif
212 }
213};
214#endif
215#endif
216} // namespace detail
217
218/// Count number of 0's from the most significant bit to the least
219/// stopping at the first 1.
220///
221/// Only unsigned integral types are allowed.
222///
223/// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
224/// valid arguments.
225template <typename T>
226unsigned countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
227 static_assert(std::numeric_limits<T>::is_integer &&
228 !std::numeric_limits<T>::is_signed,
229 "Only unsigned integral types are allowed.");
230 return llvm::detail::LeadingZerosCounter<T, sizeof(T)>::count(Val, ZB);
231}
232
233/// Get the index of the first set bit starting from the least
234/// significant bit.
235///
236/// Only unsigned integral types are allowed.
237///
238/// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
239/// valid arguments.
240template <typename T> T findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) {
241 if (ZB == ZB_Max && Val == 0)
242 return std::numeric_limits<T>::max();
243
244 return countTrailingZeros(Val, ZB_Undefined);
245}
246
247/// Create a bitmask with the N right-most bits set to 1, and all other
248/// bits set to 0. Only unsigned types are allowed.
249template <typename T> T maskTrailingOnes(unsigned N) {
250 static_assert(std::is_unsigned<T>::value, "Invalid type!");
251 const unsigned Bits = CHAR_BIT8 * sizeof(T);
252 assert(N <= Bits && "Invalid bit index")((N <= Bits && "Invalid bit index") ? static_cast<
void> (0) : __assert_fail ("N <= Bits && \"Invalid bit index\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 252, __PRETTY_FUNCTION__))
;
253 return N == 0 ? 0 : (T(-1) >> (Bits - N));
254}
255
256/// Create a bitmask with the N left-most bits set to 1, and all other
257/// bits set to 0. Only unsigned types are allowed.
258template <typename T> T maskLeadingOnes(unsigned N) {
259 return ~maskTrailingOnes<T>(CHAR_BIT8 * sizeof(T) - N);
260}
261
262/// Create a bitmask with the N right-most bits set to 0, and all other
263/// bits set to 1. Only unsigned types are allowed.
264template <typename T> T maskTrailingZeros(unsigned N) {
265 return maskLeadingOnes<T>(CHAR_BIT8 * sizeof(T) - N);
266}
267
268/// Create a bitmask with the N left-most bits set to 0, and all other
269/// bits set to 1. Only unsigned types are allowed.
270template <typename T> T maskLeadingZeros(unsigned N) {
271 return maskTrailingOnes<T>(CHAR_BIT8 * sizeof(T) - N);
272}
273
274/// Get the index of the last set bit starting from the least
275/// significant bit.
276///
277/// Only unsigned integral types are allowed.
278///
279/// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
280/// valid arguments.
281template <typename T> T findLastSet(T Val, ZeroBehavior ZB = ZB_Max) {
282 if (ZB == ZB_Max && Val == 0)
283 return std::numeric_limits<T>::max();
284
285 // Use ^ instead of - because both gcc and llvm can remove the associated ^
286 // in the __builtin_clz intrinsic on x86.
287 return countLeadingZeros(Val, ZB_Undefined) ^
288 (std::numeric_limits<T>::digits - 1);
289}
290
291/// Macro compressed bit reversal table for 256 bits.
292///
293/// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
294static const unsigned char BitReverseTable256[256] = {
295#define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
296#define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
297#define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
298 R6(0), R6(2), R6(1), R6(3)
299#undef R2
300#undef R4
301#undef R6
302};
303
304/// Reverse the bits in \p Val.
305template <typename T>
306T reverseBits(T Val) {
307 unsigned char in[sizeof(Val)];
308 unsigned char out[sizeof(Val)];
309 std::memcpy(in, &Val, sizeof(Val));
310 for (unsigned i = 0; i < sizeof(Val); ++i)
311 out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
312 std::memcpy(&Val, out, sizeof(Val));
313 return Val;
314}
315
316// NOTE: The following support functions use the _32/_64 extensions instead of
317// type overloading so that signed and unsigned integers can be used without
318// ambiguity.
319
320/// Return the high 32 bits of a 64 bit value.
321constexpr inline uint32_t Hi_32(uint64_t Value) {
322 return static_cast<uint32_t>(Value >> 32);
323}
324
325/// Return the low 32 bits of a 64 bit value.
326constexpr inline uint32_t Lo_32(uint64_t Value) {
327 return static_cast<uint32_t>(Value);
328}
329
330/// Make a 64-bit integer from a high / low pair of 32-bit integers.
331constexpr inline uint64_t Make_64(uint32_t High, uint32_t Low) {
332 return ((uint64_t)High << 32) | (uint64_t)Low;
333}
334
335/// Checks if an integer fits into the given bit width.
336template <unsigned N> constexpr inline bool isInt(int64_t x) {
337 return N >= 64 || (-(INT64_C(1)1L<<(N-1)) <= x && x < (INT64_C(1)1L<<(N-1)));
338}
339// Template specializations to get better code for common cases.
340template <> constexpr inline bool isInt<8>(int64_t x) {
341 return static_cast<int8_t>(x) == x;
342}
343template <> constexpr inline bool isInt<16>(int64_t x) {
344 return static_cast<int16_t>(x) == x;
345}
346template <> constexpr inline bool isInt<32>(int64_t x) {
347 return static_cast<int32_t>(x) == x;
348}
349
350/// Checks if a signed integer is an N bit number shifted left by S.
351template <unsigned N, unsigned S>
352constexpr inline bool isShiftedInt(int64_t x) {
353 static_assert(
354 N > 0, "isShiftedInt<0> doesn't make sense (refers to a 0-bit number.");
355 static_assert(N + S <= 64, "isShiftedInt<N, S> with N + S > 64 is too wide.");
356 return isInt<N + S>(x) && (x % (UINT64_C(1)1UL << S) == 0);
357}
358
359/// Checks if an unsigned integer fits into the given bit width.
360///
361/// This is written as two functions rather than as simply
362///
363/// return N >= 64 || X < (UINT64_C(1) << N);
364///
365/// to keep MSVC from (incorrectly) warning on isUInt<64> that we're shifting
366/// left too many places.
367template <unsigned N>
368constexpr inline std::enable_if_t<(N < 64), bool> isUInt(uint64_t X) {
369 static_assert(N > 0, "isUInt<0> doesn't make sense");
370 return X < (UINT64_C(1)1UL << (N));
371}
372template <unsigned N>
373constexpr inline std::enable_if_t<N >= 64, bool> isUInt(uint64_t X) {
374 return true;
375}
376
377// Template specializations to get better code for common cases.
378template <> constexpr inline bool isUInt<8>(uint64_t x) {
379 return static_cast<uint8_t>(x) == x;
380}
381template <> constexpr inline bool isUInt<16>(uint64_t x) {
382 return static_cast<uint16_t>(x) == x;
383}
384template <> constexpr inline bool isUInt<32>(uint64_t x) {
385 return static_cast<uint32_t>(x) == x;
386}
387
388/// Checks if a unsigned integer is an N bit number shifted left by S.
389template <unsigned N, unsigned S>
390constexpr inline bool isShiftedUInt(uint64_t x) {
391 static_assert(
392 N > 0, "isShiftedUInt<0> doesn't make sense (refers to a 0-bit number)");
393 static_assert(N + S <= 64,
394 "isShiftedUInt<N, S> with N + S > 64 is too wide.");
395 // Per the two static_asserts above, S must be strictly less than 64. So
396 // 1 << S is not undefined behavior.
397 return isUInt<N + S>(x) && (x % (UINT64_C(1)1UL << S) == 0);
398}
399
400/// Gets the maximum value for a N-bit unsigned integer.
401inline uint64_t maxUIntN(uint64_t N) {
402 assert(N > 0 && N <= 64 && "integer width out of range")((N > 0 && N <= 64 && "integer width out of range"
) ? static_cast<void> (0) : __assert_fail ("N > 0 && N <= 64 && \"integer width out of range\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 402, __PRETTY_FUNCTION__))
;
403
404 // uint64_t(1) << 64 is undefined behavior, so we can't do
405 // (uint64_t(1) << N) - 1
406 // without checking first that N != 64. But this works and doesn't have a
407 // branch.
408 return UINT64_MAX(18446744073709551615UL) >> (64 - N);
409}
410
411/// Gets the minimum value for a N-bit signed integer.
412inline int64_t minIntN(int64_t N) {
413 assert(N > 0 && N <= 64 && "integer width out of range")((N > 0 && N <= 64 && "integer width out of range"
) ? static_cast<void> (0) : __assert_fail ("N > 0 && N <= 64 && \"integer width out of range\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 413, __PRETTY_FUNCTION__))
;
414
415 return -(UINT64_C(1)1UL<<(N-1));
416}
417
418/// Gets the maximum value for a N-bit signed integer.
419inline int64_t maxIntN(int64_t N) {
420 assert(N > 0 && N <= 64 && "integer width out of range")((N > 0 && N <= 64 && "integer width out of range"
) ? static_cast<void> (0) : __assert_fail ("N > 0 && N <= 64 && \"integer width out of range\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 420, __PRETTY_FUNCTION__))
;
421
422 // This relies on two's complement wraparound when N == 64, so we convert to
423 // int64_t only at the very end to avoid UB.
424 return (UINT64_C(1)1UL << (N - 1)) - 1;
425}
426
427/// Checks if an unsigned integer fits into the given (dynamic) bit width.
428inline bool isUIntN(unsigned N, uint64_t x) {
429 return N >= 64 || x <= maxUIntN(N);
430}
431
432/// Checks if an signed integer fits into the given (dynamic) bit width.
433inline bool isIntN(unsigned N, int64_t x) {
434 return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N));
435}
436
437/// Return true if the argument is a non-empty sequence of ones starting at the
438/// least significant bit with the remainder zero (32 bit version).
439/// Ex. isMask_32(0x0000FFFFU) == true.
440constexpr inline bool isMask_32(uint32_t Value) {
441 return Value && ((Value + 1) & Value) == 0;
442}
443
444/// Return true if the argument is a non-empty sequence of ones starting at the
445/// least significant bit with the remainder zero (64 bit version).
446constexpr inline bool isMask_64(uint64_t Value) {
447 return Value && ((Value + 1) & Value) == 0;
448}
449
450/// Return true if the argument contains a non-empty sequence of ones with the
451/// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true.
452constexpr inline bool isShiftedMask_32(uint32_t Value) {
453 return Value && isMask_32((Value - 1) | Value);
454}
455
456/// Return true if the argument contains a non-empty sequence of ones with the
457/// remainder zero (64 bit version.)
458constexpr inline bool isShiftedMask_64(uint64_t Value) {
459 return Value && isMask_64((Value - 1) | Value);
460}
461
462/// Return true if the argument is a power of two > 0.
463/// Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)
464constexpr inline bool isPowerOf2_32(uint32_t Value) {
465 return Value && !(Value & (Value - 1));
466}
467
468/// Return true if the argument is a power of two > 0 (64 bit edition.)
469constexpr inline bool isPowerOf2_64(uint64_t Value) {
470 return Value && !(Value & (Value - 1));
471}
472
473/// Count the number of ones from the most significant bit to the first
474/// zero bit.
475///
476/// Ex. countLeadingOnes(0xFF0FFF00) == 8.
477/// Only unsigned integral types are allowed.
478///
479/// \param ZB the behavior on an input of all ones. Only ZB_Width and
480/// ZB_Undefined are valid arguments.
481template <typename T>
482unsigned countLeadingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
483 static_assert(std::numeric_limits<T>::is_integer &&
484 !std::numeric_limits<T>::is_signed,
485 "Only unsigned integral types are allowed.");
486 return countLeadingZeros<T>(~Value, ZB);
487}
488
489/// Count the number of ones from the least significant bit to the first
490/// zero bit.
491///
492/// Ex. countTrailingOnes(0x00FF00FF) == 8.
493/// Only unsigned integral types are allowed.
494///
495/// \param ZB the behavior on an input of all ones. Only ZB_Width and
496/// ZB_Undefined are valid arguments.
497template <typename T>
498unsigned countTrailingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
499 static_assert(std::numeric_limits<T>::is_integer &&
500 !std::numeric_limits<T>::is_signed,
501 "Only unsigned integral types are allowed.");
502 return countTrailingZeros<T>(~Value, ZB);
503}
504
505namespace detail {
506template <typename T, std::size_t SizeOfT> struct PopulationCounter {
507 static unsigned count(T Value) {
508 // Generic version, forward to 32 bits.
509 static_assert(SizeOfT <= 4, "Not implemented!");
510#if defined(__GNUC__4)
511 return __builtin_popcount(Value);
512#else
513 uint32_t v = Value;
514 v = v - ((v >> 1) & 0x55555555);
515 v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
516 return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
517#endif
518 }
519};
520
521template <typename T> struct PopulationCounter<T, 8> {
522 static unsigned count(T Value) {
523#if defined(__GNUC__4)
524 return __builtin_popcountll(Value);
525#else
526 uint64_t v = Value;
527 v = v - ((v >> 1) & 0x5555555555555555ULL);
528 v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);
529 v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
530 return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56);
531#endif
532 }
533};
534} // namespace detail
535
536/// Count the number of set bits in a value.
537/// Ex. countPopulation(0xF000F000) = 8
538/// Returns 0 if the word is zero.
539template <typename T>
540inline unsigned countPopulation(T Value) {
541 static_assert(std::numeric_limits<T>::is_integer &&
542 !std::numeric_limits<T>::is_signed,
543 "Only unsigned integral types are allowed.");
544 return detail::PopulationCounter<T, sizeof(T)>::count(Value);
545}
546
547/// Compile time Log2.
548/// Valid only for positive powers of two.
549template <size_t kValue> constexpr inline size_t CTLog2() {
550 static_assert(kValue > 0 && llvm::isPowerOf2_64(kValue),
551 "Value is not a valid power of 2");
552 return 1 + CTLog2<kValue / 2>();
553}
554
555template <> constexpr inline size_t CTLog2<1>() { return 0; }
556
557/// Return the log base 2 of the specified value.
558inline double Log2(double Value) {
559#if defined(__ANDROID_API__) && __ANDROID_API__ < 18
560 return __builtin_log(Value) / __builtin_log(2.0);
561#else
562 return log2(Value);
563#endif
564}
565
566/// Return the floor log base 2 of the specified value, -1 if the value is zero.
567/// (32 bit edition.)
568/// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
569inline unsigned Log2_32(uint32_t Value) {
570 return 31 - countLeadingZeros(Value);
571}
572
573/// Return the floor log base 2 of the specified value, -1 if the value is zero.
574/// (64 bit edition.)
575inline unsigned Log2_64(uint64_t Value) {
576 return 63 - countLeadingZeros(Value);
577}
578
579/// Return the ceil log base 2 of the specified value, 32 if the value is zero.
580/// (32 bit edition).
581/// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
582inline unsigned Log2_32_Ceil(uint32_t Value) {
583 return 32 - countLeadingZeros(Value - 1);
584}
585
586/// Return the ceil log base 2 of the specified value, 64 if the value is zero.
587/// (64 bit edition.)
588inline unsigned Log2_64_Ceil(uint64_t Value) {
589 return 64 - countLeadingZeros(Value - 1);
590}
591
592/// Return the greatest common divisor of the values using Euclid's algorithm.
593template <typename T>
594inline T greatestCommonDivisor(T A, T B) {
595 while (B) {
596 T Tmp = B;
597 B = A % B;
598 A = Tmp;
599 }
600 return A;
601}
602
603inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) {
604 return greatestCommonDivisor<uint64_t>(A, B);
605}
606
607/// This function takes a 64-bit integer and returns the bit equivalent double.
608inline double BitsToDouble(uint64_t Bits) {
609 double D;
610 static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
611 memcpy(&D, &Bits, sizeof(Bits));
612 return D;
613}
614
615/// This function takes a 32-bit integer and returns the bit equivalent float.
616inline float BitsToFloat(uint32_t Bits) {
617 float F;
618 static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
619 memcpy(&F, &Bits, sizeof(Bits));
620 return F;
621}
622
623/// This function takes a double and returns the bit equivalent 64-bit integer.
624/// Note that copying doubles around changes the bits of NaNs on some hosts,
625/// notably x86, so this routine cannot be used if these bits are needed.
626inline uint64_t DoubleToBits(double Double) {
627 uint64_t Bits;
628 static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
629 memcpy(&Bits, &Double, sizeof(Double));
630 return Bits;
631}
632
633/// This function takes a float and returns the bit equivalent 32-bit integer.
634/// Note that copying floats around changes the bits of NaNs on some hosts,
635/// notably x86, so this routine cannot be used if these bits are needed.
636inline uint32_t FloatToBits(float Float) {
637 uint32_t Bits;
638 static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
639 memcpy(&Bits, &Float, sizeof(Float));
640 return Bits;
641}
642
643/// A and B are either alignments or offsets. Return the minimum alignment that
644/// may be assumed after adding the two together.
645constexpr inline uint64_t MinAlign(uint64_t A, uint64_t B) {
646 // The largest power of 2 that divides both A and B.
647 //
648 // Replace "-Value" by "1+~Value" in the following commented code to avoid
649 // MSVC warning C4146
650 // return (A | B) & -(A | B);
651 return (A | B) & (1 + ~(A | B));
652}
653
654/// Returns the next power of two (in 64-bits) that is strictly greater than A.
655/// Returns zero on overflow.
656inline uint64_t NextPowerOf2(uint64_t A) {
657 A |= (A >> 1);
658 A |= (A >> 2);
659 A |= (A >> 4);
660 A |= (A >> 8);
661 A |= (A >> 16);
662 A |= (A >> 32);
663 return A + 1;
664}
665
666/// Returns the power of two which is less than or equal to the given value.
667/// Essentially, it is a floor operation across the domain of powers of two.
668inline uint64_t PowerOf2Floor(uint64_t A) {
669 if (!A) return 0;
670 return 1ull << (63 - countLeadingZeros(A, ZB_Undefined));
671}
672
673/// Returns the power of two which is greater than or equal to the given value.
674/// Essentially, it is a ceil operation across the domain of powers of two.
675inline uint64_t PowerOf2Ceil(uint64_t A) {
676 if (!A)
677 return 0;
678 return NextPowerOf2(A - 1);
679}
680
681/// Returns the next integer (mod 2**64) that is greater than or equal to
682/// \p Value and is a multiple of \p Align. \p Align must be non-zero.
683///
684/// If non-zero \p Skew is specified, the return value will be a minimal
685/// integer that is greater than or equal to \p Value and equal to
686/// \p Align * N + \p Skew for some integer N. If \p Skew is larger than
687/// \p Align, its value is adjusted to '\p Skew mod \p Align'.
688///
689/// Examples:
690/// \code
691/// alignTo(5, 8) = 8
692/// alignTo(17, 8) = 24
693/// alignTo(~0LL, 8) = 0
694/// alignTo(321, 255) = 510
695///
696/// alignTo(5, 8, 7) = 7
697/// alignTo(17, 8, 1) = 17
698/// alignTo(~0LL, 8, 3) = 3
699/// alignTo(321, 255, 42) = 552
700/// \endcode
701inline uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
702 assert(Align != 0u && "Align can't be 0.")((Align != 0u && "Align can't be 0.") ? static_cast<
void> (0) : __assert_fail ("Align != 0u && \"Align can't be 0.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 702, __PRETTY_FUNCTION__))
;
703 Skew %= Align;
704 return (Value + Align - 1 - Skew) / Align * Align + Skew;
705}
706
707/// Returns the next integer (mod 2**64) that is greater than or equal to
708/// \p Value and is a multiple of \c Align. \c Align must be non-zero.
709template <uint64_t Align> constexpr inline uint64_t alignTo(uint64_t Value) {
710 static_assert(Align != 0u, "Align must be non-zero");
711 return (Value + Align - 1) / Align * Align;
712}
713
714/// Returns the integer ceil(Numerator / Denominator).
715inline uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) {
716 return alignTo(Numerator, Denominator) / Denominator;
717}
718
719/// Returns the integer nearest(Numerator / Denominator).
720inline uint64_t divideNearest(uint64_t Numerator, uint64_t Denominator) {
721 return (Numerator + (Denominator / 2)) / Denominator;
722}
723
724/// Returns the largest uint64_t less than or equal to \p Value and is
725/// \p Skew mod \p Align. \p Align must be non-zero
726inline uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
727 assert(Align != 0u && "Align can't be 0.")((Align != 0u && "Align can't be 0.") ? static_cast<
void> (0) : __assert_fail ("Align != 0u && \"Align can't be 0.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 727, __PRETTY_FUNCTION__))
;
728 Skew %= Align;
729 return (Value - Skew) / Align * Align + Skew;
730}
731
732/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
733/// Requires 0 < B <= 32.
734template <unsigned B> constexpr inline int32_t SignExtend32(uint32_t X) {
735 static_assert(B > 0, "Bit width can't be 0.");
736 static_assert(B <= 32, "Bit width out of range.");
737 return int32_t(X << (32 - B)) >> (32 - B);
738}
739
740/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
741/// Requires 0 < B < 32.
742inline int32_t SignExtend32(uint32_t X, unsigned B) {
743 assert(B > 0 && "Bit width can't be 0.")((B > 0 && "Bit width can't be 0.") ? static_cast<
void> (0) : __assert_fail ("B > 0 && \"Bit width can't be 0.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 743, __PRETTY_FUNCTION__))
;
744 assert(B <= 32 && "Bit width out of range.")((B <= 32 && "Bit width out of range.") ? static_cast
<void> (0) : __assert_fail ("B <= 32 && \"Bit width out of range.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 744, __PRETTY_FUNCTION__))
;
745 return int32_t(X << (32 - B)) >> (32 - B);
746}
747
748/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
749/// Requires 0 < B < 64.
750template <unsigned B> constexpr inline int64_t SignExtend64(uint64_t x) {
751 static_assert(B > 0, "Bit width can't be 0.");
752 static_assert(B <= 64, "Bit width out of range.");
753 return int64_t(x << (64 - B)) >> (64 - B);
754}
755
756/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
757/// Requires 0 < B < 64.
758inline int64_t SignExtend64(uint64_t X, unsigned B) {
759 assert(B > 0 && "Bit width can't be 0.")((B > 0 && "Bit width can't be 0.") ? static_cast<
void> (0) : __assert_fail ("B > 0 && \"Bit width can't be 0.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 759, __PRETTY_FUNCTION__))
;
760 assert(B <= 64 && "Bit width out of range.")((B <= 64 && "Bit width out of range.") ? static_cast
<void> (0) : __assert_fail ("B <= 64 && \"Bit width out of range.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 760, __PRETTY_FUNCTION__))
;
761 return int64_t(X << (64 - B)) >> (64 - B);
762}
763
764/// Subtract two unsigned integers, X and Y, of type T and return the absolute
765/// value of the result.
766template <typename T>
767std::enable_if_t<std::is_unsigned<T>::value, T> AbsoluteDifference(T X, T Y) {
768 return std::max(X, Y) - std::min(X, Y);
769}
770
771/// Add two unsigned integers, X and Y, of type T. Clamp the result to the
772/// maximum representable value of T on overflow. ResultOverflowed indicates if
773/// the result is larger than the maximum representable value of type T.
774template <typename T>
775std::enable_if_t<std::is_unsigned<T>::value, T>
776SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) {
777 bool Dummy;
778 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
779 // Hacker's Delight, p. 29
780 T Z = X + Y;
781 Overflowed = (Z < X || Z < Y);
782 if (Overflowed)
783 return std::numeric_limits<T>::max();
784 else
785 return Z;
786}
787
788/// Multiply two unsigned integers, X and Y, of type T. Clamp the result to the
789/// maximum representable value of T on overflow. ResultOverflowed indicates if
790/// the result is larger than the maximum representable value of type T.
791template <typename T>
792std::enable_if_t<std::is_unsigned<T>::value, T>
793SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) {
794 bool Dummy;
795 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
796
797 // Hacker's Delight, p. 30 has a different algorithm, but we don't use that
798 // because it fails for uint16_t (where multiplication can have undefined
799 // behavior due to promotion to int), and requires a division in addition
800 // to the multiplication.
801
802 Overflowed = false;
803
804 // Log2(Z) would be either Log2Z or Log2Z + 1.
805 // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z
806 // will necessarily be less than Log2Max as desired.
807 int Log2Z = Log2_64(X) + Log2_64(Y);
808 const T Max = std::numeric_limits<T>::max();
809 int Log2Max = Log2_64(Max);
810 if (Log2Z < Log2Max) {
811 return X * Y;
812 }
813 if (Log2Z > Log2Max) {
814 Overflowed = true;
815 return Max;
816 }
817
818 // We're going to use the top bit, and maybe overflow one
819 // bit past it. Multiply all but the bottom bit then add
820 // that on at the end.
821 T Z = (X >> 1) * Y;
822 if (Z & ~(Max >> 1)) {
823 Overflowed = true;
824 return Max;
825 }
826 Z <<= 1;
827 if (X & 1)
828 return SaturatingAdd(Z, Y, ResultOverflowed);
829
830 return Z;
831}
832
833/// Multiply two unsigned integers, X and Y, and add the unsigned integer, A to
834/// the product. Clamp the result to the maximum representable value of T on
835/// overflow. ResultOverflowed indicates if the result is larger than the
836/// maximum representable value of type T.
837template <typename T>
838std::enable_if_t<std::is_unsigned<T>::value, T>
839SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) {
840 bool Dummy;
841 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
842
843 T Product = SaturatingMultiply(X, Y, &Overflowed);
844 if (Overflowed)
845 return Product;
846
847 return SaturatingAdd(A, Product, &Overflowed);
848}
849
850/// Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
851extern const float huge_valf;
852
853
854/// Add two signed integers, computing the two's complement truncated result,
855/// returning true if overflow occured.
856template <typename T>
857std::enable_if_t<std::is_signed<T>::value, T> AddOverflow(T X, T Y, T &Result) {
858#if __has_builtin(__builtin_add_overflow)1
859 return __builtin_add_overflow(X, Y, &Result);
860#else
861 // Perform the unsigned addition.
862 using U = std::make_unsigned_t<T>;
863 const U UX = static_cast<U>(X);
864 const U UY = static_cast<U>(Y);
865 const U UResult = UX + UY;
866
867 // Convert to signed.
868 Result = static_cast<T>(UResult);
869
870 // Adding two positive numbers should result in a positive number.
871 if (X > 0 && Y > 0)
872 return Result <= 0;
873 // Adding two negatives should result in a negative number.
874 if (X < 0 && Y < 0)
875 return Result >= 0;
876 return false;
877#endif
878}
879
880/// Subtract two signed integers, computing the two's complement truncated
881/// result, returning true if an overflow ocurred.
882template <typename T>
883std::enable_if_t<std::is_signed<T>::value, T> SubOverflow(T X, T Y, T &Result) {
884#if __has_builtin(__builtin_sub_overflow)1
885 return __builtin_sub_overflow(X, Y, &Result);
886#else
887 // Perform the unsigned addition.
888 using U = std::make_unsigned_t<T>;
889 const U UX = static_cast<U>(X);
890 const U UY = static_cast<U>(Y);
891 const U UResult = UX - UY;
892
893 // Convert to signed.
894 Result = static_cast<T>(UResult);
895
896 // Subtracting a positive number from a negative results in a negative number.
897 if (X <= 0 && Y > 0)
898 return Result >= 0;
899 // Subtracting a negative number from a positive results in a positive number.
900 if (X >= 0 && Y < 0)
901 return Result <= 0;
902 return false;
903#endif
904}
905
906/// Multiply two signed integers, computing the two's complement truncated
907/// result, returning true if an overflow ocurred.
908template <typename T>
909std::enable_if_t<std::is_signed<T>::value, T> MulOverflow(T X, T Y, T &Result) {
910 // Perform the unsigned multiplication on absolute values.
911 using U = std::make_unsigned_t<T>;
912 const U UX = X < 0 ? (0 - static_cast<U>(X)) : static_cast<U>(X);
913 const U UY = Y < 0 ? (0 - static_cast<U>(Y)) : static_cast<U>(Y);
914 const U UResult = UX * UY;
915
916 // Convert to signed.
917 const bool IsNegative = (X < 0) ^ (Y < 0);
918 Result = IsNegative ? (0 - UResult) : UResult;
919
920 // If any of the args was 0, result is 0 and no overflow occurs.
921 if (UX == 0 || UY == 0)
922 return false;
923
924 // UX and UY are in [1, 2^n], where n is the number of digits.
925 // Check how the max allowed absolute value (2^n for negative, 2^(n-1) for
926 // positive) divided by an argument compares to the other.
927 if (IsNegative)
928 return UX > (static_cast<U>(std::numeric_limits<T>::max()) + U(1)) / UY;
929 else
930 return UX > (static_cast<U>(std::numeric_limits<T>::max())) / UY;
931}
932
933} // End llvm namespace
934
935#endif